# awk program allowing you to supply lots of filenames as parameters

# invoke awk with this as the first program-file, i.e.
#      gawk -f extcmdline -f <myprog> -f <anotherprog> <input1> <input2> ....
# where <myprog> and <anotherprog> are filenames of awk programs and <input1>
# and <input2> (optional, if you're using this program) are filenames of data
# for the awk programs to process

BEGIN{ 
        f="<Wimp$ScrapDir>.awksed.Scrap"
        RS=""
       getline t < f
       split(t,filenames)

       if(tolower(filenames[1])=="#prefix")
         {addtofilepath(filenames[2])
          getline t < f
          split(t,filenames) }

# you can supply an optional first line reading #Prefix <directory name>
# and the filenames on the next lines will be searched for in that
# directory, e.g. a scrap file containing
# "#Prefix ADFS::0.$.Books
#
#  Emma
#  Excession
#  Dragonsong"
# will cause files ADFS::0.$.Books.Emma, ADFS::0.$.Books.Excession and
# ADFS::0.$.Books.Dragonsong to be used as input.

       close(f)
       for(i in filenames)
         {
          ARGV[ARGIND+i]=filenames[i]
          count++
         }
      if (count==0 || tolower(filenames[1]) ~ "#prefix")
# count==0 if file was empty
# filenames[1] ~ #prefix when file contains a prefix line *only*
        {ERRNO="list of input filenames not found"
         exit }
      ARGC=count+1
      RS="\n"
      }


# this should prevent other exit statements from being carried out
# - provided that this file is invoked first in the command-line arguments.
END{
     system("SetMacro File$Path " oldfilepath)
#attempt to restore File$Path
     if(ERRNO>0)
         {print ERRNO > "/dev/stderr"
         exit 1}
    }

function sysvar(s,  f,t)
{ f= "Pipe:$.V"
 system("echo <" s "> { > " f"  }")
 getline t < f
 close(f)
 return t 
}

function addtofilepath(pathname,  temp)
{ RS=" "
# this seems to be the only way to restore normal output concatentation
 temp=gensub(/[$(]/,"\\\\&","g",pathname)
  oldfilepath=sysvar("File$Path")
  if(oldfilepath !~ temp )
    {
    system("SetMacro File$Path " oldfilepath pathname ".,")
   # print sysvar("File$Path")
     }
   # else print "No change"
 RS=""
}