#!/bin/sh
#
# This script is a part of ChiTeX
# By Hung-Yih Chen    
#           Last updated  Jan. 20, 2000
#
#                All rights preserved   
#
# This script is used to compile  and preview('dvips and ghostview') 
# both chinese (Big5/GB) plain TeX or LaTeX source file
#
# Usage: chitexpsv [-option [option]] sourcefile
#
#         chitexpsv math2   (or chitexpsv math2.tex)
# Example:
#         chitexpsv math2   (or chitexpsv math2.tex)
# when you have math2.tex 
#

newchitran="y"

#nottfcheck="y"      # if remove the first character '#' of this line,
                     #   it will not check the change of directories
                     #   of chinese TrueType files. The contents of
                     #   those directories will the the content of
                     #   file 'chitex.fdfile' which define definitions
                     #   of chinese fonts. So if the contents of
                     #   the directories (of chinese TrueType files)
                     #   (.../texmf/fonts/chinese/ttf) is as before,
                     #   then you may do such removing of "#' if
                     #   your system work slowly in shell scripts.
                     # As I know, systems of 'linux' and 'freebsd' works
                     #   quickly in shell scripts, so need not do this
                     #   removing of '#'

#quickmode="y"     
#export quickmode    # if remvove the first character '#' of this and 
                     #   the above line,
                     #   it will not have the utlility of "\filecontents"
                     #   for chinese to accellerlate the speed of
                     #   ChiTeX for some system which works slowly in shell
                     #   scripts
                     # As I know, systems of 'linux' and 'freebsd' works
                     #   quickly in shell scripts, so need not do this
                     #   removing of '#'


gawkbin="gawk"


option="0"; opno="0"

if test "$1" = "-nogv"; then
   Nogv="y"
   shift
fi

if test "$1" = "-big5"; then
   option="big5"; code="big5"
   opno="1"
   codeoption="y"
else
   if test "$1" = "-gb"; then
        option="gb";  code="gb"
        opno="1"
        codeoption="y"
   else 
    if test "$1" = "-e"; then
       option="e"
       opno="1"
       code="big5"
    else
      if test "$1" = "-batch"; then
        option="batch"
        opno="1"
        code="big5"
      else
       if test "$1" = "-nonstop"; then
         option="nonstop"
         opno="1"
         code="big5"
       else
         if test "$1" = "-c"; then    
            option="0"
            opno="1"
            code="big5"
         else
          if test "$1" = "-help"; then  
            option="-help"
            opno="1"
          else
            if test "$1" = "-chitexhelp"; then  
               option="-chitexhelp"
               opno="1"
            else
             if test "$1" = "-pdftex"; then  
                option="-pdftex"
                opno="1"
             else
               option="none"
               code="big5"
               opno="0"
             fi
            fi
          fi
         fi
       fi
      fi
    fi
   fi
fi

if test "$option" = "-chitexhelp"; then
   chitexhelp
   exit


fi

if test "$1" = "-pdftex" -o "$2" = "-pdftex"; then
   opno="3"
fi

if test "$#" = "0" -o "$opno" = "1" -a "$#" = "1" \
     -o "$#" = "2" -a "$codeoptin" = "y" ; then
      option="help"
fi




menu () {
   echo " "; echo " "
   echo "  Usage: chitexdvi [option [option]] sourcefile "
   echo " "
   echo "  where  sourcefile is a TeX/LaTeX source file"
   echo "  option are:"
   echo "  -pdftex  compile with pdftex/pdflatex"
   echo "  -gb      for using in GB encoded chinese"
   echo "           this option must appear as the 1st option"
   echo "           using macro '\GBchinese' in GB encoded chinese"
   echo "           document may omit this option"
   echo "  -big5    for using in Big5 encoded chinese" 
   echo "           this option must appear as the 1st option"
   echo "           default is with option -big5"
   echo "  -e       with error message and .log file non-chineses"
   echo "  -c       with chinese error message and chinese .log file"
   echo "           default is with option -c"
   echo "  -batch   with chinese .log file generated at run time"
   echo "           but without prompt error message which is only suitable"
   echo "           for compiling in 'batchmode' or in 'nonstopmode' and"
   echo "           could spend less time."
#   echo "           There is a command 'chilatexb' which is equivalent to"
#   echo "           'chilatex -batch' and is used for 'lyx'."
   echo "  -nonstop  same as '-batch'"
   echo "  -help    help"
   echo " "
   exit
}

if test "$option" = "help"; then
   menu
fi

if test "$1" = "-pdftex"; then
   pdftex="y"
   export pdftex
   shift
   if test "$1" = "-big5"; then
      option="big5"; code="big5"
      opno="1"
      codeoption="y"
      shift
   else
      if test "$1" = "-gb"; then
         option="big5"; code="gb"
         opno="1"
         codeoption="y"
         shift
      fi
   fi
else  
 if test "$codeoption" = "y"; then
   shift
   if test "$1" = "-pdftex"; then
      pdftex="y"
      export pdftex
      shift
   fi
 fi
fi

if test "$pdftex" = "y"; then
#   virtexbin="pdfvirtex"
   virtexbin="pdftex"
else
   virtexbin="virtex"
fi


#rm -f tmp@

option="0"; opno="0"

if test "$1" = "-e"; then
   option="e"
   opno="1"
