#! /bin/tcsh -f
# -*- Shell-script -*- Time-stamp: <2017-09-26 11:34:33 sander>
# Authors: Sebastian Tauer, Hartwig Harder, Rolf Sander (MPI Mainz, 2017)

if ( "$1" == "" ) then
  echo "Create MECCA *.spc and *.eqn files from MCM-generated kpp file"
  echo "Usage:"
  echo "  $0 <myfilename>"
  echo "  Type <myfilename> with or without suffix kpp"
  echo "Example:"
  echo "  $0 limonene"
  exit
endif

# type the MCM-generated *.kpp with or without extension .kpp:
set basefilename = `echo $1 | sed 's/.kpp$//'`
set kppfile = "$basefilename.kpp"
set spcfile = "$basefilename.spc"
set eqnfile = "$basefilename.eqn"

set tmpfile1 = "tmp_1.kpp"
set tmpfile2 = "tmp_2.kpp"

# ----------------------------------------------------------------------------

# Make some adjustments to $kppfile:
# 1) remove \r in case the file comes from a DOS environment:
tr -d '\r' < $kppfile > $tmpfile1
# 2) expand tabs to spaces:
expand $tmpfile1 > $tmpfile2
# 3) rm "USE constants":
grep -iEv '^ *USE constants *$'  $tmpfile2 > $tmpfile1
# 4) put negative Exponents in parentheses, e.g.
#    (TEMP/300)**-6.87 --> (TEMP/300)**(-6.87)
sed 's/\*\*\(-[0-9.]*\)/**(\1)/g' $tmpfile1 > $tmpfile2

# ----------------------------------------------------------------------------

# Generate new eqn file:
gawk -f mcm2mecca.awk -v unkfile=tmp_unknown.kpp -v jsubstfile=Jsubstitution.txt -v photorecfile=tmp_photorec.txt -v spcfile=tmp_allnew.spc -v eqnfile=$eqnfile $tmpfile2 

# Generate new spc file:
# From tmp_allnew.spc, extract those species that are not yet in gas.spc
# and put them into tmp_additional.spc:
./spcmerge.py tmp_allnew.spc tmp_additional.spc
echo "// This file was created automatically by xmcm2kpp, DO NOT EDIT\!" > $spcfile
echo "// PART 1: A copy of gas.eqn:" >> $spcfile
cat ../../gas.spc      >> $spcfile
echo "// PART 2: New species from MCM mechanism:" >> $spcfile
cat tmp_additional.spc >> $spcfile

# ----------------------------------------------------------------------------

echo "$spcfile and $eqnfile were generated from $kppfile"

rm tmp_*

exit
