#!/bin/ksh
#PURPOSE: Executes a Unix command over an indexed set of files
#VERSION: 1.1
#AUTHOR: V.A. Sole
#MODIFICATIONS: 2008-10-30 PB "test -f" removed

if [ "$1" = "-help" ];then
    echo 'Usage: ' 
    echo 'loopcmd "unix_command" "format1" indx1 indx2 [indx3] ["format2"] [indx4]]' 
    exit 0
fi

#check for the presence of a format
testit="$2"
testit=`echo "$testit" |sed 's/[^%]//g'`
if test -z "$testit";then
   echo "No valid format present"
   flagi1=0
else
   flagi1=1
fi

if test $# -gt 3;then
	unixcmd="$1"
    pf="$2"
	i1=$3
	i2=$4
    i3=1
    pf2=$pf
    i4=$i1
    flagi4=0
    twochains=0
else 
    echo 'Usage: ' 
    echo 'loopcmd unix_command "format1" indx1 indx2 [indx3] ["format2"] [indx4]]' 
    exit 0
fi

if test $# -eq 5;then
    #the increment
    testit="$5"
    testit=`echo $testit |sed 's/[0-9]//g'`
    if test -z "$testit";then
        #echo "This looks like a number"
      i3=$5
    else
        #echo "This does not look like a number"
      i3=1
      twochains=1
        #check for the presence of a format
      pf2="$5"
      testit="$5"
      testit=`echo $testit |sed 's/[^%]//g'`
      if test -z "$testit";then
        flagi4=0
      else
        flagi4=1
        i4=$i1
      fi
    fi
fi

if test $# -eq 6;then
    #the increment
    testit="$5"
    testit=`echo $testit |sed 's/[0-9]//g'`
    if test -z "$testit";then
        #echo "This looks like a number"
      i3=$5
      twochains=1
        #check for the presence of a format
      pf2="$6"
      testit="$6"
      testit=`echo $testit |sed 's/[^%]//g'`
      if test -z "$testit";then
        flagi4=0
      else
        flagi4=1
        i4=$i1
      fi
    else
        #echo "This does not look like a number"
      i3=1
      twochains=1
        #check for the presence of a format
      pf2="$5"
      testit="$5"
      testit=`echo $testit |sed 's/[^%]//g'`
      if test -z "$testit";then
        flagi4=0
      else
        flagi4=1
        i4=$6
      fi
    fi
fi

if test $# -eq 7;then
    twochains=1
    flagi4=1
    i3=$5
    pf2="$6"    
    i4=$7
fi

while test $i1 -le $i2;
do
    if test $twochains -eq 1;then
        if test $flagi4 -eq 1;then
            if test $flagi1 -eq 0;then
            	a=`printf "$pf $pf2" $i4`
            else
            	a=`printf "$pf $pf2" $i1 $i4`
            fi 
        else
            if test $flagi1 -eq 0;then
            	a=`printf "$pf $pf2"`
	    else
            	a=`printf "$pf $pf2" $i1`
	    fi
        fi
    else    
            if test $flagi1 -eq 0;then
       		a=`printf "$pf" `
            else
        	a=`printf "$pf" $i1`            
            fi
    fi
    #echo "$a"
    #echo `printf "Index %d" $i1`
#    if test -f $a;then
        echo `printf "%s %s" "$unixcmd" "$a"`
        $unixcmd $a
#    fi 
	i1=`expr $i1 + $i3`
    i4=`expr $i4 + $i3`

done