else
   if test "$1" = "-batch"; then
        option="batch"
        opno="1"
   else
      if test "$1" = "-nonstop"; then
         option="nonstop"
         opno="1"
      else
         if test "$1" = "-help"; then
            option="help"
            opno="1"
         else
            if test "$1" = "-c"; then    
               option="0"
               opno="1"
            fi
         fi
      fi
   fi
fi


#if [ "$#" = "0" -o "$opno" = "1" -a "$#" = "1" ]; then
if test "$#" = "0" -o "$opno" = "1" -a "$#" = "1"; then
   option="help"
fi



#if [ "$opno" = "1" -a "$#" = "1" ]; then
#   option="help"
#fi


if test "$option" = "help"; then
   menu
fi



if test $# -gt 1; then
if test "$2" = "-e"; then
   option="e"
else
   if test "$2" = "-batch"; then
      option="batch"
   else
      if test "$2" = "-nonstop"; then
         option="nonstop"
      else 
         if test "$2" = "-c"; then    
            option="0"
         fi
      fi
   fi
fi
fi

#if test "$1" = "-e" -o "$1" = "-batch" -o "$1" = "-nonstop" -o "$1" = "-c"
#then
#   shift 1
#fi

#if test "$1" = "-e" -o "$1" = "-batch" -a "$#" = "1"; then
if test "$1" = "-e"; then
    shift 1
else
    if test "$1" = "-batch"; then
       shift 1
    else
       if test "$1" = "-nonstop"; then
          shift 1
       else
          if test "$1" = "-c"; then
             shift 1
          fi
       fi
    fi
fi

searchtexmf="y"
if test "$searchtexmf" = "y"; then
TEXMF=`kpsexpand '$TEXMF'|cut -d! -f 3 `
VARTEXFONTS=`kpsexpand '$VARTEXFONTS' `
if test "$VARTEXFONTS" = ""; then
   VARTEXFONTS=`kpsexpand '$VARFONTS' `
   export VARFONTS
   export VARTEXFONTS
else
   export VARTEXFONTS
fi

#$gawkbin -v texmfcnf=$texmfcnf '

echo "yes" > tmp@
texmfcnffile=`kpsexpand -w cnf texmf.cnf`
TEXMFCNF=`
$gawkbin  '
{texmfcnfloc=index(texmfcnffile,"/texmf.cnf")
 print substr(texmfcnffile,1,texmfcnfloc-1)
}' texmfcnffile=$texmfcnffile tmp@ `

echo $TEXMFCNF > tmp@
TEXMF=`
$gawkbin '
{
  inline=$0
  gsub(/web2c/,"",inline)
  inline=substr(inline,1,length(inline)-1)
  print inline
}' tmp@ `
fi

#TEXMFCNF=$TEXMF/web2c
TTF2PKINPUTS=.:$TEXMF
TTF2TFMINPUTS=.:$TEXMF
TTFONTS=.:$TEXMF/fonts/chinese/ttf//
TFMFONTS=.:$TEXMF/fonts/tfm//:$VARTEXFONTS/tfm//
TEXMFDBS=$TEXMF:$VARTEXFONTS
#TEXINPUTS=.:$TEXMF/tex//
T1FONTS=.:$TEXMF/fonts/type1//:$VARTEXFONTS/type1/fonts//

export TEXMF
export VARTEXFONTS
#export TEXMFCNF
export TTF2PKINPUTS
export TTFONTS
export TTF2TFMINPUTS
export TFMFONTS
export TEXMFDBS
#export TEXINPUTS
export T1FONTS

  if test ! -s $HOME/".NotFirstRun"; then
     echo " "; echo " "
     echo "    **********************************************"
     echo "    *  Your TeX document should be saved in Big5 *"
     echo "    *  or in GB and do not saved in UTF-8        *"
     echo "    *                                            *"
     echo "    *  Ignore this message if your TeX document  *"     
     echo "    *  have been in Big5 or GB                   *"
     echo "    **********************************************"             
     echo "     "
     echo "    Press Enter key to continue to compile"
     echo "    or Press 'Ctrl C' to quit              " 

     echo "yes" > $HOME/".NotFirstRun"

     read xxxxxxxxxxxx
  fi   


if test "$code" = "gb"; then
   GBENV="gbenv"
   export GBENV
else
   GBENV=""   
   export GBENV
fi


fileno=1
export fileno
inputno=0
export inputno
labelcount=0
export labelcount
bitemcount=0
export bitemcount
chitranno=0
export chitranno


if test ! -d .tmp00; then
   mkdir .tmp00
fi


PWD=`pwd`  

/bin/rm -f *@ *.tmp00
if test -s ch@labelfile; then /bin/rm -f  ch@labelfile;fi

#/bin/rm -f *temp@ maintemp*@ maintmp*@ fileb@ *.@@@ *.temp$ *.temp$ trasl*@
#/bin/rm -f addmac*@ filemap@ trancode@ *.tmp00 ch@export* ch@labelfile
#/bin/rm -f setaddpercent@ pfbfile@ chbold@

chbold=
export chbold

if test ! -s $1.tex
then
 if test ! -s $1; then 
   filename=`find $TEXMF/tex -follow -name $1 -print`
   if test "$filename" = ""; then
      filename=`find $TEXMF/tex/ -follow -name $1.tex -print`
      if test "$filename" = ""; then
         exit
      fi
   fi
 else
   filename=$1
 fi
