#! /bin/tcsh -f
# Time-stamp: <2010-11-30 09:53:01 sander>
# Authors:
# Rolf Sander,     Max-Planck-Institute, Mainz, Germany, 2003-...
# Astrid Kerkweg,  Max-Planck-Institute, Mainz, Germany, 2005-2007
# Patrick Joeckel, Max-Planck-Institute, Mainz, Germany, 2007

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

#set echo verbose
set echo_style=both    

echo;echo "xmecca = eXecute KPP on equations from mecca mechanism"
echo "         For more information, read:"
echo "         www.mpch-mainz.mpg.de/~sander/messy/mecca/"

# input files
set gasspcfile        = "gas.spc"
set aqueousspcfile    = "aqueous.spc"
set defaultgaseqnfile = "gas.eqn"
set defaultbatchfile  = "simple.bat"
set aqueouseqnfile    = "aqueous.eqn"
set cloudeqnfile      = "cloud.eqn"
set gastexfile        = "gas.tex"
set aqueoustexfile    = "aqueous.tex"
set diaglist          = "diagtrac.tex"

# input for KPP (selected reactions only):
set spcfile  = "mecca.spc"
set eqnfile  = "mecca.eqn"

# some temporary files:
set awkfile1   = "tmp_1.awk"
set awkfile2   = "tmp_2.awk"
set eqnfile0   = "tmp_0.eqn"
set eqnfile1   = "tmp_1.eqn"
set eqnfile2   = "tmp_2.eqn"
set eqnfile3   = "tmp_3.eqn"
set eqnfile4   = "tmp_4.eqn"
set eqnfile5   = "tmp_5.eqn"
set eqnfile6   = "tmp_6.eqn"
set f90file1   = "tmp_1.f90"
set f90file2   = "tmp_2.f90"
set f90file3   = "tmp_3.f90"
set headerfile = "tmp_header"
set paramfile  = "tmp_param"
set spcfile5   = "tmp_5.spc"
set texfile2   = "tmp_2.tex"
set diagtractexfile = "tmp_diagtrac.tex"
set rxnratestexfile = "tmp_rxnrates.tex"
set tracdeftexfile  = "tmp_tracdef.tex"

# ferret jnl files:
set jnlfile1 = "../jnl/_rxnrates.jnl"
set jnlfile2 = "../jnl/_rxnrates_scaled.jnl"

# define header line
set date_now = `date +"%Y-%m-%d"`
set time_now = `date +"%H:%M:%S"`
set dontedit  = "This file was created automatically by xmecca, DO NOT EDIT\!"
set timestamp = "xmecca was run on $date_now at $time_now by $user on machine $HOST"

# logfile
set logfile = "$PWD/xmecca.log"
echo "$dontedit"   > $logfile
echo "$timestamp" >> $logfile

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

if ( "$1" != "" ) then
  # type batchfile with or without extension .bat:
  #  ":r" does not work for names with more than one dot, e.g., eval2.3
  #  set batchfile = $1:t:r.bat
  set batchfile = `basename $1 .bat`.bat
