#!/bin/sh
#
#  This is a part of ChiTeX.
#  This script is created by 
#    Hung-Yih Chen ()  (yih@math.ncu.edu.tw)
#               (Dept. of Mathematics, National Central Univ.)
#           Last updated  April. 19, 2000
# 
#                All rights preserved   
#

#quickmode="y"


gawkbin="gawk"

searchtexmf="y"
if test "$searchtexmf" = "y"; then
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

export TEXMF

filename=$1

if test "$filename" = ".tex"; then 
   exit
fi

echo "y" > tmp@

if test ! -s "$filename"; then 
filename=`
$gawkbin  '
BEGIN{}
{
 if (substr(filename,length(filename)-3) == ".tex")
    {filename=substr(filename,1,length(filename)-4)} 
 print filename    
}
END{}' filename=$filename tmp@`
fi

unadd=`echo $filename|fgrep "@unadd"`
if test "$unadd" != ""; then
   addperc=0
else
   add=`echo $filename|fgrep "@add"`
   if test "$add" != ""; then
      addperc=1
   fi
fi
export addperc


filename=`echo "$filename"|\
  sed -e 's#.@unadd##' -e 's#.@add##'`

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

stexf=`
$gawkbin  '
BEGIN{}
{if (index($0,filename) > 0)
  {print "yes"}
 else
  {print ""}
}
END{}' filename=$filename texfile@`

#echo $inputpath".tmp00"

outfilename=`echo "$filename"|sed 's#/#c#g'`
#outfilename=".tmp00/$outfilename"


if test "$inputpath" != "" -a "$stexf" = "" -a -s $outfilename; then
   outfilename=$inputpath".tmp00/$outfilename"
else
   outfilename=$inputpath".tmp00/$outfilename"
fi
if test ! -d $inputpath".tmp00"; then
   mkdir -p $inputpath".tmp00"
fi


echo "yes" > tmp@

test1=""
if test "$test1" = "y"; then
 if test "$stexf" = "" -a "$outfilename" != ""; then
  if test "$inputpath" != ""; then
    include=`
    gawk '
    BEGIN{}
    {ch=substr($0,length($0),1)
       if (ch=="@")
         {print "yes"}
    }
    END{}' outfilename=$outfilename tmp@ `

    if test "$include" != ""; then
       baseoutfilename=`basename $outfilename`
       ext=`cut -d. -f 2 $baseoutfilename=`
       if test "$ext" != "";then
          baseoutfilename=baseoutfilename ".tex"
       fi
    fi
  fi  
 fi
fi


  bname=`basename $filename`                    


  filea=`echo $bname|cut -d. -f 1` 


rm -f maintemp*@ maintmpb@

  echoprompt=`echo -n "."`
  if test "$echoprompt" = "."; then
     echomode="-n ."
  else
     echoprompt=`echo  ".\c"`
     if test "$echoprompt" = "."; then
        echomode=" .\c"
     else 
        echomode="-e .\c"
     fi
  fi

echo $echomode


cp $filename maintemp@


rm -f *.tmp@@
if test -s "ask@"; then rm -f ask@; fi

# begin to manage \begin{filecontents} ...\end{filecontents}
# 

if test "$quickmode" = ""; then
if test "$chitranno" = "0"; then
filecontents=`chitran00 maintemp@`