else 
 filename=$1.tex
fi

echo "yes" > tmp@

new="y"
if test "$new" = "y"; then
newfilename=""
newfilename=`
gawk -v filename=$filename -v extno=$extno '
{
 llen=length(filename)
 i=1; chinese=0
 for (i;i<=llen;i++)
   {ch=substr(filename,i)
    if (ch > "\240" && ch < "\372")
       {chinese=1; break}
   } 
 if (chinese==1)
    {
     while (getline inline < ".tmp00/texf.tab">0)
      {++recno
       sp=index(inline," ")
       chfilename=substr(inline,1,sp-1)
       if (filename==chfilename)
          {rinline=substr(inline,sp+1)
           gsub("^ *","",rinline)
           newfname=rinline; found=1
          }
      }        
     close(".tmp00/texf.tab")

     if (found==0)
       {
        if (recno>1000)
          {recno=0; print "yes" > "recnomax@"}
           newfname="m@@ch@" recno+1 "@.tex"
        if (recno>1000)
          {print filename " " newfname > ".tmp00/texf.tab"}
        else
          {print filename " " newfname >> ".tmp00/texf.tab"}
       }
     
     print newfname
    }
}' tmp@ `  


  if test -s recnomax@; then
     echo " "
     echo "  File name table too large. "
     echo "  Please run chitex from the beginning."
     echo " "
  fi

  oldfilename=$filename
  export oldfilename

if test "$newfilename" != ""; then
   cp -f $filename $newfilename
#   oldfilename=$filename
   chinesef=1
   bname=`basename $filename`                    
   oldfilea=`echo $bname|cut -d. -f 1` 
   filename=$newfilename
fi
fi


  bname=`basename $filename`                    
  filea=`echo $bname|cut -d. -f 1` 
  fileb=`echo $bname |cut -d. -f 2`
  filenamea=`echo $filename|cut -d. -f 1`

  filea=$filea
  export filea


echo $filename > texfile@


#if test -s $filea.tex; then
if test -s $filenamea.tex; then
   texfile=$filea.tex
else
   texfile=$filea
fi

# Determine GB' mode if have \GBchinese in source document
#GBchinese=`fgrep "\\\\\\GBchinese" $filename|cut -d% -f 1`
#bgdoc=`fgrep "\\\\\\begin{document}" $filename|cut -d% -f 1`

#if test "$GBchinese" != ""; then
#  if test "$bgdoc" != ""; then
  gbchinese=`
   $gawkbin '
   {
    per=index($0,"%"); 
    if (per >0)
       {inline=substr($0,1,per-1)}
    else
       {inline=$0}
    bgdoc=index(inline,"\134begin{document}")
    if (bgdoc == 0)
       {
        gbchinese=index(inline,"\134GBchinese")
        if (gbchinese > 0)
           {print "y";exit}
       }
    else
       {exit}
   }' $filename  `
#  fi
  
#  if test "$bgdoc" = "" -o "$gbchinese" = "y"; then
  if test "$gbchinese" = "y"; then
   code="gb"  
   GBENV="gbenv"
  else
   code="big5"
   GBENV=""
  fi
  export GBENV

#else
#   code="big5"
#   GBENV=""
#   export GBENV
#fi

##### Check whether the contents of dir.$TEXMF/fonts/chinese/ttf
#     has been changed. If so, then run chitexconfig -chitex.fdf
#####
if test "$nottfcheck" = ""; then
if test -f $VARTEXFONTS/ttf; then rm -f $VARTEXFONTS/ttf; fi
if test ! -d $VARTEXFONTS/ttf; then
    mkdir $VARTEXFONTS/ttf
    chmod a+rw $VARTEXFONTS/ttf
fi

/bin/ls $TEXMF/fonts/chinese/ttf > ttffiletmp
/bin/ls $VARTEXFONTS/ttf >> ttffiletmp
#/bin/ls $VARTEXFONTS/type1/fonts >> ttffiletmp

if test -s $VARTEXFONTS/ttf/ttffile; then
   changettf=`diff ttffiletmp $VARTEXFONTS/ttf/ttffile`
fi

if test "$changettf" != ""; then
   chitexconfig -chitex.fdf
fi
if test -f ttffiletmp; then
   cp -f  ttffiletmp  $VARTEXFONTS/ttf/ttffile
   chmod a+rw $VARTEXFONTS/ttf/ttffile
   /bin/rm -f ttffiletmp
fi
fi # end of nottfcheck

checkfdf="n"
if test "$checkfdf" = "y"; then
##########
# If time of $texmf/tex/chinese/chitex.fdf
#  > $texmf/tex/chinese/chitex.fdfile, or 
#  > $texmf/ttfonts.map, or
#  the contents of dir. $texmf/fonts/chinese/ttf and
#  $VARTEXFONTS/ttf changed, make new chitex.fdfile
#
/bin/ls $TEXMF/fonts/chinese/ttf > ttffiletmp
/bin/ls $VARTEXFONTS/ttf >> ttffiletmp

changettf=`diff ttffiletmp $VARTEXFONTS/ttf/ttffile`

