#!/bin/csh -f

if ($#argv == 0) then
  echo Usage: $0 '[list of files to be merged]'  output-file
  exit 0
endif

set d = `date`
set awkprog = /tmp/xxxMpsout-awk.$USER.$d[4]
set scratchfile = /tmp/xxxMpsout.$USER.$d[4]

echo 'BEGIN { FLAG = 0; }' > $awkprog
echo '(FLAG == 1 && $1 == "%" && $2 == "End" && $3 == "mergeinclude") {FLAG = 0;}' >> $awkprog
echo 'FLAG == 1 {print $0;}'  >> $awkprog
echo '(FLAG == 0 && $1 == "%" && $2 == "Begin" && $3 == "mergeinclude") { FLAG = 1; }'  >> $awkprog

# echo 'BEGIN { FLAGBG = 0; }' >> $awkprog
# echo '(FLAGBG == 1 && $1 == "%" && $2 == "End" && $3 == "background") {FLAGBG = 0;}' >> $awkprog
# echo 'FLAGBG == 1 {print $0;}'  >> $awkprog
# echo '(FLAGBG == 0 && $1 == "%" && $2 == "Begin" && $3 == "background") { FLAGBG = 1; }'  >> $awkprog

set n = 1

if ($1 == "--delete") then
  set delete_files = true
  @ n++
else
  set delete_files = false
endif

set ext = ""

foreach f (".eps" "_a4.eps") 
  if (-e $argv[$n]$f) then
    set ext = $f
    break
  endif
end

set outfile = $argv[$#argv]$ext

head -11 $argv[$n]$ext > $outfile
echo -n "" > $scratchfile

while ($n < $#argv)
  set epsfile = $argv[$n]$ext
  awk -f $awkprog  $epsfile >> $outfile
  grep Zpos $epsfile >> $scratchfile
  echo merging $epsfile
  if ($delete_files == true) then
    echo /bin/rm $epsfile
    /bin/rm $epsfile
  endif
  @ n++
end

echo gsave >> $outfile

cat $scratchfile | awk '{printf("%s ",$NF);for(i=1;i<=NF-3;i++)printf("%s ",$i);printf("\n")}' | sort -n | awk '{for(i=2;i<=NF;i++)printf("%s ",$i);printf("\n")}' >> $outfile

echo grestore >> $outfile
echo % End of merged data >> $outfile
echo showpage  >> $outfile

/bin/rm $scratchfile $awkprog

echo to output file $outfile