else
  cd batch
  echo "Available batch files:"
  set inn=0
  set allfiles = *.bat
  foreach i ($allfiles) # list all possibilities
    @ inn=$inn + 1
    printf "%2d) %s\n" $inn $allfiles[$inn]
  end
  echo
  echo "Select a batch file which defines the chemistry mechanism that you"
  echo "want to generate. Please type a number [q=quit]:"
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  if (($inputstring <= $#allfiles) && ($inputstring >= 1)) then
    set batchfile = $allfiles[$inputstring]
  else
    set batchfile = UNDEFINED
  endif
  cd -
endif

if ( -f batch/$batchfile ) then
  set batch
  echo                               | tee -a $logfile
  echo "Using batchfile: $batchfile" | tee -a $logfile
  source batch/$batchfile
else
  echo
  echo "You did not select a valid batch file."
  echo
  echo "The xmecca script will now ask several questions. You can continue"
  echo "and answer all questions interactively or you can quit and create"
  echo "a *.bat file in the mecca/batch directory, e.g. based on simple.bat."
  echo 
  echo "Continue? [y/n/q, default=y]"
  set inputstring = "$<"
  if ( "$inputstring" == "n" ) exit 1
  if ( "$inputstring" == "q" ) exit 1
endif

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

if ( -d ../../../smil ) then
  echo;echo "The directory ../../smil has been found and it is now assumed that"
  echo "MECCA is part of an 3D-BM/MESSy system. xmecca will also create the"
  echo "files necessary for running global MECCA chemistry with 3D-BM/MESSy."
  set bm3d
endif

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

if ${?apn} then
  echo                                 | tee -a $logfile
  echo "From ${batchfile}: apn = $apn" | tee -a $logfile
else
  echo;echo "How many aerosol phases? [q/0...99, default=0]"
  set apn="$<"
  if ( "$apn" == "q" ) exit 1
endif

if ( "$apn" == "" ) set apn=0
if ($apn<0) then
  echo "ERROR: Number of phases is negative."
  exit 1
endif
if ($apn>99) then
  echo "ERROR: Number of aerosol phases is to large"
  exit 1
endif
if ( ("$apn" == "3") && ("$user" != "sander") ) then
  echo "ERROR: do not use APN=3 which is still under construction\!"
  exit 1
endif
echo "Selected number of aerosol phases = $apn" | tee -a $logfile

if ( "$apn" == "0" ) then
  set apn_or_1 = 1
else
  set apn_or_1 = $apn
endif

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

# create complete *.spc file by combining gas and aqueous file
echo "{$dontedit}"   > $spcfile
echo "{$timestamp}" >> $spcfile

# gas phase
echo "{***** START: gas-phase species from $gasspcfile *****}" >> $spcfile
echo "Gas-phase species from:       $gasspcfile"
cat $gasspcfile >> $spcfile
echo "{***** END:   gas-phase species from $gasspcfile *****}" >> $spcfile

# aqueous phase
echo "Aerosol species from:         $aqueousspcfile"
set counter=0
while ($counter<$apn_or_1)
  @ counter=$counter + 1
  echo "{**** START: aerosol species (phase $counter) from $aqueousspcfile ****}" >> $spcfile
  set aerophasename = `printf "%2.2d" $counter`
  echo -n "$aerophasename "
  sed -e 's|##|'$aerophasename'|g' $aqueousspcfile >> $spcfile
  echo "{**** END:   aerosol species (phase $counter) from $aqueousspcfile ****}" >> $spcfile
end
echo ""
# set H2O fixed:
echo "{SETFIX H2O_a* is done via xmecca}" >> $spcfile
set counter=0
while ($counter<$apn)
  @ counter=$counter + 1
  set aerophasename = `printf "%2.2d" $counter`
  echo "#SETFIX H2O_a$aerophasename;" >> $spcfile
end

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

if ${?gaseqnfile} then
  echo                                               | tee -a $logfile
  echo "From ${batchfile}: gaseqnfile = $gaseqnfile" | tee -a $logfile
else
  echo;echo "Available gas phase equation files:"
  set inn=0
  set allfiles = gas*.eqn
  foreach i ($allfiles) # list all possibilities
    @ inn=$inn + 1
    printf "%2d) %s\n" $inn $allfiles[$inn]
  end
  echo "Type the number of a gas phase equation file [q=quit, default=$defaultgaseqnfile]:"
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  if (($inputstring <= $#allfiles) && ($inputstring >= 1)) then
    set gaseqnfile = $allfiles[$inputstring]
    echo "You selected $inputstring) $gaseqnfile" | tee -a $logfile
  else
    set gaseqnfile = $defaultgaseqnfile
    echo "Default selection $defaultgaseqnfile" | tee -a $logfile
  endif
endif

# set correct rpl subdirectory:
if ( "$gaseqnfile" == "gas.eqn" ) then
  set rpldir = rpl
else
  # for strange reasons, gawk only works properly if LC_ALL = C
  setenv LC_ALL C
  set rpldir = rpl/`basename $gaseqnfile .eqn | gawk -F '_' '{print $2}'`
endif

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

if ${?rplfile} then
  echo                                         | tee -a $logfile
  echo "From ${batchfile}: rplfile = $rplfile" | tee -a $logfile
else
  echo;echo "Replacement files allow you to modify the eqation file. Please"
  echo "note: If you apply any *.rpl files to the reaction mechanism, you"
  echo "do so at your own risk. The files provided here are mostly"
  echo "under development. For more information, please contact the"
  echo "authors mentioned in the *.rpl files."
  echo "Do you want to modify $gaseqnfile? [q/0/?, default=0]"
  echo "0) no replacements"
  set inn = "0"
  cd $rpldir
  set allfiles = *.rpl
  cd -
  set allfiles = `echo $allfiles | sed 's|\.rpl||g'` # delete suffix .rpl
  foreach i ($allfiles) # list all possibilities
    @ inn=$inn + 1
    printf "%2d) %s\n" $inn $allfiles[$inn]
  end
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  if(($inputstring <= $#allfiles) && ($inputstring >= 1)) then
    set rplfile = $allfiles[$inputstring]
  else
    set rplfile =
  endif
endif
if ("$rplfile" == "") then
  echo "No replacements with any *.rpl files" | tee -a $logfile
  cp $gaseqnfile $eqnfile0
else
  set fullrplfile = $rpldir/$rplfile.rpl
  if ( -f $fullrplfile) then
    echo "You selected the replacement file: $rplfile" | tee -a $logfile
    # for strange reasons, gawk only works properly if LC_ALL = C
    setenv LC_ALL C
    gawk -f replace.awk -v infile=$gaseqnfile -v outfile=$eqnfile0 $fullrplfile
    if (! ${?batch}) then
      echo "Continue? [y/n/q, default=y]"
      set inputstring = "$<"
      if ( "$inputstring" == "n" ) exit 1
      if ( "$inputstring" == "q" ) exit 1
    endif
  else
    echo "ERROR: Replacement file $fullrplfile does not exist"
    exit 1
  endif
endif

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

echo;echo "Running aerosol.awk. Please wait..."
# for strange reasons, gawk only works properly if LC_ALL = C
setenv LC_ALL C
gawk -f aerosol.awk -v apn=$apn_or_1 -v declfile=$f90file1 \
  -v initfile=$f90file2 $spcfile
# declfile = file with declarations of ind_*_a arrays
# initfile = file with initializations of ind_*_a arrays

# print aqueous definitions at beginning of equation file:
echo "#INLINE F90_GLOBAL"                                      > "$eqnfile1"
echo "  ! from xmecca for aerosol:"                           >> "$eqnfile1"
echo "  INTEGER, PARAMETER, PUBLIC :: APN = $apn_or_1"        >> "$eqnfile1"
cat $f90file1                                                 >> "$eqnfile1"
echo "#ENDINLINE {above lines go to messy_mecca_kpp_global}"  >> "$eqnfile1"

echo "#INLINE F90_UTIL"                                       >> "$eqnfile1"
echo "! from xmecca:"                                         >> "$eqnfile1"
echo "SUBROUTINE initialize_indexarrays"                      >> "$eqnfile1"
echo "  USE messy_mecca_kpp_global     ! ind_XYZ_a(:) arrays" >> "$eqnfile1"
echo "  USE messy_mecca_kpp_parameters ! ind_XYZ_a## scalars" >> "$eqnfile1"
echo "  IMPLICIT NONE"                                        >> "$eqnfile1"
if ($apn>0) cat $f90file2                                     >> "$eqnfile1"
echo "END SUBROUTINE initialize_indexarrays"                  >> "$eqnfile1"
echo "#ENDINLINE {above lines go to messy_mecca_kpp_util}"    >> "$eqnfile1"

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

# create complete *.eqn file by combining gas and aqueous file

# gas phase
echo "Gas-phase reactions from:     $gaseqnfile"
echo "{***** START: gas-phase chemistry from $gaseqnfile *****}" >> $eqnfile1
# $eqnfile0 is either identical to $gaseqnfile or
# it has been modified with a rpl file:
cat $eqnfile0 >> $eqnfile1
echo "{***** END:   gas-phase chemistry from $gaseqnfile *****}" >> $eqnfile1

# aqueous phase
if ($apn>0) then
  echo "Aqueous-phase reactions from: $aqueouseqnfile"
  set counter=0
  while ($counter<$apn)
    @ counter=$counter + 1
    echo "{**** START: aerosol chemistry (phase $counter) from $aqueouseqnfile ****}" >> $eqnfile1
    set aerophasename = `printf "%2.2d" $counter`
    echo -n "$aerophasename "
    sed -e 's|##|'$aerophasename'|g' $aqueouseqnfile >> $eqnfile1
    echo "{**** END:   aerosol chemistry (phase $counter) from $aqueouseqnfile ****}" >> $eqnfile1
    end
  echo ""
else
  echo "No aqueous-phase reactions"
endif

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

# deleting comments starting with // and empty lines:
grep -v "^//" $eqnfile1 | grep -Ev '^ *$' > $eqnfile2

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

# select specific reactions:
if ${?wanted} then
  echo                                       | tee -a $logfile
  echo "From ${batchfile}: wanted = $wanted" | tee -a $logfile
else
  # the symbol for NOT must be escaped in a string as "\!"
  set wanted01 = "((Tr && (G || Het) && \!Cl && \!Br && \!I) || St) && \!Hg"
  set wanted02 = "Tr && G && \!C && \!S && \!Cl && \!Br && \!I && \!Hg"
  set wanted03 = "Tr && (G || (Aa && Mbl)) && \!Hg"
  set wanted04 = "Tr && (G || Aa) && \!Hg"
  set wanted05 = "\!Ara"

  echo ""
  echo "1) EVAL:                           ($wanted01)"
  echo "2) Minimum tropospheric chemistry: ($wanted02)"
  echo "3) Minimum MBL chemistry:          ($wanted03)"
  echo "4) Full MBL chemistry:             ($wanted04)"
  echo "5) Most reactions (no rain chem):  ($wanted05)"
  echo "Only a few standard selections are listed here. For all other"
  echo "purposes, a batch file (mecca/batch/*.bat) should be created."
  set default  = "$wanted01"
  echo "Type the number of your selection or type a boolean"
  echo "expression [q=quit, default=1]:"
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  switch ("$inputstring")
  case "1":
    set wanted = "$wanted01"
    breaksw
  case "2":
    set wanted = "$wanted02"
    breaksw
  case "3":
    set wanted = "$wanted03"
    breaksw
  case "4":
    set wanted = "$wanted04"
    breaksw
  case "5":
    set wanted = "$wanted05"
    breaksw
  default:
    if ( "$inputstring" == "" ) then
      set wanted = "$default"
    else
      set wanted = "$inputstring"
    endif
    breaksw
  endsw
endif

# create awk script
cat > $awkfile1 << EOF
# ----------------------------------------------------------------------------

BEGIN {
logfile  = "wanted.log"
REQ_HET     = ".FALSE."
REQ_PHOTRAT = ".FALSE."
REQ_AEROSOL = ".FALSE."
}

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

# locate returns 1 (=true) if the label is found and 0 (=false) if not
# (a label is a component of the marker)
function locate(label)
  {return (match(\$0,"{%[A-Za-z0-9]*" label "(}|[^a-z][A-Za-z0-9]*})") != 0)}

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

{
# is there a {%...} marker in the current line?
marker = match(\$0,"{%[A-Za-z0-9]*}")
# is current line a comment?
#comment = match(\$0,"^//")
#reaction = match(\$0,"=.+:.+;") && !comment
# is current line a reaction?
reaction = match(\$0,"=.+:.+;")
# altitude:
Tr = locate("Tr")
St = locate("St")
# phase:
Aa   = locate("Aa")
Ara  = locate("Ara")
G    = locate("G")
Het  = locate("Het")
# elements:
C  = locate("C")
N  = locate("N")
F  = locate("F")
S  = locate("S")
Cl = locate("Cl")
Br = locate("Br")
I  = locate("I")
Hg = locate("Hg")
# other:
J  = locate("J")
Mbl= locate("Mbl")
Sc = locate("Sc")
Scm= locate("Scm")

# info for logfile:
printf("\n%s\n",\$0) >> logfile
printf("marker:   %d\n",marker) >> logfile
printf("elements: C=%d N=%d F=%d S=%d Cl=%d Br=%d I=%d Hg=%d\n",C,N,F,S,Cl,Br,I,Hg) >> logfile
printf("phase:    Aa=%d G=%d Ara=%d\n",Aa,G,Ara) >> logfile
printf("other:    Tr=%d St=%d J=%d Het=%d Mbl=%d Sc=%d Scm=%d\n",Tr,St,J,Het,Mbl,Sc,Scm) >> logfile
printf("wanted:   %d\n",($wanted)) >> logfile

# select current line?
if (!marker || ($wanted)) {print >> "$eqnfile"}

# set requirements:
if (Het && ($wanted)) {REQ_HET=".TRUE."}
if (J   && ($wanted)) {REQ_PHOTRAT=".TRUE."}
if (Aa  && ($wanted)) {REQ_AEROSOL=".TRUE."}

# print warnings, if necessary:
if (!Tr && !St && reaction)
  {print "WARNING! No height range (Tr,St) specified for:"; print}
if (!G && !Aa && !Ara && !Het && reaction)
  {print "WARNING! No phase (G,Aa##,Ara,Het) specified for:"; print}
if (G+Aa+Ara+Het>1)
  {print "WARNING! Specify only one phase (G,Aa##,Ara,Het) for:"; print}

}

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

END {
print  ""                                >> "$logfile"
printf "REQ_HET     = %s\n", REQ_HET     >> "$logfile"
printf "REQ_PHOTRAT = %s\n", REQ_PHOTRAT >> "$logfile"
printf "REQ_AEROSOL = %s\n", REQ_AEROSOL >> "$logfile"
print  "#INLINE F90_GLOBAL"                                      >> "$eqnfile"
print  "  ! from xmecca:"                                        >> "$eqnfile"
printf "  LOGICAL, PARAMETER :: REQ_HET     = %s\n", REQ_HET     >> "$eqnfile"
printf "  LOGICAL, PARAMETER :: REQ_PHOTRAT = %s\n", REQ_PHOTRAT >> "$eqnfile"
printf "  LOGICAL, PARAMETER :: REQ_AEROSOL = %s\n", REQ_AEROSOL >> "$eqnfile"
print  "#ENDINLINE {above lines go to messy_mecca_kpp_global}"   >> "$eqnfile"
}

# ----------------------------------------------------------------------------
EOF

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

echo                               | tee -a $logfile
echo "You selected the reactions:" | tee -a $logfile
echo "($wanted)"                   | tee -a $logfile
echo "(later, you will find your selection in messy_mecca_kpp_global.f90)" | tee -a $logfile
echo "Running gawk script to select reactions. Please wait..."
# remove old $eqnfile:
if ( -f $eqnfile ) mv -f $eqnfile $eqnfile~
# select some reactions from $eqnfile2 and put them into $eqnfile:
# for strange reasons, gawk only works properly if LC_ALL = C
setenv LC_ALL C
gawk -f $awkfile1 $eqnfile2

set all_eqns = `grep "=.*:.*;"            $eqnfile | wc -l`
if ("$all_eqns" == "0") then
  echo;echo "ERROR: Your selection created an empty mechanism\!" ; echo
  exit 1
endif

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

# add Monte-Carlo factor to all reactions:
if ${?mcfct} then
  echo                                     | tee -a $logfile
  echo "From ${batchfile}: mcfct = $mcfct" | tee -a $logfile
else
  echo;echo "Add Monte-Carlo factor to all rate coefficients? [y/n/q, default=n]"
  set mcfct = "$<"
endif
if ( "$mcfct" == "q" ) exit 1
cp $eqnfile $eqnfile6
if ( "$mcfct" == "y" ) then
  echo "Running mcfct.awk ..."
  # for strange reasons, gawk only works properly if LC_ALL = C
  setenv LC_ALL C
  gawk -f mcfct.awk $eqnfile6 >! $eqnfile
  set REQ_MCFCT = ".TRUE."
else
  # remove factors from eqn file (necessary inside inlined f90 code):
  sed 's|{§[^}]*}||g' $eqnfile6 >! $eqnfile
  # define dummy array size for MAX_MCEXP:
  echo "#INLINE F90_GLOBAL"                                     >> $eqnfile
  echo "  \! from xmecca:"                                      >> $eqnfile
  echo "  INTEGER, PARAMETER, PUBLIC :: MAX_MCEXP = 1"          >> $eqnfile
  echo "\!KPPPP_DIRECTIVE vector variable definition start"     >> $eqnfile
  echo "  REAL :: mcexp(MAX_MCEXP) \! dummy Monte-Carlo factor" >> $eqnfile
  echo "\!KPPPP_DIRECTIVE vector variable definition end"       >> $eqnfile
  echo "#ENDINLINE {above lines go to messy_mecca_kpp_global}"  >> $eqnfile
  set REQ_MCFCT = ".FALSE."
endif

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

# add diagnostic tracers to $eqnfile
echo -n "" >! $diagtractexfile

if ${?diagtracfile} then
  echo                                                   | tee -a $logfile
  echo "From ${batchfile}: diagtracfile = $diagtracfile" | tee -a $logfile
else
  set inn=0
  cd diagtrac
  set allfiles = *.tex
  cd -
  set allfiles = `echo $allfiles | sed 's|\.tex||g'` # delete suffix .tex
  echo;echo "Add diagnostic tracers to $gaseqnfile? [q/0/?, default=0]"
  echo "0) no diagnostic tracers"
  foreach i ($allfiles) # list all possibilities
    @ inn=$inn + 1
    printf "%2d) %s\n" $inn $allfiles[$inn]
  end
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  if (($inputstring <= $#allfiles) && ($inputstring >= 1)) then
     set diagtracfile = $allfiles[$inputstring]
  else
    set diagtracfile =
  endif
endif

if ("$diagtracfile" == "") then
  echo "No diagtracfile selected" | tee -a $logfile
else
  echo "you selected $diagtracfile"
  # for strange reasons, gawk only works properly if LC_ALL = C
  setenv LC_ALL C
  sed 's|%.*||g' diagtrac/$diagtracfile.tex | sed '/^$/d' >&! $texfile2
  set eqnlist  = `gawk -F '&' '{print $1}' $texfile2 | sed 's| ||g'`
  set traclist = `gawk -F '&' '{print $2}' $texfile2 | sed 's| |_SPACE_|g'`
  if (${#eqnlist} >= 1) then
    echo -n "" >! $spcfile5
    cp -f $eqnfile $eqnfile3
    @ count = 1
    while ($count <= ${#eqnlist})
      set eqnnr = $eqnlist[${count}]
      set dtrac = `echo $traclist[${count}] | sed 's|_SPACE_| |g'`
      echo "adding $dtrac as product to equation $eqnnr"
      # add diagnostic tracer to spcfile:
      # (if $dtrac starts with a factor, then $dtrac[${#dtrac}] only
      # contains the last item, i.e. the name of the diagnostic tracer)
      set dtrac_tex = `echo "$dtrac[${#dtrac}]" | sed 's|_|\\_|g' `
      echo "$dtrac[${#dtrac}] = IGNORE ; {@${dtrac_tex}}" >> $spcfile5
      # add diagnostic tracer to "tracdef.tex":
      echo "'$dtrac[${#dtrac}]' & & AIR & & & OFF & OFF & OFF & & OFF & & OFF & & & & & 1._dp & & & & & & & \\" >> $diagtractexfile
      # add diagnostic tracers to eqnfile:
      gawk -F '>' '{if ($1">" == "'$eqnnr'") \
                      {a=$0; \
                       sub("=","= '"$dtrac"' + ",a); \
                       print a} \
                   else print}' $eqnfile3 >! $eqnfile4
      # op_pj_20100614+
      # mv -f $eqnfile4 $eqnfile3
      sed 's|+[ ]*-| - |g' $eqnfile4 >! $eqnfile3 
      # op_pj_20100614-
      @ count++
    end
  endif
  cp -f $eqnfile3 $eqnfile

  # add diagnostic tracers to spc file:
  echo "{--- diagnostic tracers from $diagtracfile.tex, added via xmecca ---}" >> $spcfile
  echo "#DEFVAR" >> $spcfile
  sort $spcfile5 | uniq >> $spcfile

  if (! ${?batch}) then
    echo "Continue? [y/n/q, default=y]"
    set inputstring = "$<"
    if ( "$inputstring" == "n" ) exit 1
    if ( "$inputstring" == "q" ) exit 1
    echo ""
  endif
endif

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

# add product to all reactions for calculation of accumulated reaction rates:
if ${?rxnrates} then
  echo                                           | tee -a $logfile
  echo "From ${batchfile}: rxnrates = $rxnrates" | tee -a $logfile
else
  echo;echo "Calculate accumulated reaction rates of all equations? [y/n/q, default=n]"
  set rxnrates = "$<"
endif
if ( "$rxnrates" == "q" ) exit 1
if ( "$rxnrates" == "y" ) then
  echo -n "" >! $spcfile5
  echo "#DEFVAR" >> $spcfile
  cp -f $eqnfile $eqnfile4
  gawk '{if ($1 ~ /^</) {nr=$1; gsub("<","RR",nr); gsub(">","",nr);\
       sub("=","= "nr" + ",$0); \
       print nr" = IGNORE ; {@"nr"} {diagnostic tracer}" > "'$spcfile5'"; \
       print "_QUOTE_"nr"_QUOTE_ & & AIR & & & OFF & OFF & OFF & & OFF & & OFF & & & & & 1._dp & & & & & & & \\\\" > "'$rxnratestexfile'"} \
       print }' $eqnfile4 > $eqnfile5
  # create real apostrophies:
  sed -e "s|_QUOTE_|'|g" $rxnratestexfile > $texfile2
  # split aqueous-phase species into basename and subname:
  sed -e "s|_a\([0-9][0-9]\)' & & AIR &|' \& 'a\1' \& AEROSOL \&|" $texfile2 > $rxnratestexfile
  cp -f $eqnfile5 $eqnfile
  echo "{**** START: accumulated reaction rates ****}" >> $spcfile
  cat $spcfile5 >> $spcfile
  echo "{**** END: accumulated reaction rates ****}" >> $spcfile
  echo "pseudo-KPP species RR* have been added for accumulated reaction rates"
  # create jnl files for reaction rates:
  # for strange reasons, gawk only works properly if LC_ALL = C
  setenv LC_ALL C
  gawk -f rxnrates.awk -v jnlfile1=$jnlfile1 -v jnlfile2=$jnlfile2 $eqnfile
else
  set rxnrates = "n"
  if (-f $jnlfile1) rm $jnlfile1
  if (-f $jnlfile2) rm $jnlfile2
endif

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

if ${?tagdbl} then
  echo                                       | tee -a $logfile
  echo "From ${batchfile}: tagdbl = $tagdbl" | tee -a $logfile
else
  echo;echo "Tagging, doubling, both, or none? [t/d/b/n/q, default=n]"
  echo "(under construction, please just press Return)"
  set tagdbl = "$<"
endif
if ( "$tagdbl" == "q" ) exit 1
if ( "$tagdbl" == "" ) set tagdbl = "n"

# doubling
cd dbl
if ( ( "$tagdbl" == "d" ) || ( "$tagdbl" == "b" ) ) then
  if (${?batch}) then
     ./xdbl norm $batchfile
  else
     ./xdbl norm
  endif
else
  # calling to setup zero configuration
  ./xdbl zero  
endif
cd -

# tagging
cd tag
if ( ( "$tagdbl" == "t" ) || ( "$tagdbl" == "b" ) ) then
  if (${?batch}) then
    ./xtag norm $batchfile
  else
    ./xtag norm
  endif
else
  # calling to setup zero configuration
  ./xtag zero
endif
cd -

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

# write header:
mv -f $eqnfile $eqnfile4
echo "{$dontedit}"                                              > $eqnfile
echo "#INLINE F90_GLOBAL"                                      >> $eqnfile
echo "  ! MECCA info from xmecca:"                             >> $eqnfile
echo "  CHARACTER(LEN=*), PUBLIC, PARAMETER :: &"              >> $eqnfile
echo "    timestamp            = '$timestamp', &"              >> $eqnfile
echo "    gas_spc_file         = '`ls -l $gasspcfile`', &"     >> $eqnfile
echo "    aqueous_spc_file     = '`ls -l $aqueousspcfile`', &" >> $eqnfile
echo "    gas_eqn_file         = '`ls -l $gaseqnfile`', &"     >> $eqnfile
echo "    aqueous_eqn_file     = '`ls -l $aqueouseqnfile`', &" >> $eqnfile
echo "    gas_spc_file_sum     = '`sum $gasspcfile`', &"       >> $eqnfile
echo "    aqueous_spc_file_sum = '`sum $aqueousspcfile`', &"   >> $eqnfile
echo "    gas_eqn_file_sum     = '`sum $gaseqnfile`', &"       >> $eqnfile
echo "    aqueous_eqn_file_sum = '`sum $aqueouseqnfile`', &"   >> $eqnfile
echo "    rplfile              = '$rplfile', &"                >> $eqnfile
echo "    wanted               = '$wanted', &"                 >> $eqnfile
echo "    diagtracfile         = '$diagtracfile', &"           >> $eqnfile
echo "    rxnrates             = '$rxnrates', &"               >> $eqnfile
echo "    tagdbl               = '$tagdbl'"                    >> $eqnfile
echo "  LOGICAL, PARAMETER :: REQ_MCFCT = $REQ_MCFCT"          >> $eqnfile
echo "#ENDINLINE {above lines go to messy_mecca_kpp_global}"   >> $eqnfile
cat $eqnfile4                                                  >> $eqnfile

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

# define path to KPP (via pwd command to resolve symbolic links):
setenv KPP_HOME "`cd kpp;pwd`"

set KPP_VERSION = `grep KPP_VERSION $KPP_HOME/src/gdata.h | sed 's|.*"\(.*\)".*|\1|g'`
echo;echo "Please verify that the KPP version is 2.2.1_rs*"
echo "KPP_HOME    = $KPP_HOME"
echo "KPP version = $KPP_VERSION"

if ${?kppoption} then
  echo                                             | tee -a $logfile
  echo "From ${batchfile}: kppoption = $kppoption" | tee -a $logfile
  if ( "$kppoption" == "q" ) exit 1
else
  echo;echo "Run KPP?"
  echo "y = Yes, run KPP (default)"
  if (${?bm3d}) then
    echo "4 = run KPP via KP4"
  endif
  echo "q = Quit"
  set inputstring = "$<"
  if ( "$inputstring" == "q" ) exit 1
  set kppoption = "k"
  if ( "$inputstring" == "4" ) then
    if (${?bm3d}) then
      set kppoption = "4"
    else
      echo "KP4 is not available."
      exit 1
    endif
  endif
  echo "kppoption = $kppoption" >> $logfile
endif

echo "removing all KPP-generated files from previous xmecca run"
rm -f smcl/messy_mecca_kpp*.f90* # f90* includes f90-ori

echo                                   | tee -a $logfile
echo "Fixed species are:"              | tee -a $logfile
grep -i "^#setfix" messy_mecca_kpp.kpp | tee -a $logfile

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

if ( "$kppoption" == "k" ) then

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

  if ${?integr} then
    echo                                       | tee -a $logfile
    echo "From ${batchfile}: integr = $integr" | tee -a $logfile
  else
    set defaultintegr = "rosenbrock_posdef"
    echo                         >> $logfile
    echo "Numerical integrator:" >> $logfile
    cd $KPP_HOME/int
    echo "Available KPP integrators:"
    set inn      = "0"
    set allfiles = *.f90
    set allfiles = `echo $allfiles | sed 's|\.f90||g'` # delete suffix .f90
    foreach i ($allfiles) # list all possibilities
      @ inn=$inn + 1
      printf "%2d) %s\n" $inn $allfiles[$inn]
    end
    echo "The Rosenbrock integrators with automatic time-step control are"
    echo "strongly recommended for their ability to cope with stiff sets of"
    echo "differential equations. If you choose another integrator, do so at"
    echo "your own risk\!"
    echo "Type the number of an integrator [q=quit, default=$defaultintegr]:"
    set inputstring = "$<"
    if ( "$inputstring" == "q" ) exit 1
    if (($inputstring <= $#allfiles) && ($inputstring >= 1)) then
      set integr = "$allfiles[$inputstring]"
      echo "You selected: $inputstring) $integr" | tee -a $logfile
    else
      set integr = "$defaultintegr"
      echo "Default selection: $integr" | tee -a $logfile
    endif
    cd -
  endif
  echo "#INTEGRATOR $integr" >! integr.kpp

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

  echo "#INLINE F90_GLOBAL"                                    >> integr.kpp
  echo "  ! KPP info from xmecca (via integr.kpp):"            >> integr.kpp
  echo "  CHARACTER(LEN=*), PUBLIC, PARAMETER :: &"            >> integr.kpp
  echo "    mecca_spc_file     = '`ls -l $spcfile`', &"        >> integr.kpp
  echo "    mecca_eqn_file     = '`ls -l $eqnfile`', &"        >> integr.kpp
  echo "    mecca_spc_file_sum = '`sum $spcfile`', &"          >> integr.kpp
  echo "    mecca_eqn_file_sum = '`sum $eqnfile`', &"          >> integr.kpp
  echo "    kppoption          = '$kppoption', &"              >> integr.kpp
  echo "    KPP_HOME           = '$KPP_HOME', &"               >> integr.kpp
  echo "    KPP_version        = '$KPP_VERSION', &"            >> integr.kpp
  echo "    integr             = '$integr'"                    >> integr.kpp
  echo "#ENDINLINE {above lines go to messy_mecca_kpp_global}" >> integr.kpp

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

  echo;echo "Running KPP with the commands:"
  echo "setenv KPP_HOME $KPP_HOME"
  echo '$KPP_HOME/bin/kpp messy_mecca_kpp.kpp'
  echo "Please wait..."
  $KPP_HOME/bin/kpp messy_mecca_kpp.kpp | tee -a $logfile
  set exitstatus = "$status"
  echo "exit status from KPP is: $exitstatus"
  if ( "$exitstatus" != "0" ) exit 1

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

  # add USE messy_cmn_photol_mem:
  mv messy_mecca_kpp_Global.f90 tmp_messy_mecca_kpp_Global_f90
  sed 's|\(USE messy_mecca_kpp_Parameters\)|USE messy_cmn_photol_mem ! IP_MAX, ip_*, jname\n  \1|' tmp_messy_mecca_kpp_Global_f90 > messy_mecca_kpp_Global.f90

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

  echo;echo "creating mecca core files in smcl/"

  # produce a copy of the parameter file because it will be needed later:
  cp messy_mecca_kpp_Parameters.f90 $paramfile

  # move the KPP-generated *.f90 files (except for _Model) into the smcl/
  # directory and change the file names to lowercase:
  set kppparts = ("Function" "Global" "Initialize" "Integrator" "Jacobian" "JacobianSP" "LinearAlgebra" "Monitor" "Parameters" "Precision" "Rates" "Util")
  foreach kpppart ($kppparts)
    set kppfile = "messy_mecca_kpp_$kpppart.f90"
    set smclfile = smcl/`echo "$kppfile" | tr '[A-Z]' '[a-z]'`
    echo "creating $smclfile"
    mv $kppfile $smclfile
  end

  # KPP/KP4 compatibility file:
  cp template_messy_mecca_kpp.f90 smcl/messy_mecca_kpp.f90

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

  # mz_pj_20070823+
  if (${?bm3d}) then
    if ${?decomp} then
      echo                                       | tee -a $logfile
      echo "From ${batchfile}: decomp = $decomp" | tee -a $logfile
    else
      echo;echo "Remove indirect indexing with decomp? [y/n/q, default=n]"
      set decomp = "$<"
    endif
    echo "decomp = $decomp" >> $logfile 
    if ( "$decomp" == "q" ) exit 1
    if ( "$decomp" == "y" ) then
      cp -f smcl/messy_mecca_kpp_linearalgebra.f90 smcl/messy_mecca_kpp_linearalgebra.f90-ori
      cp -f smcl/messy_mecca_kpp_integrator.f90 smcl/messy_mecca_kpp_integrator.f90-ori
      (cd decomp ; ./xdecomp $integr)
    endif
  endif
  # mz_pj_20070823-

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

endif # (if kppoption = k)

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

if ( "$kppoption" == "4" ) then
  echo "running KPP via KP4 (kppoption=4)" | tee -a $logfile
  cd ../../../tools/kp4
  if (${?batch}) then
     ./bin/kp4.tcsh mecca $batchfile | tee -a $logfile
  else
     ./bin/kp4.tcsh mecca | tee -a $logfile
  endif
  if ( "$status" != "0" )  exit 1
  cd -
  # add USE messy_cmn_photol_mem:
  mv messy_mecca_kpp.f90 tmp_messy_mecca_kpp_f90
  sed 's|\(USE messy_mecca_kpp_Parameters\)|USE messy_cmn_photol_mem ! IP_MAX, ip_*, jname\n  \1|' tmp_messy_mecca_kpp_f90 > messy_mecca_kpp.f90
endif

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

if (${?bm3d}) then

  # create a tracer definition ("tracdef") file by combining gas.tex and
  # aqueous.tex for all selected aerosol phases:
  cat $gastexfile > $tracdeftexfile
  set counter=0
  while ($counter<$apn)
    @ counter=$counter + 1
    set aerophasename = `printf "%2.2d" $counter`
    echo -n "$aerophasename "
    sed -e "s|##|$aerophasename|g" $aqueoustexfile >> $tracdeftexfile
  end
  echo ""
  if ("$diagtracfile" != "") then
    # add diagnostic tracers:
    echo "% diagnostic tracers from $diagtracfile.tex, added via xmecca:" >> $tracdeftexfile
    sort $diagtractexfile | uniq >> $tracdeftexfile
  endif
  if ( "$rxnrates" == "y" ) then
    # accumulated reaction rates:
    echo "% START: accumulated reaction rates" >> $tracdeftexfile
    cat                       $rxnratestexfile >> $tracdeftexfile
    echo "% END: accumulated reaction rates"   >> $tracdeftexfile
  endif
  #  mz_sg_20090730+
  if ( ( "$tagdbl" == "d" ) || ( "$tagdbl" == "b" ) ) then
    # doubled tracers:
    echo "% START: doubled tracers" >> $tracdeftexfile
    cat dbl/messy_mecca_dbl*.tex    >> $tracdeftexfile
    echo "% END: doubled tracers"   >> $tracdeftexfile
  endif
  #  mz_sg_20090730-

  # tracdef.awk extracts all KPP_XXX from $paramfile and inserts these
  # species into messy_mecca_idt_si.inc. For all KPP_XXX that are not zero
  # it also inserts the species into messy_mecca_c2mr_si.inc,
  # messy_mecca_mr2c_si.inc, and messy_mecca_trac_si.inc, using the tracer
  # info in $tracdeftexfile.

  # for strange reasons, gawk only works properly if LC_ALL = C
  setenv LC_ALL C
  gawk -f tracdef.awk -v tracdef=$tracdeftexfile $paramfile

endif

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

# update links to all KPP-generated f90 files in mecca/smcl/ directory:

# for caaba box model:
cd ..
# remove all kpp files, since it is unclear how many are present (kpp or kp4)
rm -f messy_mecca_kpp*.f90
rm -f messy_mecca.f90
rm -f messy_mecca_aero.f90
rm -f messy_mecca_khet.f90
#set kppfiles = (`find mecca/smcl -name "messy_mecca_kpp*.f90" -print`)
set kppfiles = (mecca/smcl/*.f90)
foreach kppfile ($kppfiles)
  ln -s $kppfile .
end
set MECCA_VERSION = `grep -i "modver *=" messy_mecca.f90 | sed "s|.*'\(.*\)'.*|\1|g"`
cd -

# for ECHAM5/MESSy:
if (${?bm3d}) then
  cd ../../../smcl
  rm -f messy_mecca_kpp*.f90
  #  mz_sg_20090807+
  # set kppfiles = (../mbm/caaba/mecca/smcl/messy_mecca_kpp*.f90)
  # (`find ../mbm/caaba/mecca/smcl -name "messy_mecca_kpp*.f90" -print`)
  set kppfiles = (../mbm/caaba/mecca/smcl/messy_mecca_kpp*.f90 ../mbm/caaba/mecca/smcl/messy_mecca_dbl*.f90 ../mbm/caaba/mecca/smcl/messy_mecca_tag*.f90 ../mbm/caaba/mecca/smcl/messy_mecca_dbl*.inc ../mbm/caaba/mecca/smcl/messy_mecca_tag*.inc)
  rm -f messy_mecca_dbl*.f90 messy_mecca_dbl*.inc
  rm -f messy_mecca_tag*.f90 messy_mecca_tag*.inc
  #  mz_sg_20090807-
  foreach kppfile ($kppfiles)
    ln -s $kppfile .
  end
  cd -
endif

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

# count number of selected species:
set all_spc = `grep -iE ":: ind_.* = [1-9]+"             $paramfile | wc -l`
set aq_spc  = `grep -iE ":: ind_.*_a[0-9][0-9] = [1-9]+" $paramfile | wc -l`
@ gas_spc = $all_spc - $aq_spc
echo                                            | tee -a $logfile
echo "Number of species in selected mechanism:" | tee -a $logfile
echo "gas phase:          $gas_spc"             | tee -a $logfile
echo "aqueous phase:      $aq_spc"              | tee -a $logfile
echo "all species:        $all_spc"             | tee -a $logfile

# count number of selected reactions:
set all_eqns = `grep "=.*:.*;"            $eqnfile | wc -l`
set G_eqns   = `grep "<G[0-9].*=.*:.*;"   $eqnfile | wc -l`
set A_eqns   = `grep "<A[0-9].*=.*:.*;"   $eqnfile | wc -l`
set H_eqns   = `grep "<H[0-9].*=.*:.*;"   $eqnfile | wc -l`
set J_eqns   = `grep "<J[0-9].*=.*:.*;"   $eqnfile | wc -l`
set PH_eqns  = `grep "<PH[0-9].*=.*:.*;"  $eqnfile | wc -l`
set HET_eqns = `grep "<HET[0-9].*=.*:.*;" $eqnfile | wc -l`
set EQ_eqns  = `grep "<EQ[0-9].*=.*:.*;"  $eqnfile | wc -l`
set DG_eqns  = `grep "<DG[0-9].*=.*:.*;"  $eqnfile | wc -l`
set D_eqns   = `grep "<D[0-9].*=.*:.*;"   $eqnfile | wc -l`
# sum over these reaction types:
@ sum = $G_eqns + $A_eqns + $H_eqns + $J_eqns + $PH_eqns + $HET_eqns + $EQ_eqns + $DG_eqns + $D_eqns
echo                                                | tee -a $logfile
echo "Number of reactions in selected mechanism:"   | tee -a $logfile
echo "gas phase      G:   $G_eqns"                  | tee -a $logfile
echo "aqueous phase  A:   $A_eqns"                  | tee -a $logfile
echo "Henry          H:   $H_eqns"                  | tee -a $logfile
echo "photolysis     J:   $J_eqns"                  | tee -a $logfile
echo "aq. photolysis PH:  $PH_eqns"                 | tee -a $logfile
echo "heterogeneous  HET: $HET_eqns"                | tee -a $logfile
echo "equilibria     EQ:  $EQ_eqns"                 | tee -a $logfile
echo "isot. exchange DG:  $DG_eqns"                 | tee -a $logfile
echo "dummy          D:   $D_eqns"                  | tee -a $logfile
echo "all equations:      $all_eqns"                | tee -a $logfile
if ( "$sum" != "$all_eqns" ) then
  echo "sum of the above:   $sum"                   | tee -a $logfile
  echo "WARNING: sum is not equal to all equations" | tee -a $logfile
endif

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

cd latex

if (-f meccanism.pdf) rm meccanism.pdf
set infofile = mecca_info.tex
echo "% $dontedit"                                  > $infofile
echo "% $timestamp"                                >> $infofile
echo "\\def\\meccaversion{\\code{$MECCA_VERSION}}" >> $infofile
echo "\\def\\kppversion{\\code{$KPP_VERSION}}"     >> $infofile
echo "\\def\\wanted{\\code{$wanted}}"              >> $infofile
echo "\\def\\apn{$apn}"                            >> $infofile
echo "\\def\\gasspc{$gas_spc}"                     >> $infofile
echo "\\def\\aqspc{$aq_spc}"                       >> $infofile
echo "\\def\\allspc{$all_spc}"                     >> $infofile
echo "\\def\\Geqns{$G_eqns}"                       >> $infofile
echo "\\def\\Aeqns{$A_eqns}"                       >> $infofile
echo "\\def\\Heqns{$H_eqns}"                       >> $infofile
echo "\\def\\Jeqns{$J_eqns}"                       >> $infofile
echo "\\def\\HETeqns{$HET_eqns}"                   >> $infofile
echo "\\def\\EQeqns{$EQ_eqns}"                     >> $infofile
echo "\\def\\DGeqns{$DG_eqns}"                     >> $infofile
echo "\\def\\Deqns{$D_eqns}"                       >> $infofile
echo "\\def\\alleqns{$all_eqns}"                   >> $infofile
# for strange reasons, gawk only works properly if LC_ALL = C
setenv LC_ALL C
gawk -f spc2tex.awk   ../$spcfile
gawk -f eqn2tex.awk   ../$eqnfile
gawk -f henry2tex.awk -v paramfile=$paramfile ../../messy_cmn_gasaq.f90
gawk -f alpha2tex.awk -v paramfile=$paramfile ../../messy_cmn_gasaq.f90

if ${?latex} then
  echo                                     | tee -a $logfile
  echo "From ${batchfile}: latex = $latex" | tee -a $logfile
else
  echo;echo "Create LaTeX listing of selected mechanism? [y/n/q, default=n]"
  set latex = "$<"
endif
if ( "$latex" == "q" ) exit 1
if ( "$latex" == "y" ) then
  pdflatex meccanism.tex
  bibtex meccanism
  pdflatex meccanism.tex
  pdflatex meccanism.tex
  pdflatex meccanism.tex
  if ( -e `which evince` ) then
    evince meccanism.pdf >& /dev/null &
  else
    acroread meccanism.pdf &
  endif
endif

cd -

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

if ( -e `which dot` ) then
  if ${?graphviz} then
    echo                                           | tee -a $logfile
    echo "From ${batchfile}: graphviz = $graphviz" | tee -a $logfile
  else
    echo;echo "Create graphviz plots of selected mechanism? [y/n/q, default=n]"
    set graphviz = "$<"
  endif
  if ( "$graphviz" == "q" ) exit 1
  if ( "$graphviz" == "y" ) then
    cd graphviz
    ./xgraphvizall
    cd -
  endif
endif

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

# $spcfile and $eqnfile removed from list of tmpfiles
set tmpfiles = "tmp_*"
if (-f latex/meccanism.aux) then
  set tmpfiles = "$tmpfiles latex/meccanism.aux"
endif
if (-f latex/meccanism.bbl) then
  set tmpfiles = "$tmpfiles latex/meccanism.bbl"
endif
if (-f latex/meccanism.blg) then
  set tmpfiles = "$tmpfiles latex/meccanism.blg"
endif
# temporary KPP files:
if (-f messy_mecca_kpp_Model.f90) then
  set tmpfiles = "$tmpfiles messy_mecca_kpp_Model.f90"
endif
if (-f messy_mecca_kpp.map) then
  set tmpfiles = "$tmpfiles messy_mecca_kpp.map"
endif
if (-f Makefile_messy_mecca_kpp) then
  set tmpfiles = "$tmpfiles Makefile_messy_mecca_kpp"
endif
if ${?deltmp} then
  echo                                       | tee -a $logfile
  echo "From ${batchfile}: deltmp = $deltmp" | tee -a $logfile
else
  echo;echo "Do you want to delete the temporary xmecca files"
  ls -1 $tmpfiles
  echo "[y/n/q, default=y]?"
  set deltmp = "$<"
endif
if ( "$deltmp" == "q" ) exit 1
if ( "$deltmp" != "n" ) then
  echo "Deleting the temporary xmecca files:" | tee -a $logfile
  ls -1 $tmpfiles | tee -a $logfile
  if (${?TRASH}) then
    # move to trash directory:
    mv -f $tmpfiles $TRASH
  else
    # or delete:
    rm -f $tmpfiles
  endif
endif

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

exit