if test "$changettf" != ""; then
   mv ttffiletmp $VARTEXFONTS/ttf/ttffile
   chmod a+w $VARTEXFONTS/ttf/ttffile
   touch $TEXMF/tex/chinese/chitex.fdf
fi
if test -f ttffiletmp; then
   /bin/rm -f ttffiletmp
fi

unixsys=`uname`
case $unixsys in
 "FreeBSD") timeopt="-T";;
 "Linux")   timeopt="--full-time";;
       *)   timeopt="";;
esac

#$gawkbin -v unixsys=$unixsys '

checkfdftime (){
for cmd in "$chitexfdfile" "$chitexfdf" "$TEXMF/ttfonts.map"
do
datestr=`
ls -l $timeopt $cmd| \
$gawkbin  '
BEGIN{
month["Jan"]="01"; month["Feb"]="02"; month["Mar"]="03"
month["Apr"]="04"; month["May"]="05"; month["Jun"]="06"
month["Jul"]="07"; month["Aug"]="08"; month["Sep"]="09"
month["Oct"]="10"; month["Nov"]="11"; month["Dec"]="12"
}
{
 if (unixsys=="SunOS")
  {if ($9 == "")
    {timecol="7"
     timepos=index($7,":")
     if (timepos > 0)
        {timelinetmp=$7;yearlinetmp="3000"}
     else
        {timelinetmp="00:00";yearlinetmp=$7}
     daylinetmp=$6;monthlinetmp=$5
    }
   else
     {timecol="8"
      timepos=index($8,":")
      if (timepos > 0)
         {timelinetmp=$8;yearlinetmp="3000"}
      else
         {timelinetmp="00:00";yearlinetmp=$8}
      daylinetmp=$7;monthlinetmp=$6
     }
  }
 

 if (unixsys=="FreeBSD")
    {dayline=$7;yearline=$9;timeline=$8;monthline=$6}
 else
   {if (unixsys=="Linux")
      {dayline=$8;yearline=$10;timeline=$9;monthline=$7}
    else
      {dayline=daylinetmp;yearline=yearlinetmp; \
        timeline=timelinetmp;monthline=monthlinetmp}
   }

 if (length(dayline) == 1)
    {daystr="0" dayline}
 else
    {daystr=dayline}

datestr=yearline "." month[monthline] daystr timeline; gsub(":","",datestr)
print datestr}' unixsys=$unixsys `

case $cmd in
  "$chitexfdfile")      datefdfile=$datestr;;
  "$chitexfdf")         datefdf=$datestr;;
  "$TEXMF/ttfonts.map") datemap=$datestr;;
esac
done
}


if test "$GBENV" != "gbenv"; then
# for Big5's
  if test -s chitex.fdfile; then
     chitexfdfile="chitex.fdfile"
     check="y"
  else
     chitexfdfile="$TEXMF/tex/chinese/chitex.fdfile"
     check="n"
  fi

  if test -s chitex.fdf; then
     chitexfdf="chitex.fdf"
  else
     chitexfdf="$TEXMF/tex/chinese/chitex.fdf"
  fi

  if test "$check" = "y"; then
     checkfdftime

  dateyearle=`echo "$datefdfile"|cut -d. -f 1`
  datefdfile=`echo "$datefdfile"|cut -d. -f 2`
  dateyeardf=`echo "$datefdf"|cut -d. -f 1`
  datefdf=`echo "$datefdf"|cut -d. -f 2`
  dateyearap=`echo "$datemap"|cut -d. -f 1`
  datemap=`echo "$datemap"|cut -d. -f 2`

    if test $dateyearle -lt $dateyeardf -o $dateyearle -lt $dateyearap; then
       lessstr="y"
    else
       if test $datefdfile -lt $datefdf -o $datefdfile -lt $datemap; then
          lessstr="y"
       fi
    fi

    if test "$lessstr" = "y"; then
       chitexconfig -chitex.fdf
    fi
  else
     chitexconfig -chitex.fdf
  fi
else
# for gb's
  if test -s chitexg.fdfile; then
     chitexfdfile="chitexg.fdfile"
     check="y"
  else
     chitexfdfile="$TEXMF/tex/chinese/chitexg.fdfile"
     check="n"
  fi

  if test -s chitexg.fdf; then
     chitexfdf="chitexg.fdf"
  else
     chitexfdf="$TEXMF/tex/chinese/chitexg.fdf"
  fi

  if test "$check" = "y"; then
     checkfdftime

  dateyearle=`echo "$datefdfile"|cut -d. -f 1`
  datefdfile=`echo "$datefdfile"|cut -d. -f 2`
  dateyeardf=`echo "$datefdf"|cut -d. -f 1`
  datefdf=`echo "$datefdf"|cut -d. -f 2`
  dateyearap=`echo "$datemap"|cut -d. -f 1`
  datemap=`echo "$datemap"|cut -d. -f 2`

    if test $dateyearle -lt $dateyeardf -o $dateyearle -lt $dateyearap; then
       lessstr="y"
    else
       if test $datefdfile -lt $datefdf -o $datefdfile -lt $datemap; then
          lessstr="y"
       fi
    fi

    if test "$lessstr" = "y"; then
       chitexconfig -chitex.fdf
    fi
  else
     chitexconfig -chitex.fdf
  fi
fi
#############
fi # checkfdf

