#!/bin/tcsh
#+
#  Purpose:
#     Does a few tests of the version of AST installed in $INSTALL.

#  Usage:
#     ast_tester <-nd>

#  Description:
#     Build and run various tests of an AST installation.
#
#     Some tests produce graphical output. Postscript plots of the FITS
#     cases listed in fixtures/plot/cases.txt are produced for visual
#     comparison with the references in fixtures/plot/expected. A file named
#     "*-new.ps" is created in the current directory for each case.
#
#     This script assumes the gfortran compiler is available. If this is not
#     the case, do a global edit of gfortran to whatever fortran 77 compiler
#     you have available (you will probably also need to change the compiler
#     flags).

#  Options:
#     -nd : Suppresses display of test plots.

#  Prior Requirements:
#     - Unless the "-nd" option is specified, it requires the gv command (a
#       frontend for ghostscript) to be on your PATH.
#     - The following environment variables are used:
#        STARLINK_DIR - should be set to the root of the tree in which the SSC is
#              installed. A default of /star is used if not set.
#        AST - should be set to the root of the tree in which the version of
#              AST to be tested is installed. A default of $STARLINK_DIR is used
#              if not set.

#  Author:
#     DSB: David Berry (JAC, Hawaii)
#-

if( ! $?STARLINK_DIR ) then
   setenv STARLINK_DIR /star
endif

if( ! $?AST ) then
   setenv AST $STARLINK_DIR
endif

if( ! $?LDFLAGS ) then
   setenv LDFLAGS ""
endif

if( ! $?FFLAGS ) then
   setenv FFLAGS "-fno-range-check"
else
   setenv FFLAGS "$FFLAGS -fno-range-check"
endif

setenv PATH $AST/bin\:$STARLINK_DIR/bin\:$PATH


# Build the progs
#gfortran -fno-second-underscore -o regression regression.f $FFLAGS $LDFLAGS -I$AST/include -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -ems` `chr_link`
gfortran -fno-second-underscore -o plotter plotter.f $FFLAGS $LDFLAGS -I$AST/include -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -pgp -ems` `pgplot_link`
gfortran -fno-second-underscore -o wcsconverter wcsconverter.f $FFLAGS $LDFLAGS -I$AST/include -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -ems` `chr_link` `err_link`
gfortran -fno-second-underscore -o simplify simplify.f $FFLAGS $LDFLAGS -I$AST/include -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -ems` `chr_link` `err_link`

gcc -Wall -c -g -O0 draw3d-subs.c -I$STARLINK_DIR/include
gfortran -fno-second-underscore -o draw3d draw3d.f draw3d-subs.o $FFLAGS $LDFLAGS -I$AST/include -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -pgplot3d -ems` `sla_link` `chr_link` `err_link` `pgplot_link` -lreadline

# Run the other test progs
echo ""

#  Test the pgplot 3D graphics interface
if( $1 != "-nd" ) then
   draw3d fixtures/programs/draw3d/draw3d-test1.txt
endif

#  Note - testhuge is not included because it takes so long to run.
foreach prog (testsplinemap testcmpframe testmoc testmocchan testmapping testchebymap testunitnormmap testskyframe testframeset testchannel testpolymap testcmpmap testlutmap testfitstable testtable teststcschan teststc testspecframe testfitschan testswitchmap testrebin testrebinseq testtrangrid testnormmap testtime testrate testflux testratemap testspecflux testxmlchan testregions testkeymap )

gfortran -fno-second-underscore -fallow-argument-mismatch -w -g -o $prog -g $prog.f $FFLAGS $LDFLAGS -I$AST/include \
     -I$STARLINK_DIR/include -L$AST/lib -L$STARLINK_DIR/lib `ast_link -ems` \
     `psx_link` `prm_link` `chr_link` `err_link` `cnf_link`

./$prog
\rm $prog

end



foreach prog (testyamlchan testsplinemap_c testresimp testobject testconvert testerror testunitnorm testaxis testframe)
   gcc -o $prog $prog.c -I.. -I../src -DHAVE_CONFIG_H $LDFLAGS -L$STARLINK_DIR/lib \
         -I$STARLINK_DIR/include `ast_link`

   ./$prog
   \rm $prog

end




# Make new plots.
echo ""
echo "Generating new plots..."
echo ""
if( $1 == "-nd" ) then
echo "   (but not displaying them because the -nd option was supplied)"
echo ""
endif

\rm *-new.ps  >& /dev/null

set plotcases = fixtures/plot/cases.txt

#  The registered plot cases, plus sip and sip2, which have no row in the
#  manifest (the grid and plotter ctests do not cover them) but are still
#  worth plotting with default settings.  The awk pattern selects data rows
#  rather than rejecting comment rows because csh history expansion would eat
#  a "!" here even inside single quotes.
set plotnames = ( `awk -F\| '/^[ \t]*[A-Za-z0-9]/ && NF >= 5 {gsub(/^[ \t]+|[ \t]+$/, "", $1); print $1}' $plotcases` sip sip2 )

foreach bn ( $plotnames )

   eval `awk -f plotcase.awk -v name=$bn $plotcases`

#  Not a registered case, so plot the canonical header of that name with
#  default settings.
   if( "$head" == "" ) then
      set head = fixtures/wcsconv/inputs/${bn}.head
      set attr1 = ' '
      set attr2 = ' '
      set box = ( )
   endif

   if( ! -e $head ) then
      echo "   no such header: $head"
      continue
   endif

   set psfile = "${bn}-new.ps"
   ./plotter $head "$attr1" "$attr2" a.ps $box

   if( -e $STARLINK_DIR/bin/psmerge ) then
      $STARLINK_DIR/bin/psmerge -t300x300 -r90 a.ps > $psfile
   else
      cp a.ps $psfile
   endif

   if( $1 != "-nd" ) then
      gv $psfile -orientation=landscape
   endif