oldtest1="n"
if test "$oldtest1" = "y"; then
filecontents=`gawk '
BEGIN{endprint="0"}
{
 if (endprint != "2")
 {percent=index($0,"%")
#  inline=substr($0,percent+1,length($0)-percent)
  if (percent > 0)
     {inline=substr($0,1,percent-1)}
  else
     {inline=$0} 
  if (documentclass == 0)
     {documentclass=index(inline,"\134documentclass")}
  if (documentclass > 0)
     {exit}
  filecontents=index(inline,"\134begin{filecontents}")
  endfilecontents=index(inline,"\134end{filecontents}")
  
  rinlinebg=0
  if (filecontents > 0)
     {havefilecontents="1"
      rbrlbra=index(inline,"\134begin{filecontents}{")
      rbrlbrb=index(inline,"\134begin{filecontents} {") 
      if (rbrlbra > 0)
         {rinlinebg=22}
      else
         {if (rbrlbrb > 0)
             {rinlinebg=23}
         }
      if (rinlinebg > 0)
         {rinline=substr(inline,rinlinebg,length(inline))
          rinlinerbr=index(rinline,"}")
          filename=substr(rinline,1,rinlinerbr-1)
          system("rm -f " filename".tmp@@")
          kk=1
          }
     }


  if (filename != "")
     {if (endfilecontents == 0)
         {if (kk > 1)
             {print $0 >> filename".tmp@@"}
          else
             {kk=kk+1}
         }
      else
         {
          filename=""
          }
     }
  if (documentclass > 0)
     {endprint="1";exit}
  if (endprint == "0") 
     {
     }
  else
     {if (endprint == "1") 
        {endprint="2"}
     }
 }  
}
END{
  if (havefilecontents == "1")
#     {print "filecontents" > "filecontents@"}
      {print "yes"}
}' maintemp@  `
fi # if test "$oldtest1" = "y"...


if test "$filecontents" = "yes"; then
ls -1 *.tmp@@ > tmpfile@@ 2>/dev/null


if test ! -s tmpfile@@; then 
   exit
fi


# ask overwrite old files
#if test -s filecontents@; then

chitran01  tmpfile@@ 

oldtest2="n"
if test "$oldtest2" = "y"; then
gawk '
BEGIN{FS=".tmp@@"}
{
 print "message=\42" "1\42" > "ask@"
 print "while test \42$message\42 = \42" "1\42" > "ask@"
 print "do " > "ask@"
 print "if test -s " $1 "; then " > "ask@"
 print "differ=`diff " $1 " " $1".tmp@@`" > "ask@"
 print "if test \42$differ\42 != \42\42; then" > "ask@"
 print "clear " > "ask@"
 print "echo \42 " " \42 " > "ask@"
 print "echo \42    File " $1 " exist \42" > "ask@"
 print "echo \42 \42 " > "ask@"
 print "echo \42    1. Make new file \134\42" $1 "\134\42 and overwrite the old \
one, while \42" > "ask@"
 print "echo \42       the old one \134\42" $1 "\134\42 will be \
backup as \134\42" $1 ".bak\134\42 \42" > "ask@"

 print "echo \42    2. Keep the old one. \42" > "ask@"
 print "echo \42    \42" > "ask@"
 print "echo -n \42    Enter '1' or '2' to choose one of the above: \42" > "ask@"
 print "read inkey" > "ask@"
 print "if test \42$inkey\42 = \42" "1\42; then" > "ask@"
 print "   mv  " $1 " " $1".bak" > "ask@"
 print "   mv -f " $1 ".tmp@@ " $1 > "ask@"
 print "   message=\42" "0\42 " > "ask@"
 print "fi" > "ask@"
 print "if test \42$inkey\42 = \42" "2\42; then" > "ask@"
 print "   message=\42" "0\42 " > "ask@"
 print "fi" > "ask@"
 print "else" > "ask@"
 print "  message=\42" "0\42" > "ask@"
 print "fi" > "ask@"
 print "else" > "ask@"
 print "  mv -f " $1 ".tmp@@ " $1 > "ask@"
 print "  message=\42" "0\42" > "ask@"
 print "fi" > "ask@"
 print "done "  > "ask@"
}
END{} ' tmpfile@@
fi # if test "$oldtest2" = "y"; then 


chmod +x ask@
./ask@

fi
# end for managing  \begin{filecontents} ...\end{filecontents}
fi # end if test "$chitranno" = "0" ...
fi # end of nonquickmode


if test -s setaddpercent@; then
   chmod +x setaddpercent@
   . ./setaddpercent@   
fi


if test "$chbold" = ""; then
 if test -s chbold@; then
   chbold=`echo "y"`
   export chbold
 fi
fi



/bin/rm -f klinetemp*@

#nochprotect="y"


gawk '
BEGIN{}
{
   inline=$0
   subinline=$0
   percent=0
#   tail=""

   percent=index(inline,"%")
   if (percent > 0)
   {
     inlinetmp=subinline; 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=""}
       }
     subinline=newline