if test "$code" = "big5"; then
  if test "$pdftex" = "y"; then
   texfmt="pdfchitex"
   latexfmt="pdfchitexl"
  else
   texfmt="chitex"
   latexfmt="chitexl"
  fi
else
  if test "$pdftex" = "y"; then
   texfmt="pdfchitexg"
   latexfmt="pdfchitexlg"
  else
   texfmt="chitexg"
   latexfmt="chitexlg"
  fi
fi   

if test "$newchitran" = "y" ; then
  docu=`
  chitexsub1 $filename `
else
  docu=`
  $gawkbin '
BEGIN{}
{ inline=$0
     inlinetmp=inline; newline=""
     CMDSTR="\\%"; NEWCMDSTR="##"
     while (inlinetmp != "")  
       {cmdpos=index(inlinetmp,CMDSTR)
        if (cmdpos>0)
          {newline=newline substr(inlinetmp,1,cmdpos-1) NEWCMDSTR
           inlinetmp=substr(inlinetmp,cmdpos+length(CMDSTR))
          }
        else
          {newline=newline inlinetmp; inlinetmp=""}
       }
     inline=newline

#  gsub("\\%","##",inline)
  perc=index(inline,"%")
  if (perc > 0)
     {inline=substr($0,1,perc-1)}
  else
     {inline=$0}

  if (doculoc == 0)
    {doculoc=index(inline,"\134documentclass")}
  else
    {if (docusty == 0)
      {docusty=index(inline,"\134documentstyle")}
     else
      {if (begindocu == 0)
         {begindocu=index(inline,"\134begin{document}")}
       else
         {if (begindocua == 0)
           {begindocua=index(inline,"\134begin {document}")}
          else
           {if (enddocu == 0)
               {enddocu=index(inline,"\134enddocument")}
            else
             {if (inputamstexa == 0)
                {inputamstexa=index(inline,"\134input amstex")}
              else
               {if (inputamstexb == 0)
                 {inputamstexb=index(inline,"\134input  amstex")}
                else
                 {if (inputamstexc == 0)
                    {inputamstexc=index(inline,"\134input   amstex")}
                  else
                   {if (inputamstexd == 0)
                      {inputamstexb=index(inline,"\134input    amstex")}
                    else
                       {if (inputamstexe == 0)
                          {inputamstexe=index(inline,"\134input     amstex")}
                       }
                   }
                 }
               }
             }
           }
         }
      }
    }


  if (inputamstexa > 0 || inputamstexb > 0 || inputamstexc > 0 \
     || inputamstexd >0 || inputamstexe > 0)
     {inputamstex=1;print "plainamstex"# > "docufile@"
      exit}

  if (doculoc > 0)
    {print "latex" # > "docufile@"
     documentclass=1;exit}
  
  if (docusty > 0)
     {documentstyle=1}
  if (begindocu > 0 || begindocua > 0)
     {begindocument=1}
  if (enddocu > 0)
     {enddocument=1}
# }
}
END{
#print documentclass " " documentstyle " " begindocument

  if (documentclass == 0 && documentstyle == 1 && inputamstex == 0)
     {if (begindocument == 1)
         {print "latex" # > "docufile@"
         }
      else
        {if (enddocument == 1)
            {
             print "amstex" # > "docufile@"
            }
         else
            {print "amstexorlatex" # > "docufile@"
            }
        }
     }
}' $filename `

fi # if "$newchitran" = "y"; then 




#if test -r docufile@; then
#   docu=`cat docufile@`
#fi

#rm -f docufile@ docu@ > /dev/null


if test "$docu" = ""; then
   docu="plaintex"
fi

if test "$docu" = "amstexorlatex"; then
typechoose="0"
 while test "$typechoose" = "0"
 do
 echo "    *****************************************"
 echo "    *                                       *"  
 echo "    *   Tell me the type of your document:  *"
 echo "    *   1. LaTeX document                   *"
 echo "    *   2. AmsTeX document                  *"
 echo "    *                                       *"  
 echo "    *****************************************"   
 echo " "
 echo -n "   Type '1' or '2' to choose one of the above: "
 read inkey

 if test "$inkey" != "1" -a "$inkey" != "2"; then
    typechoose="0"
 else
    typechoose="1"
 fi

 if test "$inkey" = "1"; then
    docu="latex"
 else
    docu="amstex"
 fi 
 done

fi


if test "$docu" = "latex"; then

 echo "    ************************************************"
 echo "    *                                              *"
 echo "    *   The compiled document is a LaTeX document  *"
 echo "    *                                              *"
 echo "    ************************************************"

if test "$newchitran" = "y"; then
   chitranc $filename
else
   chitran $filename
fi

if test -s defmacro@; then
   mv -f defmacro@ def@macro
fi


if test -s chbold@; then
$gawkbin '
BEGIN{}
{print $0 > "maintemp@"
 if (documentclasspos == 0)
  {inline=$0
   gsub("\\%","##",inline)
   per=index(inline,"%")
   if (per > 1)
      {inline=substr($0,1,per-1)}
   else
      {inline=$0}
   documentclasspos=index(inline,"\134documentclass")
   if (documentclasspos > 0)
      {print "\\usepackage{chboxit}" > "maintemp@"}
  }
}
END{} ' $filea.tmp00

