#!/bin/tcsh
set refversion=1.3.4a
#set refversion=1.1.0
# for comparison with 0.5:
#set options="-V -t UNDERLINE -s SAFE -f FLOATSAFE  --disable-citation-markup"
set options="-V -t UNDERLINE -s SAFE -f FLOATSAFE "

# we can set this manually to keep track of modified versions
#set options="$options --math-markup=FINE"  ; set variant="FINE"


if ($?variant) then 
  set nameext="-$variant"
else
  set nameext
endif


set reportfile=report$nameext.txt

#setenv INTERACTIVE
alias latexdiff ../latexdiff
#alias latexdiff ../latexdiff-1.3.2/latexdiff
#alias latexdiff ../dist/latexdiff-fast
# also run?
set run=0
# only compare bodies
set bodydiff=0

set testroots=( test rapine_et_al island_obs2004 texdiffsample gershwin12 "gershwin34 --graphics-markup=none" example utf \
delequ latin9 pollack move-equation nomarkup subscript doubledollar intertext \
DIFDELCMDBUG eqnarray eqnarray2 subscriptm delequ2 schneider gennady umesh underwood endfloat endfloat2 outerrise \
delequ3 delequ4 "simplefrac --allow-spaces" "master --flatten" "subfile --flatten" "import --flatten" titlediffTest2 exampleDiff bornd2 split \
"rolla --math-markup=2" mini "complex-maths --math-markup=1" margalit oubmath circonflex mwe-comment "apacite-test --flatten" quoteddollarunderscore units complicated-math move-equation2 lists "figures --graphics-markup=both" alignat "safecmd --append-safecmd=remark" verbatim verbatim2-is143 embedded-math-array "verbatim-input --flatten" anchordemo 'customdiffcmdtest --add-to-config "CUSTOMDIFCMD=blindtext;mypar;donothing;cmd"' description frac_w_space_comments multicolumn tikz-dependency-test \
"href-in-bibliography --append-safecmd=path" revtex-bibliography biblatex 'txtcmd-with-multiple-arguments --append-textcmd=cmd' \
"no-del --no-del"  \
) # siunitx
# Note that siunitx test will only run on newer (>~2020) versions of siunitx)
#set testroots= ( test subscript )
# ttest-siunitx ttest-glossaries ttest-chem ttest-cleveref