#        gsub("\\\\%","##",subinline)
        percent=index(subinline,"%")
   }
   

   if (percent > 0)
      {#tail="!!@%@!%@ch@tmp%%% " substr(inline,percent)
       inline=substr(inline,1,percent-1)
       }

  if (nonautoaddpercent==0)
     {nonautoaddpercent=index(inline,"\\nonautoaddpercent")}

   verbpos=index(inline,"\\verb")  
   verbatimpos=index(inline,"\\begin{verbatim")
   endverbatimpos=index(inline,"\\end{verbatim")
   boxedverbatimpos=index(inline,"\\begin{boxedverbatim}")
   endboxedverbatimpos=index(inline,"\\end{boxedverbatim}")
   listingpos=index(inline,"\\begin{listing")
   endlistingpos=index(inline,"\\end{listing")
   verbatimwritepos=index(inline,"\\begin{verbatimwrite}")
   endverbatimwritepos=index(inline,"\\end{verbatimwrite}")
   verbatimtabpos=index(inline,"\\begin{verbatimtab}")
   endverbatimtabpos=index(inline,"\\end{verbatimtab}")
   chtabverbatimpos=index(inline,"\\chtabverbatim")
   endchtabverbatimpos=index(inline,"\\endchtabverbatim")

   verbatimcmdpos=index(inline,"\\begin{verbatimcmd}")
   endverbatimcmdpos=index(inline,"\\end{verbatimcmd}")

   allttpos=index(inline,"\\begin{alltt}")
   endallttpos=index(inline,"\\end{alltt}")

   chprotect=index(inline,"\\chprotect")
   unchprotect=index(inline,"\\unchprotect")

 if (chprotect > 0)
    {verbatim=0}
 if (unchprotect > 0)
    {verbatim=1}

 if (verbatimpos > 0)
    {verbatimmark=verbatimmark+1}
 if (endverbatimpos > 0)
    {verbatimmark=verbatimmark-1}

 if (verbatimtabpos > 0)
    {verbatimtabmark=verbatimtabmark+1}
 if (endverbatimtabpos > 0)
    {verbatimtabmark=verbatimtabmark-1}

 if (chtabverbatimpos > 0)
    {chtabverbatimmark=chtabverbatimmark+1}
 if (endchtabverbatimpos > 0)
    {chtabverbatimmark=chtabverbatimmark-1}

 if (boxedverbatimpos > 0)
    {boxedverbatimmark=boxedverbatimmark+1}
 if (endboxedverbatimpos > 0)
    {boxedverbatimmark=boxedverbatimmark-1}

 if (listingpos > 0)
    {listingmark=listingmark+1}
 if (endlistingpos > 0)
    {listingmark=listingmark-1}

 if (allttpos > 0)
    {allttmark=allttmark+1}
 if (endallttpos > 0)
    {allttmark=allttmark-1}

 if (verbatimmark+boxedverbatimmark+listingmark+allttmark+verbatimtabmark+chtabverbatimmark==1)
    {bgverbatimmark=1}
 else
    {bgverbatimmark=0}

 if (verbatimmark<0||boxedverbatimmark<0||listingmark<0||\
       allttmark<0||verbatimtabmark<0||chtabverbatimmark<0)
    {edverbatimmark=-1}
 else
    {edverbatimmark=1}


 if (verbpos>0||verbatimpos > 0 || allttpos > 0||verbatimcmdpos > 0||verbatimtabpos > 0 \
     ||boxedverbatimpos > 0||listingpos > 0|| verbatimwritepos > 0||chtabverbatimpos>0)
    {verbatim=1}
 if (endverbatimpos > 0||endallttpos > 0||endverbatimcmdpos > 0||endverbatimtabpos > 0\
      ||endboxedverbatimpos > 0||endlistingpos > 0 ||endverbatimwritepos >0 \
      ||endchtabverbatimpos >0)
    {verbatim=0}

 if (verbatim==0 && nochexpand==0)
    { nochexpand=index(inline,"\\nochexpand")
      if (nochexpand>0)
         {nochexpand=1; edverbatimmark=0}
    }
 if (verbatim==0 && chexpand==0)
    { chexpand=index(inline,"\\chexpand")
      if (chexpand>0)
         {nochexpand=0; edverbatimmark=1}
    }

 if (verbatim == 0 && nochexpand==0|| allttmark==1 && nochexpand==0)
    {
        if (index(inline,"\\newenvironment") > 0)
           {
            if (havechnulcpmmand=="")
               {havechnulcpmmand="y"
                print "\\makeatletter"
                print "\\newcommand{\\ch@nulcommand}{\\relax}"
                print "\\makeatother"
               }
           }
    }
 print $0
}
END{} ' maintemp@ | \
gawk -f /usr/bin/chitran0.awk > mainfiletmp@

