#! /bin/sh
#file: o2grammars.sh
#compile all o2 grammars
#o2=/mnt/c2d0s0/yacco2/bin/o2
# no parms: just gen c++ code per grammar
# parms: -t -err # to also gen Tes or Errors vocabulary
# parms: -p # gen grammar's pdf and ps documents 
o2=/usr/local/yacco2/bin/o2
###o2=/yacco2/bin/o2
dir_only=`pwd` #"/usr/local/yacco2/compiler/grammars"
tmp=/tmp/o2
if [ ! -e "$tmp" ] 
then
  mkdir $tmp
fi
cd $tmp
 
delete_files=1 #clean up the work files in /tmp

sw1=$1
sw2=$2

file_no=$((0))
file_pos=$((1))
cc_lex()
{
  file_name_only="`basename $2`"
  #dir_only=`pwd` #"/usr/local/yacco2/compiler/grammars"
  #echo "%%%%%%%%%%%%%%%%target directory $dir_only"
  #echo "%%%%%%%%%%%%%%%%basename $file_name_only"
  if ! eval "$o2  $sw1 $sw2 $1"
  then
    echo "===================> grammar in error: $1 switch(es): $sw1 $sw2";
    return;
  fi 
  for j in $sw1 $sw2  
  do
    case $j in
    *p)
      eval "mpost $file_name_only.mp"
      eval "cweave $file_name_only.w"
      eval "pdftex $file_name_only.tex"
      xref="$file_name_only""_idx"
      #echo "%%%%%%%%%%%%%%%%% index file: $xref to cweave and pdftex"
      eval "cweave $xref.w"
      eval "pdftex $xref.tex"
      ###pdftops "$file_name_only.pdf"
      ###pdftops "$xref"".pdf"
      eval "cp $xref\.pdf* $dir_only"; #copy gened docs to its gening folder
      ###eval "cp $xref\.ps* $dir_only"; #copy gened docs to its gening folder
      return
    esac
  done
if test $delete_files -eq 1; then
  for k in `ls * `;
  do
   #echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!Casing on $k"
   case $k in
    *.cpp|*.h) 
      eval "cp $k $dir_only/$k";
      #echo "-----Copying--------> $k to $dir_only/$k"
      eval "rm -f $k" 
      ;;
    *.fsc) 
      eval "cp $k $dir_only/$k";
      #echo "-------------> Deleting $k"
      eval "rm -f $k" ;;
    *.scn|*.idx|*.log|*.toc)
      #echo "-------------> Deleting $k"
      eval "rm -f $k" 
      ;;
    Err.w|T.w) # error and terminal documents to be cweave then pdftex printed by xpdf
      #echo "-------------> Deleting $k"
      #eval "rm -f $k" eof
      ;;
    *.w)
      #echo "-------------> Deleting $k"
      #eval "rm -f $k" 
      ;;
    *.tex)
      #echo "-------------> Deleting $k"
      eval "rm -f $k" 
      ;;
    *.mp)
      #echo "-------------> Deleting $k"
      #eval "rm -f $k" 
      ;;
    *.tex1)
      #echo "-------------> Deleting $k"
      eval "rm -f $k" 
      ;;
    *.[1-9])
      #echo "-------------> Deleting Mpost diagrams $k"
      ##eval "rm -f $k" 
      ;;
     *.[1-9][0-9]*)
      #echo "-------------> Deleting Mpost diagrams $k"
      ##eval "rm -f $k"
      ;;
   esac
  done
fi
}

for i in `find $dir_only | grep '.*\.lex$'`;
do
  echo "==========> Grammar to compile: $i with switch(es): $sw1 $sw2" 
  file_no=$((++file_no))
  if test $((file_no)) -ge $((file_pos)); then
    file_no_ext=${i%%.*}
    cc_lex $i $file_no_ext
  fi 
done
cd $dir_only 

