#!/bin/csh

# -----------------------------------------------------------------------------------------------------------------
# Usage and parameter handling
# -----------------------------------------------------------------------------------------------------------------

# Write usage information
if ( ${#argv} == 0 ) then
  echo 
  echo "-----------------------------------------------------------------------------------------------------------"
  echo "Usage: startf <date> <ofile> <specifier> [ -t tvfile ] [ -changet ] [-noclean]"
  echo 
  echo "      date      : Date of input P and S file (e.g. 20100101_00)"
  echo "      ofile     : Output file with start points (e.g. startf)"
  echo "      tvfile    : Tracing file with variables for selection criteria "
  echo "      changet   : Flag whether to change times on P,S files before calculation"
  echo "      clean     : Flag whether to remove temporary files"
  echo "      specifier : Detailed description of starting positions"
  echo 
  echo "The specification <specifier> is of the form:"
  echo
  echo "      <specifier>  = <horizontal> @ <vertical> @ <unit> @ <selection>"
  echo 
  echo "      <horizontal> = file[filename]                  : Read lat/lon from file"
  echo "                     line[lon1,lon2,lat1,lat2,n]     : n points from (lon1,la1) to (lon2,lat2)"
  echo "                     box.eqd[lon1,lon2,lat1,lat2,ds] : lat/lon box with equdistant points (ds in [km])"
  echo "                     box.grid[lon1,lon2,lat1,lat2,]  : lat/lon box with grid points"
  echo "                     point[lon,lat]                  : Single lon/lat point"
  echo "                     shift[lon,lat,dlon,dlat]        : lon/at points and dlon/dlat shifhted ones"
  echo "                     polygon.eqd[filename,ds]        : Equidistant within arbirtrary polygon (ds in [km])"
  echo "                     polygon.grid[filename]          : Grid points within arbirtrary polygon"
  echo 
  echo "                     Polygon file is of the format   : lat/lon within polygon"
  echo "                                                       lat1,lon1"
  echo "                                                       lat2,lon2"
  echo "                                                       ..."
  echo
  echo "      <vertical>   = file[filename]                  : Read lev from file"
  echo "                   = level[lev]                      : Start from single level"
  echo "                   = list[l1v1,lev2,lev3,...]        : List of levels"
  echo "                   = profile[lev1,lev2,n]            : n equdistant levels betwenn lev1 and lev2"
  echo
  echo "      <unit>       = hPa                             : Pressure [hPa]"
  echo "                   = hPa,agl                         : Pressure above ground [hPa]"
  echo "                   = K                               : Isentropic level [K]"
  echo "                   = PVU                             : PV surface [PVU]"
  echo 
  echo "      <selection>  = same syntax as for the programme <select>"
  echo
  echo "      If <vertical=nil>, then <horizontal> must be equal to <file> and all lat/lon/lev coordinates are"
  echo "      read from a file. "
  echo 
  echo "      Example: 'box.eqd[10,30,30,70,50] @ profile[100,500,10] @ hPa @ GT:PV:2'"
  echo "------------------------------------------------------------------------------------------------------------"
  exit 1
endif

# -----------------------------------------------------------------------------------------------------------------
# Handle input parameters
# -----------------------------------------------------------------------------------------------------------------

# Prefix of primary and secondary file; and set the filenames
set charp='P'
set chars='S'

# Write title
echo 
echo '========================================================='
echo '       *** START OF PREPROCESSOR STARTF ***              '
echo

# Extract arguments and split reference date
set refdate   = $1
set ofile     = $2
set specifier = `echo $3` 
shift
shift
shift

# Check whether specifier is a file or whether it is explicitly written
set flag_criterion = 'file'
set test = `echo ${specifier} | grep '@' | wc -c`
if ( "${test}" != "0" ) then 
  set flag_criterion = 'criterion'
endif

# Get the criterion from the file
if ( "${flag_criterion}" == "file" ) then
    if ( -f ${specifier} ) then
       set filename  = ${specifier}
       set specifier = `cat ${specifier}`
    else
       echo " ERROR: cannot read criterion from file ${specifier}... Stop"
       exit 1
    endif
endif

echo "---- INPUT PARAMETERS ----------------------------------"
echo 
echo "Reference date        : ${refdate}"
if ( "${flag_criterion}" == "criterion" ) then 
   echo "Specifier             : ${specifier}"
else
   echo "Specifier             : ${specifier} [from file ${filename}]"
endif
echo "Output file           : ${ofile}"
echo

# Handle optional arguments
set tvfile    = 'tracevars'
set changet   = 'false'
set noclean   = 'false'
set regionf   = 'regionf'
set timecheck = 'no' 

while ( $#argv > 0 )

  switch ( $argv[1] )

   case -t
     set tvfile = $argv[2]
     echo "tvfile                -> ${tvfile} (user defined)"
     shift;
   breaksw

   case -changet
     set changet = 'true'
     echo "changet               -> true (user defined)"
   breaksw

   case -noclean
     set noclean = 'true'
     echo "noclean               -> true (user defined)"
   breaksw

   case -notimecheck
     set timecheck = 'no'
     echo "timecheck               -> no (user defined)"
   breaksw

   case -regionf
     set regionf = $argv[2]
     echo "regionf                -> ${regionf} (user defined)"
     shift;
   breaksw

   endsw
 
   shift;

end

# No change of times necessary if no check requested
if ( "${timecheck}" == "no" ) then
   set  changet = 'false'
endif

# Split the reference date
set yyyy=`echo ${refdate}   | cut -c 1-4` 
set   mm=`echo ${refdate}   | cut -c 5-6` 
set   dd=`echo ${refdate}   | cut -c 7-8` 
set   hh=`echo ${refdate}   | cut -c 10-11` 
set  min=`echo ${refdate}00 | cut -c 12-13` 

# Set base directories (run+prog)
set tradir=${PWD}

# Set program paths and filenames 
set parfile=${tradir}/startf.param 
set crifile=${tradir}/startf.criterion

# Decide whether a tracing and selection is necessary
# If so, some intermediate file are writen (in Fortran binary)
set flag_criterion = `${LAGRANTO}/startf/startf.perl "${specifier}" | tail -1` 
if ( "${flag_criterion}" != "nil" ) then
    set format1 = ".3"
    set format2 = ".3"
else
    set format1 = ""
    set format2 = ""
endif

# Write status information
echo
echo '---- DIRECTORIES AND PROGRAMS ---------------------------'
echo    
echo "PROGRAM CREATE_STARTF : ${LAGRANTO}/startf/startf"
echo "PARAMETER file        : ${parfile}"
echo "CRITERION file        : ${crifile}"
echo "RUN directory         : ${tradir}"
echo

# -----------------------------------------------------------------------------------------------------------------
# Set the primary and secondary data files (necessary for interpolation if intermediate reference date)
# -----------------------------------------------------------------------------------------------------------------

# Find a first data file (if possible corresponding to reference date) -> <file>
set file=${charp}${yyyy}${mm}${dd}_${hh}
if ( ( -f ${file} ) && ( ${min} == 0 ) ) then
   set timeshift=0
   set date0=${yyyy}${mm}${dd}_${hh}
   set date1=${yyyy}${mm}${dd}_${hh}
   set pfile0=${file}
   set pfile1=${file}
   goto label3
else
  set file=`ls ${charp}[0-9_]*[0-9] | head -1 | sed -e 's/@//'`
endif

# Determine time increment (in hours) between data files -> <timeinc>
set date1=`echo $file | cut -c 2-`
set n=`ls ${charp}[0-9_]*[0-9] | grep -n $date1 | awk -F: '{print $1}'`
@ n ++
set date2=`ls ${charp}[0-9_]*[0-9] | head -$n | tail -1 | cut -c 2-`
set timeinc=`${LAGRANTO}/goodies/gettidiff $date2 $date1`
if ( $timeinc == 0 ) then
    echo " ERROR: cannot set the time increment between input files ***"
    exit 1
endif

# Decide whether the time increment is smaller than 1 h; if so set the hires 
# flag and convert the time increment into fractional hour
set flag = `echo ${timeinc} | grep -n '\.'`
set hires = 0

if ( "${flag}" != "" ) then
  echo "Input files availability < 1 hour ($timeinc): switch to hires"
  echo "mode. All input files must be of form: P{yyyymmdd_hhmm}"
  set hires = 1
  set timeinc_min = `echo "(${timeinc} * 100 + 0.5)/1" | bc`
  set timeinc     = `echo "scale=2; ${timeinc} * 100 / 60" | bc`
  goto hires
endif

# Search the first file to use
set timeshift=
foreach i ( ${charp}????????_?? )

  set date0 = `echo $i | cut -c 2-12`
  set td1  = `${LAGRANTO}/goodies/gettidiff ${yyyy}${mm}${dd}_${hh} ${date0}`

  if ( ( $td1 >= 0 ) && ( $td1 < $timeinc ) )  then
      set timeshift=$td1
      set pfile0=${charp}${date0}
      goto label2
  endif

end

# Check if no P files are available for the specified time period
if ( $timeshift == "" ) then
  echo " ERROR: no data files available for the specified reference date"
  exit 1
endif

# If the input files come with time increment < 1 hour, handle it in this
# special section. The aim is not to 'interfere' with the well established
# code handling the standard case with time increment >= 1 hour. In this mode
# we require that the start and end date are available as P files: no start is
# allowed between the model output files
hires:

set flag = "nil"
set td = 0

set timeshift = 0
set date0 = ${yyyy}${mm}${dd}_${hh}${min}
set date1 = `${LAGRANTO}/goodies/newtime ${date0} ${timeinc_min}`

set pfile0 = ${charp}${date0}
set pfile1 = ${charp}${date1}

if ( ! -f ${pfile0} ) then
  echo
  echo " ERROR: no data files available for the specified time period (hires,$date0)"
  exit 1
endif 
if ( ! -f ${pfile1} ) then
  echo
  echo " ERROR: no data files available for the specified time period (hires,$date1)"
  exit 1
endif 

goto label3

# Everything is fine so far: proceed
label2:

# Set the next date and check its availability
if ( ( ${timeshift} != 00 ) || ( ${min} > 0 ) ) then
    set date1=`${LAGRANTO}/goodies/newtime $date0 $timeinc`
    if ( ! -f ${charp}${date1} ) then
       echo " ERROR: file with primary data is missing for $date"
       exit 1
    else
       set pfile1=${charp}${date1}
    endif
else
    set date1=${date0}
    set pfile1=${pfile0}
endif

# Set the final timeshift 
if ( ${min} != 00 ) then
    set timeshift=${timeshift}.${min}
endif

# Everything is fine!
label3:

# Set secondary files and check their availability
set sfile0=${chars}${date0}
set sfile1=${chars}${date1}

# Write status information
echo '---- DATA FILES -----------------------------------------'
echo    
echo "Primary files                         : ${pfile0}"
echo "                                      : ${pfile1}"
echo "Secondary files                       : ${sfile0}"
echo "                                      : ${sfile1}"
echo "Timeshift to first data file (hh.mm)  : ${timeshift}"
echo "Time increment of data files          : ${timeinc}"
echo

# --------------------------------------------------------------------------------------------------------------
# Create the start positions (without selection)
# -----------------------------------------------------------------------------------------------------------------

# Set times relative to the reference date
if ( "${changet}" == "true" ) then
  echo '---- CHANGE TIMES ON DATA FILES  ------------------------'
  echo   
  ${LAGRANTO}/goodies/changet.sh ${refdate} ${pfile0}
  ${LAGRANTO}/goodies/changet.sh ${refdate} ${pfile1}
  if ( -f  ${sfile0} ) then
    ${LAGRANTO}/goodies/changet.sh ${refdate} ${sfile0}
  endif
  if ( -f  ${sfile1} ) then
    ${LAGRANTO}/goodies/changet.sh ${refdate} ${sfile1}
  endif
endif

# Write parameters to parameter file and create the starting positions
\rm -f ${parfile}
echo \"${pfile0}\" \"${pfile1}\"    >! ${parfile}
echo \"${sfile0}\" \"${sfile1}\"    >> ${parfile}
echo \"${ofile}${format1}\"         >> ${parfile}
echo \"${regionf}\"                 >> ${parfile}
echo ${yyyy}                        >> ${parfile}
echo ${mm}                          >> ${parfile}
echo ${dd}                          >> ${parfile}
echo ${hh}                          >> ${parfile}
echo ${min}                         >> ${parfile}
echo 00                             >> ${parfile}
echo ${timeshift}                   >> ${parfile}
echo ${timeinc}                     >> ${parfile}

# Analyse the specifier and append to parameter file
${LAGRANTO}/startf/startf.perl "${specifier}" >> ${parfile}

if ( "${status}" != "0" ) then
  echo "ERROR:  Preprocessor <startf> failed"
  exit 1
endif

# Write selection criterion to file
\rm -f ${crifile}
tail -1 ${parfile} >! ${crifile} 

# Write flag for no time check
echo \"${timecheck}\"               >> ${parfile}

# Write title
echo 
echo '       *** END OF PREPROCESSOR STARTF ***'        
echo '========================================================='
echo

# Create the startf
cd ${tradir}
${LAGRANTO}/startf/startf

if ( "${status}" != "0" ) then
  echo "ERROR:  Program <startf> failed"
  exit 1
endif

# --------------------------------------------------------------------------------------------------------------
# Apply selection (first tracing then selection)
# --------------------------------------------------------------------------------------------------------------

# Stop if no tracing and selection is necessary
if ( "${flag_criterion}" == "nil" ) goto finish

# Tracing of extra variables
if ( -f  ${ofile}${format2} ) then
  \rm -f ${ofile}${format2}
endif
if ( "${timecheck}" == "no" ) then
  ${LAGRANTO}/trace/trace.sh ${ofile}${format1} ${ofile}${format2} -v ${tvfile} -notimecheck
else
  ${LAGRANTO}/trace/trace.sh ${ofile}${format1} ${ofile}${format2} -v ${tvfile}
endif
\rm -f ${ofile}${format1}

# Selection
if ( -f  ${ofile} ) then
  \rm -f ${ofile}
endif
${LAGRANTO}/select/select.sh ${ofile}${format2} ${ofile} `cat ${crifile}` 
\rm -f ${ofile}${format2}

# --------------------------------------------------------------------------------------------------------------
# Final tasks (make clean)
# --------------------------------------------------------------------------------------------------------------

finish:

echo $noclean

if ( "${noclean}" == "false" ) then
  \rm -f ${crifile}
  \rm -f ${parfile}
 endif

exit 0 
  