end

\rm -f a.ps


# Make new fits headers
echo ""
echo "Doing WCS conversion tests..."
echo ""

set ok = 1
@ ncase = 0
@ ncmp = 0
@ nskip = 0
foreach rec ( "`awk -f cases.awk fixtures/wcsconv/cases.txt`" )

  set f = ( $rec )
  set name = $f[1]
  set in_file = fixtures/$f[2]
  set old_file = fixtures/$f[3]
  set encoding = $f[4]
  set attrs = $f[5]
  set skip = $f[6]
  if( "$attrs" == "-" ) set attrs = ""

  @ ncase++
  set new_file = "wcsconv-${name}-new.$encoding"
  set diff_file = "wcsconv-${name}.diff"

  ./wcsconverter $in_file $encoding $new_file "$attrs"
  set cstatus = $status

#  wcsconverter reports "no WCS could be read" on stdout and still exits 0,
#  so check that it produced output rather than trusting the exit status.
#  Otherwise a case that reads nothing looks like a pass whenever the row is
#  flagged skip_string_compare and no diff is taken.
  if( $cstatus != 0 || ! -e $new_file ) then
     echo "   wcsconverter produced no output for $name"
     echo "   Command was:"
     echo "      wcsconverter $in_file $encoding $new_file <quote>$attrs<quote>"
     set ok = 0
     continue
  endif

#  Rows flagged skip_string_compare serialise differently between platforms'
#  maths libraries, so only the conversion itself is exercised here.  The ctest
#  suite compares those with compare_dumps, which tolerates a last-bit
#  difference, and semantically with astEqual.
#
#  "astequal" is flagged for the same reason and skipped the same way.  Those
#  rows differ by more than a few ulp -- a value amplified by cancellation --
#  and this script has only a byte-level diff to offer, so diffing them here
#  would report a difference that ctest has already judged acceptable.
  if( "$skip" == "yes" || "$skip" == "astequal" ) then
     @ nskip++
     \rm -f $new_file
     continue
  endif

  diff -c $old_file $new_file > ! $diff_file
  set dstatus = $status

  @ ncmp++
  if( $dstatus == 0 ) then
     \rm -f $diff_file $new_file
  else
     echo "   $old_file and $new_file differ\!\! (see $diff_file)"
     echo "   Command was:"
     echo "      wcsconverter $in_file $encoding $new_file <quote>$attrs<quote>"
     set ok = 0
  endif

end

if( $ok == 1 ) then
   echo "   All $ncmp compared WCS conversion tests passed"
   echo "   ($ncase registered; $nskip left to ctest, which compares them"
   echo "    with a tolerance this script does not have)"
   echo ""
endif


echo ""
echo "Doing Simplification tests..."
echo ""

set ok = 1
@ ncase = 0
@ ncmp = 0
@ nskip = 0
@ nintra = 0
foreach rec ( "`awk -f cases.awk fixtures/simplify/cases.txt`" )

   set f = ( $rec )
   set name = $f[1]
   set n = fixtures/$f[2]
   set expected = fixtures/$f[3]
   set skip = $f[4]

   @ ncase++

#  An IntraMap names a private transformation function that has to be
#  registered before the dump can be read.  simplify.c does that with
#  astIntraReg; simplify.f has no equivalent, so these fixtures cannot be
#  loaded here at all and are left to ctest.
   grep -q IntraMap $n
   if( $status == 0 ) then
      @ nintra++
      continue
   endif

   ./simplify $n ${name}.out
   set cstatus = $status

#  As for wcsconverter above, simplify reports an unreadable input without
#  exiting non-zero.
   if( $cstatus != 0 || ! -e ${name}.out ) then
      echo "   simplify produced no output for $name"
      set ok = 0
      continue
   endif

   if( "$f[2]" == "$f[3]" ) then

#  A fixture that is its own reference asserts astSimplify leaves the Mapping
#  alone.  astSimplify stamps an IsSimp marker on every Mapping it has passed
#  through, so drop those lines from both sides before comparing.  This runs
#  even for rows flagged skip_string_compare, because astEqual compares
#  meaning and so passes a structural rewrite -- exactly what such a fixture
#  exists to catch.
      grep -v -E '^[[:space:]]*IsSimp[[:space:]]*=' $expected > ! ${name}.ref
      grep -v -E '^[[:space:]]*IsSimp[[:space:]]*=' ${name}.out > ! ${name}.new
      diff -c ${name}.ref ${name}.new > ! ${name}.diff
      set dstatus = $status
      \rm -f ${name}.ref ${name}.new

   else if( "$skip" == "yes" || "$skip" == "astequal" ) then
      @ nskip++
      \rm -f ${name}.out
      continue

   else
      diff -c $expected ${name}.out > ! ${name}.diff
      set dstatus = $status
   endif

   @ ncmp++
   if( $dstatus == 0 ) then
      \rm -f ${name}.out ${name}.diff
   else
      echo "   $expected and ${name}.out differ\!\! (see ${name}.diff)"
      set ok = 0
   endif

end

if( $ok == 1 ) then
   echo "   All $ncmp compared simplification tests passed"
   echo "   ($ncase registered; $nskip ulp-unstable and $nintra needing astIntraReg left to ctest)"
   echo ""
   echo ""
endif






\rm -f plotter wcsconverter simplify testxmlchan