mv -f maintemp@ $filea.tmp00

fi  


if test -s ch@labelfile; then
   mv -f ch@labelfile ch@label
fi

enddoc=`cut -d% -f 1 $filea.tmp00|fgrep "\\end{document}"`
if test "$enddoc" = ""; then
   enddocsp=`cut -d% -f 1 $filea.tmp00|fgrep "\\end {document}"`
fi
if test "$enddoc" = "" -a "$enddocsp" = ""; then
   echo "\\end{document}" >> $filea.tmp00
   echo -e " \a "
   echo " "
   echo " "
   echo "Warning! Warning! "
   echo "Missing command \\end{document} "
   echo "Now ChiTeX insert it to your document temporarily. "
   echo "    "
   echo -e "* Press any key to continue\c"
   read inkey
fi


#/bin/rm -f *temp@ maintemp*@ maintmp*@ fileb@ *.@@@ 
/bin/rm -f *@

compilelatex () {
if test "$option" = "e"; then
   if test "$pdftex" = "y"; then
      ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map
      pdflatex  \&$latexfmt $filea.tmp00
      rm -f pdftex.map
   else
      latex \&$latexfmt $filea.tmp00
   fi   
else
   if test "$option" = "batch"; then
       if test "$pdftex" = "y"; then
          ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map       
          pdflatex \&$latexfmt $filea.tmp00|cctran 2> /dev/null
          rm -f pdftex.map          
       else
          latex \&$latexfmt $filea.tmp00|cctran 2> /dev/null 
        fi   
   else
     if test "$option" = "nonstop"; then
        if test "$pdftex" = "y"; then
           ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map               
           pdflatex \&$latexfmt $filea.tmp00|cctran 2> /dev/null
           rm -f pdftex.map    
    else
           latex \&$latexfmt $filea.tmp00|cctran 2> /dev/null
        fi
     else
        if test "$pdftex" = "y"; then
           ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map               
           pdflatex \&$latexfmt $filea.tmp00|ctran 2> errf@.dat
           rm -f pdftex.map           
        else
           latex \&$latexfmt $filea.tmp00|ctran 2> errf@.dat 
        fi
     fi
   fi
fi
}


compilelatex


  if test -s $filea.toc -o -s $filea.lof -o -s $filea.lot; then
     secondcompile="1"
  else
     if test -s $filea.log; then
        msg=`fgrep "LaTeX Warning: Reference" $filea.log|fgrep "undefined" `
        msga=`fgrep "LaTeX Warning: Label(s) may have changed" $filea.log `
        if test "$msg" != "" -o "$msga" != ""; then
           secondcompile="1" 
        fi
     fi
  fi          
# fi

  if test "$secondcompile" = "1"; then
   if test "$code" = "big5"; then
     echo "*******************************"
     echo "*                             *"
     echo "*      }lĤG^sĶ         *"
     echo "*                             *"
     echo "*******************************"
   else
     echo "*******************************"
     echo "*                             *"
     echo "*      ʼڶر         *"
     echo "*                             *"
     echo "*******************************"
   fi
     echo " "

#     chilatex $1

  if test -s def@macro; then
     chicodeb $filea
     mv -f tex@.out $filea".out"
  fi

compilelatex

  fi

if test -s pfbfile@; then
   texhash
fi