gawk -f /usr/bin/chitran1.awk -v chitranno=$chitranno \
     -v nochprotect=$nochprotect mainfiletmp@ | \
gawk -f /usr/bin/chitran11.awk | \
chitran2 | \
chitran3 | \
gawk -f /usr/bin/chitran3a.awk -v chitranno=$chitranno  \
   -v addperc=$addperc -v beginpercprev=$beginpercprev | \
chitran4 | \
chitran5b


if test -s maintempp@; then
   mv -f  maintempp@ maintemp@
fi


  /bin/rm -f nexttemp*@ 


if test -s trancode@; then rm -f trancode@; fi
if test -s maintemp2@;then rm -f maintemp2@; fi

  if test -s HaveBg5@; then
     HaveBg5="y"
     export HaveBg5
  fi

if test ! -s klinetemp@ -a ! -s klinetemp3@ -a ! -s klinetemp2@ \
    -a ! -s klinetemp5@ ; then 


  if test "$stexf" != ""; then
#     chicode -u |chicodelistc > $filea.tmp00
     sed 's/\\@@!#?@enput/\\input/g' maintemp@| \
     chicode -u |chicodelistc > $filea.tmp00.tmp@ 
     sed 's/\\makeatother/\\relax/g' $filea.tmp00.tmp@ > $filea.tmp00
     stexf=""
  else
#     chicode -u |chicodelistc > $outfilename
   if test "$HaveBg5" = "y"'then
     sed 's/\\@@!#?@enput/\\input/g' maintemp@> maintemp2@
     mv -f maintemp2@ maintemp@
     bg5conv < maintemp@ > $outfilename.tmp@
     sed 's/\\makeatother/\\relax/g' $outfilename.tmp@ > $outfilename.tmp2@
     sed 's/\\@@?!lineend@@chinese@@!@\$\*?char//g' $outfilename.tmp2@ > $outfilename
   else
     sed 's/\\@@!#?@enput/\\input/g' maintemp@| \
     chicode -u |chicodelistc > $outfilename.tmp@
     sed 's/\\makeatother/\\relax/g' $outfilename.tmp@ > $outfilename.tmp2@
     sed 's/\\@@?!lineend@@chinese@@!@\$\*?char//g' $outfilename.tmp2@ > $outfilename
   fi  
  fi
  exit

else

if test -s klinetemp@; then
chitran5 -v inputpath=$inputpath klinetemp@
fi


new="y"
if test "$new" = "y"; then
if test -s klinetemp2@; then
gawk '
BEGIN{print "\\bibliography"}
{
 FS="\\\134bibliography" 
 fnum=2 
 while (fnum <=NF)
     {print $fnum 
     fnum = fnum + 1
      }
 }
END{}' klinetemp2@ | \
chitran5 -v inputpath=$inputpath 
fi


if test -s klinetemp5@; then
awk '
BEGIN{}
{
 FS="\\\134putbib" 
 fnum=2 
 while (fnum <=NF)
     {print $fnum 
     fnum = fnum + 1
      }
 }
END{}' klinetemp5@ | \
chitran7 -v inputpath=$inputpath
fi

fi

chitranno=1
export chitranno