if ( $#argv >= 1 ) then
  if ( $argv[1] == "--reset" ) then
    echo "Running verify in RESET mode, ie. save all differences with version number $refversion for later use, overwriting if necessary."
    echo "Press Return to confirm"
    set dummy="$<"
    set reset
  else if ( $argv[1] == "--run" ) then
    echo "Running pdflatex on difference files"
    set run=1
  else if ( $argv[1] == "--body-diff" ) then
    echo "Only compare the bodies of .tex files"
    set bodydiff=1
  else
    unset reset
  endif
else 
  unset reset
endif

set failed
set noexist
set failedrun
set pdfout
if ( ! $?reset ) then 
  echo "Report of diff test:" > $reportfile
  latexdiff --version >>& $reportfile
  echo "Options: $options" >> $reportfile
  echo "--------" >> $reportfile
endif
set nonomatch
while ( $#testroots >= 1 )
#foreach test ( $testroots)
  echo "$testroots[1]"
  set sample=( $testroots[1] )
  shift testroots
  if ( $#sample > 1 ) then 
    set eopt="$sample[2-]"
  else
    set eopt
  endif
  set sample=$sample[1]
  printf "%-20s :" $sample[1] >> $reportfile
  echo "========================================="
  echo "Differencing ${sample}-old.tex ${sample}-new.tex (using $eopt)"
  ( latexdiff $options $eopt ${sample}-old.tex ${sample}-new.tex > ${sample}-diff$nameext.tex) >& ${sample}-latexdiff$nameext.log 
#  diff ${sample}-diff-$refversion.tex ${sample}-diff.tex
  # sum up the quoted calculation times

  if ( $?reset ) then
    \cp  ${sample}-diff$nameext.tex  ${sample}-diff$nameext-$refversion.tex 
    \cp ${sample}-latexdiff${nameext}.log ${sample}-latexdiff${nameext}-$refversion.log
  else 
    if (! -e ${sample}-diff${nameext}-$refversion.tex ) then
       echo "Reference version ${sample}-diff$nameext-$refversion.tex does not exist."
       set noexist = ( $noexist $sample )
       echo " noref" >> $reportfile
       goto run
    endif
	if ( ! $bodydiff ) then 
      echo "Comparing ${sample}-diff-$refversion.tex and  ${sample}-diff.tex (removing latexdiff date stamp)"
      # remove 2 lines after pattern
      sed -e '/%DIF LATEXDIFF DIFFERENCE FILE/,+2d' ${sample}-diff${nameext}-$refversion.tex > tmp-ref.$$.tex
      sed -e '/%DIF LATEXDIFF DIFFERENCE FILE/,+2d' ${sample}-diff${nameext}.tex > tmp-cur.$$.tex
    else
      echo "Comparing ${sample}-diff-$refversion.tex and  ${sample}-diff.tex (strip preamble)"
      # isolate body
      sed -n '/begin{document}/,/end{document}/ p' ${sample}-diff${nameext}-$refversion.tex > tmp-ref.$$.tex
      sed -n '/begin{document}/,/end{document}/ p' ${sample}-diff${nameext}.tex > tmp-cur.$$.tex
    endif
    diff -q tmp-ref.$$.tex tmp-cur.$$.tex
    if ( $status ) then
      echo -n " fail">> $reportfile
      if (! $run) diff -c ${sample}-diff${nameext}-$refversion.tex ${sample}-diff${nameext}.tex
      echo "\07" 
      echo "Comparison of ${sample}-old.tex and ${sample}-new.tex gave different results to reference version. See above for detailed listing."
      if ( $?INTERACTIVE ) then
        echo "Press Return to continue" ; set dummy="$<" 
      endif
      set failed = ( $failed $sample )
    else
      echo -n " ok" >> $reportfile 
      echo "Passed comparison..."
    endif
    # calculate running time from summing reported time
    set totaltime=`perl -ne 'if (/\(([0-9.]*) s\)/){$sum+=$1; } END {print $sum }' ${sample}-latexdiff${nameext}.log`
    set totaltimeref=`perl -ne 'if (/\(([0-9.]*) s\)/){$sum+=$1; } END {print $sum }' ${sample}-latexdiff${nameext}-$refversion.log`
    # timediff[1] absolute diff.  timediff[2] % percentage diff rel. to old
	set timediff=( `echo  $totaltime $totaltimeref | awk  '{ diff=$1-$2; print diff, 100*diff/($2+0.005) }'` )
    printf " %5.2f s ( %6.2f s)\n" $totaltime $timediff[1]  >> $reportfile
    \rm tmp-{cur,ref}.$$.tex
  endif
run:
  if ( $run ) then 
    pdflatex -interaction=batchmode ${sample}-diff${nameext}.tex

    if ($status || ! -e ${sample}-diff.pdf ) then 
       echo "Compilation of ${sample}-diff${nameext}.tex did not complete as expected."
       set failedrun=($failedrun ${sample}-diff${nameext}.tex)
    else
       set pdfout=($pdfout ${sample}-diff${nameext}.pdf )
    endif
  endif
end


#if ( ! $?reset && $#failed >= 1 ) then 
if ( ! $?reset ) then 
  cat $reportfile
  unset flagdummy
  foreach fail ( $failed )
    set flagdummy
    echo kdiff3 ${fail}-diff${nameext}-$refversion.tex ${fail}-diff${nameext}.tex ' &'
  end
  if ($?flagdummy ) then 
    echo ""
    echo "The following test(s) failed:"
    echo $failed
  endif
  if ( "x$noexist" != x ) then
    echo "The following test(s) did not have a reference version available:"
    echo $noexist
  endif
endif

if ( $run ) then
  foreach out ( $pdfout )
    echo "okular $out &"
  end
  echo "The compilation of the following programs resulted in problems:"
  echo $failedrun
endif




