#! /bin/tcsh -f

# xchemprop: convert messy/mbm/tracer/chemprop/messy_main_tracer_chemprop.tbl to f90
# include file and create LaTeX documentation

# Author: Rolf Sander, 2016-....

# To ensure that messy_main_tracer_chemprop.inc is always up-to-date,
# this script is called automatically by messy/smcl/Makefile.m (or
# caaba/main.mk) whenever messy_main_tracer_chemprop.tbl has changed.

##############################################################################

# optional input tbl for tagging
if ( "$1" != "" ) then
  set input = $1
else
  set input = messy_main_tracer_chemprop.tbl
endif
# mz_sg_20170321+
# output file will be generated by messy_main_tracer_chemprop.awk
set output = `basename ${input} .tbl`.inc
# deletion is required if the output is a symlink (e.g. to the tag dir)
rm -f ${output}
# mz_sg_20170321-

##############################################################################

# activate the following 2 lines and then compare the tmp_* files to check
# that the *.tbl file has the same order of species as gas.spc:
#grep "^|" $input | grep -v "^|-" | sed "s/  *| .*//" | sed "s/^| *//" > tmp_tbl
#grep -E ".*=.+;" ../gas.spc | grep -v "^//" | sed "s/ *=.*//" > tmp_spc

##############################################################################

# check that there are no duplicate species in messy_main_tracer_chemprop.tbl:

grep "^|" $input | grep -v "^|-" | sed "s/  *| .*//" | sed "s/^| *//" | sort > tmp_tbl1
uniq tmp_tbl1 > tmp_tbl2
diff tmp_tbl1 tmp_tbl2 > tmp_diff
if ( -s tmp_diff != 0 ) then
  echo "ERROR: duplicate species in ${input}:"
  grep -v "^[0-9]" tmp_diff # show duplicate species but not meaningless line numbers
  exit 1
endif

##############################################################################

# messy_main_tracer_chemprop.awk:
setenv LC_ALL C
gawk -f messy_main_tracer_chemprop.awk ${input}
set exitstatus = "$status"
if ( $exitstatus != '0' ) exit 1

##############################################################################

# LaTeX, if pdflatex is available:
which pdflatex >&! /dev/null
if ( $? != 0 ) then
   echo "WARNING: pdflatex is not in your PATH\!"
else
  pdflatex chemprop
  # create chemprop.bib file, extracting the necessary references from literat.bib:
  if ("$user" == "sander") then
    gawk -f citetags.awk chemprop.aux | sort > citetags.log
    gawk -f citefind.awk citetags.log ~/tex/bib/literat.bib > chemprop.bib
  endif
  bibtex chemprop
  pdflatex chemprop
  pdflatex chemprop
  pdflatex chemprop
endif

##############################################################################

echo;echo "Deleting the temporary xchemprop files:"
set tmpfiles = "tmp_*"
#if (-f ) then
#  set tmpfiles = "$tmpfiles "
#endif
ls -1 $tmpfiles
rm $tmpfiles

##############################################################################

exit

##############################################################################