if test -s klinetemp3@; then
chitran6 -v inputpath=$inputpath klinetemp3@
fi

     if test ! -s replacetemp@
     then 
       null="1"
     else
       chmod +x replacetemp@
       ./replacetemp@
     fi


     if test ! -s replacetemp2@
     then 
       null="1"
     else
       chmod +x replacetemp2@
       ./replacetemp2@
     fi



     if test ! -s replacetemp3@
     then 
       null="1"
     else
       chmod +x replacetemp3@
       ./replacetemp3@
     fi


     if test ! -s replacetemp5@
     then 
       null="1"
     else
       chmod +x replacetemp5@
       ./replacetemp5@
     fi


test2="y"
if test "$test2" = "y"; then
# To draw back to relative filename in \include to compatible to clyx

  if test -s maintempincl@; then
     rm -f maintempincl@
  fi

  if test "$stexf" != ""; then
    if test "$inputpath" != ""; then
     gawk '
     BEGIN{}
     {outline=$0
     includepos=index($0,"\\include{")
     includeposa=index($0,"\\include {")
     if (includeposa>0){includepos=includeposa}
     if (includepos>0)
       {
        include=substr($0,includepos,length($0)-includepos+1)
        lbr=index(include,"{")
        rbr=index(include,"}")
        include=substr(include,lbr+1,rbr-lbr-1)
        ch=substr(include,length(include),1)
        if (ch=="@")
           {include=substr(include,1,length(include)-1)
            rline=substr(include,rbr+1,length(include)-rbr)
            lline=substr($0,1,includepos-1)
            if (index(include,inputpath)==1)
             {replstr=inputpath
              gsub(replstr,"",include)
#              gsub(".tmp00/","",include)
              outline=lline "\\include{" include "}" rline
             }
           }
       }
       print outline > "maintempincl@"
     }
     END{}' inputpath=$inputpath maintemp@ 
    fi

    if test -s maintempincl@; then
       cp maintempincl@ maintemp@
    fi
  fi
fi


  if test "$stexf" != ""; then
     sed 's/\\@@!#?@enput/\\input/g' maintemp@| \
     chicode -u |chicodelistc > $filea.tmp00.tmp@ 
     sed 's/\\makeatother/\\relax/g' $filea.tmp00.tmp@ > $filea.tmp00
     stexf=""
  else
     sed 's/\\@@!#?@enput/\\input/g' maintemp@| \
     chicode -u |chicodelistc > $outfilename.tmp@
     sed 's/\\makeatother/\\relax/g' $outfilename.tmp@ > $outfilename.tmp2@
     sed 's/\\@@?!lineend@@chinese@@!@\$\*?char//g' $outfilename.tmp2@ > $outfilename
  fi


  if test ! -s nexttemp@
   then null="1"
  else 
    sed 's#.@add#.tex#g' nexttemp@ > nexttemp3@
    gawk '
    { inline=$0
      ss=index(inline,"-s ")
      if (ss > 0)
        {sep=index(inline,";")
         fname=substr(inline,ss+3,sep-ss-3)
        }
      else
        {if (index(inline,"chitranc ")>0)
            {inline="chitranc " fname}
        }    
      print inline > "nexttempp@"  
    } ' nexttemp3@
#    mv -f nexttemp3@ nexttemp@
    mv -f nexttempp@ nexttemp@
    chmod +x nexttemp@
    ./nexttemp@
#    /bin/rm -f nexttemp@ 
  fi



  if test ! -s nexttemp2@
   then null="1"
  else 
    sed 's#.@add#.tex#g' nexttemp2@ > nexttemp3@
    gawk '
    { inline=$0
      ss=index(inline,"-s ")
      if (ss > 0)
        {sep=index(inline,";")
         fname=substr(inline,ss+3,sep-ss-3)
        }
      else
        {if (index(inline,"chitranc ")>0)
            {inline="chitranc " fname}
        }    
      print inline > "nexttempp@"  
    } ' nexttemp3@

#    mv -f nexttemp3@ nexttemp2@
    mv -f nexttempp@ nexttemp2@
    chmod +x nexttemp2@
    ./nexttemp2@
#    /bin/rm -f nexttemp2@ 
  fi

fi


#rm -f *.@@@

rm -f tmp@

chitranno=1
export chitranno

exit
     