#/bin/rm -f tmp@@ *.tmp@* *.temp$ *.tmp!* 
#/bin/rm -f transl@*  addmac*@ *.tmp0*  *@  ch@export* ch@labelfile
/bin/rm -f *@ *.tmp00 ch@labelfile
cp .tmp00/*.aux . >/dev/null 2>&1

fileno=
inputno=
labelcount=
bitemcount=
export fileno
export inputno
export labelcount
export bitemcount

fi  #end latex





if test "$docu" = "plaintex" -o "$docu" = "plainamstex" -o "$docu" = "amstex"; then
 echo "    **************************************************"
 echo "    *                                                *"
 if test "$docu" = "plaintex"; then
     echo "    *  The compiled document is a plain TeX document *"
 else
     echo "    *    The compiled document is a AmsTeX document  *"
 fi
 echo "    *                                                *"
 echo "    **************************************************"


if test "$newchitran" = "y"; then
   chitranpc $filename
else
   chitranp $filename
fi



if test -s chbold@; then
$gawkbin '
BEGIN{print "\\input chboxit" > "maintemp@"}
{print $0 > "maintemp@"
}
END{} ' $filea.tmp00

mv -f maintemp@ $filea.tmp00

fi  


if test "$docu" = "amstex"; then
   echo "\\input amstex" > add@
   cat $filea.tmp00 >> add@
   mv -f add@ $filea.tmp00
   docu="plainamstex"
fi   


cut -d% -f 1 $filea.tmp00|fgrep "\\end" > tmp@
cut -d% -f 1 $filea.tmp00|fgrep "\\bye" > tmp@@
cut -d% -f 1 $filea.tmp00|fgrep "\\enddocument" > tmp@@@

end=`
$gawkbin '
BEGIN{}
{
 end=$0
 if (end !="")
 {
  gsub("\t"," ",end)
  endloc=index(end,"\134end")
  endnext=substr(end,endloc+4,1)
  haveend=0
  if (end !="")
     {if (endnext == "
"||endnext == " "|| endnext == "\134"||endnext == "")
         {haveend=1}
     }
  if (haveend == 1)
     {print "end"}
  else
     {print ""}
 }
 else
     {print ""}
}
END{} ' tmp@ `

bye=`
$gawkbin '
BEGIN{}
{
 bye=$0
 if (bye != "")
 {lenn=length(bye)
  gsub("\t"," ",bye)
  byeloc=index(bye,"\134bye")
  byenext=substr(bye,byeloc+4,1)
  havebye=0
  if (bye !="")
     {if (byenext == "
"||byenext == " "|| byenext == "\134"\
          ||byenext == "")
         {havebye=1}
     }
  if (havebye == 1)
     {print "bye"}
  else
     {print ""}
 }
 else
     {print ""}
}
END{} ' tmp@@ `

enddoc=`
$gawkbin '
BEGIN{}
{
 enddoc=$0
 if (enddoc != "")
 {lenn=length(enddoc)
  gsub("\t"," ",enddoc)
  enddocloc=index(enddoc,"\134enddocument")
  enddocnext=substr(enddoc,enddocloc+12,1)
  haveenddoc=0
  if (enddoc !="")
     {if (enddocnext == "
"||enddocnext == " "|| enddocnext == "\134"\
          ||enddocnext == "")
         {haveenddoc=1}
     }
  if (haveenddoc == 1)
     {print "enddoc"}
  else
     {print ""}
 }
 else
     {print ""}
}
END{} ' tmp@@@ `



if test "$docu" = "plaintex"; then
if [ "$end" = "" -a "$bye" = ""  -a "enddoc" = "" ]; then
   echo "\\bye" >> $filea.tmp00
   echo -e " \a "
   echo " "
   echo " "
   echo "Warning! Warning! "
   echo "Missing command \\end or \\bye "
   echo "Now ChiTeX insert it to your document temporarily. "
   echo "    "
   echo -e "* Press any key to continue\c"
   read inkey
fi
fi

if test "$docu" = "plainamstex"; then
if [ "$enddoc" = "" ]; then
   echo "\\enddocument" >> $filea.tmp00
   echo -e " \a "
   echo " "
   echo " "
   echo "Warning! Warning! "
   echo "Missing command \\enddocument"
   echo "Now ChiTeX insert it to your document temporarily. "
   echo "    "
   echo -e "* Press any key to continue\c"
   read inkey
fi
fi


#/bin/rm -f *temp@ maintemp*@ maintmp*@ fileb@ *.@@@ 
/bin/rm -f *@ 

if test "$option" = "e"; then
   if test "$pdftex" = "y"; then   
      ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map   
      pdftex \&$texfmt $filea.tmp00
      rm -rf pdftex.map   
   else
      tex \&$texfmt $filea.tmp00
   fi
else
   if test "$option" = "batch"; then
      if test "$pdftex" = "y"; then
         ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map      
         pdftex \&$texfmt $filea.tmp00|cctran 2> /dev/null
         rm -rf pdftex.map            
      else
         tex \&$texfmt $filea.tmp00|cctran 2> /dev/null
      fi   
   else
     if test "$option" = "nonstop"; then
        if test "$pdftex" = "y"; then
            ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map        
            pdftex \&$texfmt $filea.tmp00|cctran 2> /dev/null
            rm -rf pdftex.map   
        else
            tex \&$texfmt $filea.tmp00|cctran 2> /dev/null        
            rm -rf pdftex.map               
        fi   
     else
        if test "$pdftex" = "y"; then
           pdftex \&$texfmt $filea.tmp00|ctran 2> errf@.dat
           ln -s /usr/share/texmf-var/fonts/map/pdftex/updmap/pdftex_dl14.map pdftex.map           
           rm -rf pdftex.map               
       else
           tex \&$texfmt $filea.tmp00|ctran 2> errf@.dat    
       fi    
     fi
   fi
fi


if test -s pfbfile@; then
   texhash
fi

/bin/rm -f *@ *.tmp00
#/bin/rm -f tmp@@ *.tmp@* *.temp$ *.tmp!* 
#/bin/rm -f transl@*  addmac*@ *.tmp0*  *@
/bin/rm -rf .tmp00 tmp@
fi


 if test -s $filea.log; then
  qmark=`
  $gawkbin '
  BEGIN{}
  {  
   if (qmark == "")
    {
     qmarkloc=index($1,"?")
     if (qmarkloc == 1)
        {qmark=1
         print "qmark"}
    }
  }
  END{} ' $filea.log `

  if test "$qmark" != "" -o ! -s $filea.log; then
#     clear
     echo " "
     echo "       ******************************************"
     echo "       *                                        *"
     echo "       *                Warning!                *"
     echo "       *  Compiled TeX document may have errors  *"
     echo "       *                                        *"
     echo "       ******************************************"
     echo "  "
  fi
 fi

  nopage=`
  $gawkbin '
  BEGIN{}
  {  
   if (nopage == "")
    {
     nopageloc=index($0,"No pages of output")
     if (nopageloc == 1)
        {nopage=1
         print "nopage"}
    }
  }
  END{} ' $filea.log `


  if test "$nopage" != ""; then
     echo "       ******************************************"
     echo "       *                                        *"
     echo "       *  Compiled TeX document may has errors. *"
     echo "       *  No dvi file generated.                *"
     echo "       *                                        *"
     echo "       ******************************************"
     echo " "
     exit
  fi

  if test "$pdftex" = "y"; then
     ext="pdf"; pspdf="pdf"
  else
     ext="dvi"; pspdf="ps"
  fi

#  if test "$qmark" != "" -o ! -s $filea.dvi; then
  if test "$qmark" != "" -o ! -s $filea.$ext; then
     askmenu="1"
  fi
   while test "$askmenu" = "1"
   do
    if test "$code" = "gb"; then
     clear
     echo "       *******************************"
     echo "       *                             *"
     echo "       *    ֮ TeX ļд    *"
     echo "       *    1. ֹͣԤ              *"
     echo "       *    2. Ԥ          *"
     echo "       *                             *"
     echo "       *******************************"
     echo "  "
     echo -n "       ѡ 1  2 : "
    else
     clear
     echo "       *******************************"
     echo "       *                             *"
     echo "       *    ҽsĶ TeX 󦳿    *"
     echo "       *    1. w              *"
     echo "       *    2. ~iw          *"
     echo "       *                             *"
     echo "       *******************************"
     echo "  "
     echo -n "       п 1  2 : "
    fi

     read inkey

     if test "$inkey" != "1" -a "$inkey" != "2"; then 
         askmenu="1" 
     else
         askmenu="0"
     fi     
     if test "$inkey" = "1"; then
        pv="no"
     fi
   done


if test "$chinesef" = "1"; then
   if test -s $filea.pdf; then
      /bin/mv -f $filea.pdf $oldfilea.pdf
   fi
   if test -s $filea.dvi; then
     /bin/mv -f $filea.dvi $oldfilea.dvi
   fi
   /bin/mv -f $filea.log $oldfilea.log
   filea=$oldfilea
fi

ctranbb $filea.log 
if test -s  tmplog@@; then
   mv tmplog@@ $filea.log
fi
/bin/rm -f tmp@ tmplog@ m@@ch@*.tex m@@ch@*.bib


  
  if test "$pv" != "no"; then
#     clear
     echo "       *********************************************************"
     echo "       *                                                       *"
     echo "       *  Start to 'dvips' and 'ghostview' the given dvi file  *"
     echo "       *                                                       *"
     echo "       *********************************************************"  
     echo "  "
#     read xxxxx
     
     if test "$pdftex" != "y";then dvips $filea; fi

    if test "$Nogv" = ""; then
       if test -s /usr/bin/gv; then
          gsv="gv"; Haveviw="y"
       else
          if test -s /usr/bin/ghostview; then
             gsv="ghostview"; Haveviw="y"
          else
             if test -s /usr/bin/kghostview; then   
                 gsv="kghostview"; Haveviw="y"             
             else
                 if test -s /usr/bin/gsview; then      
                    gsv="gsview"; Haveviw="y"             
                 fi 
             fi
          fi
       fi   
       if test "$Haveviw" = ""; then
          gsvloc=`which gv|fgrep ":"`
          if test "$gsvloc" = ""; then
             gsvloc=`which gv|fgrep "no gv"`
          fi
          if test "$gsvloc" != ""; then
             gsvloc=`which gsview|fgrep "no gsview"`
             if test "$gsvloc" != ""; then 
                gsv="ghostview"
             else
                gsv="gsview"
             fi    
          else
             gsv="gv"        
          fi
#          $gsv $filea.$pspdf
       fi
       if test "$pspdf" = "pdf"; then
          if test -s /usr/bin/xpdf; then
             xpdf $filea.$pspdf       
          else
             acroread $filea.$pspdf       
          fi   
       else
          $gsv $filea.$pspdf          
       fi   
#       $gsv $filea.$pspdf       
     fi  
  fi

# rm -f tmp@

if test "$qmark" != "" -o ! -s $filea.log \
 -o "$option" = "e" -o "$option" = "batch" -o "$option" = "nonstop"; then
if test "$code" = "big5"; then
echo "****************************************               "
echo "*****  ChiTeX version 6.1.2 - by                         "
echo "*****     (Hung-Yih Chen)  yih@math.ncu.edu.tw)   "
echo "*****  ߤjǼƾǨt (Dept. of Math., National Central Univ.)"
echo "****************************************               "
else
echo "****************************************               "
echo "*****  ChiTeX version 6.1.2 - by                         "
echo "*****     (Hung-Yih Chen)  yih@math.ncu.edu.tw)   "
echo "*****  ѧѧϵ (Dept. of Math., National Central Univ.)"
echo "****************************************               "
fi

fi

GBENV=""
export GBENV
chitranno=
export chitranno

if test "$chinesef" = "1"; then
   if test -s $filea.pdf; then
      /bin/mv -f $filea.pdf $oldfilea.pdf
   fi
   if test -s $filea.dvi; then
     /bin/mv -f $filea.dvi $oldfilea.dvi
   fi
   /bin/mv -f $filea.log $oldfilea.log
   cp -f $filea.aux $oldfilea.aux
   filea=$oldfilea
fi

ctranbb $filea.log 
if test -s  tmplog@@; then
   mv tmplog@@ $filea.log
fi
/bin/rm -f tmp@ tmplog@ m@@ch@*.tex m@@ch@*.bib
/bin/rm -f errf@.dat tmplog@@*


exit

