#!/bin/sh

#   Dec 03/2008 - F.Majaess (Revised for sa/saiph, ib/dorval-ib, af/alef)
#   Oct 16/2006 - F.Majaess (Revised for ma/maia, ns/naos)
#   Mar 01/2006 - F.Majaess (Revised for rg/rigel)
#   Jun 24/2003 - F.Majaess (Revised for az/azur and "openmp" support)
#   Feb 25/2002 - F.Majaess (Revised for ya/yata)
#   Feb 12/2002 - F.Majaess (Change "lopgm" default values to those of 
#                            "lopgmhr". Disable "hires"; since lopgm/lopgmhr 
#                            are now quivalent).
#   Feb 20/2001 - F.Majaess (Allow overriding target platform via "rmtdest")
#   Jan 29/2001 - F.Majaess (Revised to support SXCROSS_KIT/SXF90_VER)
#   Feb 23/2000 - F.Majaess (Revised for kz/kaze and "sxf90")
#   Jun 14/1999 - F.Majaess (Added "modver" support)
#   Jan 21/1999 - F.Majaess (Added yo/yonaka)
#   Aug 04/1998 - F.Majaess (Increase "tsl" to 193X96=18528 for "hires" case)
#   Jul 14/1997 - F.Majaess (Revise for sx/hiru)
#   May 06/1997 - F.Majaess (Add "multi" switch for SX4)
#   Mar 18/1997 - F.Majaess (Revise for group file ownership)
#   Apr 04/1996 - F.Majaess (revise for SX-4)
#   Dec 08/1995 - F.Majaess (Replace 'hostname' calls by "$HOSTID")
#   Oct 26/1995 - F.Majaess (Implement "nopack" & modify for IBM RS6000)
#   Jun 28/1995 - F.Majaess (Modify for Orion)
#   Feb 06/1995 - F.Majaess (Modify for SGI)
#   Nov 08/1994 - F. Majaess (Modify for sx3r and new destination identifiers)
#   MAY 24/1994 - F. Majaess ( Increase default lrt/lmt to 48 from 42)
#   MAY 17/1994 - F. Majaess ( Allow processing .f files as well)
#   MAY 09/1994 - F. Majaess ( Increase Hi-res lrt/lmt to 64 from 63)
#   Jul 19/1993 - F. Majaess ( Modify for long list of files to ftp)
#   Feb 09/1993 - E. Chan (Add hires option)
#   Oct 23/1992 - E. Chan (Use ftp to transfer code if target is not the MIPS)
#   Aug 17/1992 - E. Chan (Implement float1 option on the MIPS) 
#   Jul 29/1992 - E. Chan

#id genpgm  - generate Fortran program source code files from variable 
#id           dimensioned source code files      

#   AUTHOR  - E. Chan

#hd PURPOSE - "genpgm" takes source program files containing Fortran code 
#hd           with arrays dimensioned using parmsub parameters and generates
#hd           pure Fortran '.f' files. Each file contains one program. 
#hd           Each source file must have a '.vd' or '.f' extension. The switch
#hd           'ex' may be included on the command line to enable the
#hd           submission of a batch job to the destination machine to 
#hd           generate the corresponding program executables. 
#hd
#hd           Note: '.f' files on the command line are treated as if they
#hd                 are generated from '.vd' files; no 'parmsub' preprocessing
#hd                 is done on '.f' files.
 
#pr PARAMETERS:
#pr
#pr   POSITIONAL
#pr
#pr     fn1 ... fnm = list of m file names containing source code
#pr                   (filenames may contain path information)
#pr
#pr   PRIMARY
#pr
#pr
#pr      Note: One of 'ha/sp/po/ca/mz/hr/br/ba/dy/p1/p2/p3/p4' is to be specified.
#pr
#pr        hare/hr  = to target job to hare.
#pr
#pr      brooks/br  = to target job to brooks.
#pr
#pr       daley/dy  = to target job to daley.
#pr
#pr     banting/ba  = to target job to banting.
#pr
#pr        ppp1/p1  = to target job to ppp1.
#pr
#pr        ppp2/p2  = to target job to ppp2.
#pr
#pr        ppp3/p3  = to target job to ppp3.
#pr
#pr        ppp4/p4  = to target job to ppp4.
#pr
#pr        hadar/ha = to target job to IBM (hadar).
#pr
#pr        spica/sp = to target job to IBM (spica).
#pr
#pr        pollux/po= to target job to Linux front-end (pollux).
#pr
#pr        castor/ca= to target job to Linux front-end (castor).
#pr
#pr          mez/mz = to target job to Linux front-end (mez).
#pr
#pr      fil_grpname= User has the option of specifying one of
#pr                   'ccrn_shr/ccrn_stf/ccrn_net/ccrn_rcm/ccrn_mam/ccrn_gst'
#pr                   group ownership on the executable(s).
#pr                   (=$DEFFGRP).
#pr
#pr          modver = Model libary version to target for linking.
#pr                   (=\$DEFMODL).
#pr
#pr            fdir = directory where pure Fortran '.f' files are to be placed
#pr                   (="$CCRNSRC/source_aix/lspgm/.f_aix"       for 'ha/sp'
#pr                    ="$CCRNSRC/source_linux/lspgm/.f_linux"   for 'po/ca/mz')
#pr
#pr           exdir = directory where program executables are to be placed
#pr                   (="\$RTEXTBLS/lopgm"                     for 'ha/sp'
#pr                    ="$CCRNSRC/Linux_executables64/lopgm"   for 'po/ca/mz')
#pr
#pr            time = time limit to use for submitting "genabs" in seconds 
#pr                   (=900)
#pr  
#pr             mem = memory limit to use for submitting "genabs" in
#pr                   in megabytes (=250)
#pr  
#pr             bln = controls the number of longitudes for a subset
#pr                   of the program library which handle large record
#pr                   fields (1x1 grid) (=360)
#pr             blt = controls the number of latitudes  for a subset
#pr                   of the program library which handle large record
#pr                   fields (1x1 grid) (equator included)(=181).
#pr            ilev = number of model levels (=100)
#pr             plv = number of pressure levels (=100)
#pr             lon = number of grid longitudes (=192)
#pr             lat = number of grid latitudes  (=96)
#pr             lmt = m spectral truncation wave numbers (=64)
#pr             lrt = n spectral truncation wave numbers (=64)
#pr             typ = spectral truncation type (0=rhomboidal, 2=triangular)
#pr                   (=2)
#pr             tsl = maximum time series length (=18528)
#pr
#pr   SECONDARY
#pr
#pr          nolist = switch to turn off compiled listings 
#pr                   (=no/yes)
#pr
#pr          nopack = switch used to disable packing by enforcing
#pr                   packing density of 1 via linking to revised version
#pr                   of "recpk2" subroutine (=no/yes)
#pr
#pr              ex = switch to enable the submission of batch script to
#pr                   generate executables from the Fortran source code
#pr
#pr           hires = (No longer valid since "lopgm" and "lopgmhr" 
#pr                    are equivalent; script will abort if specified)
#pr                   switch to generate high resolution executables with
#pr                   the following differences in the default settings of 
#pr                   some of the parameters:
#pr  
#pr                    fdir = ("$CCRNSRC/source_aix/lspgm/.hrf_aix"     for 'ha/sp'
#pr                            "$CCRNSRC/source_linux/lspgm/.hrf_linux" for 'po/ca/mz') 
#pr
#pr                   exdir = ("\$RTEXTBLS/lopgmhr"                     for 'ha/sp'
#pr                            "$CCRNSRC/Linux_executables64/lopgmhr    for 'po/ca/mz')
#pr
#pr                    ilev = number of model levels (=100)
#pr                     lat = number of grid latitudes  (=96)
#pr                     lmt = m spectral truncation wave numbers (=64)
#pr                     lon = number of grid longitudes (=192)
#pr                     lrt = n spectral truncation wave numbers (=64)
#pr                     plv = number of pressure levels (=100)
#pr                     tsl = maximum time series length (=18528)
#pr  
#pr           noftp = switch to deactivate remote transfer of source code to
#pr                   the destination machine -- code is placed in "fdir" on 
#pr                   the current machine and the switch "ex" is also deactivated
#pr  
#pr            febg = switch to execute job in background mode without going 
#pr                   through batch mode (='no'/'yes')
#pr
#pr        Note: If neither "float1","float2" [nor "openmp"] 
#pr              (see below) is specified, the default
#pr              for hadar/spica/pollux/castor/mez: 64-bits real/ 32_bits integer;
#pr              (ie. whatever mode "$F77" is set to).
#pr
#pr          openmp = switch to compile the code in "openmp" 32-bits (real/integer)
#pr                   mode if "float1=yes", otherwise 64-bits mode. This switch is
#pr                   currently valid only for hadar,spica,pollux,castor,mez, 
#pr                   destinations as well as under AIX O/S.
#pr                   (='no'/'yes')
#pr          float1 = switch to compile the code in 32-bits (real/integer) mode.
#pr                   It can be used in conjunction with "openmp=yes".
#pr                   (='no'/'yes')
#pr          float2 = switch to compile the code in 64-bits (real/integer)
#pr                   It's intended to be used on "hadar/ha","spica/sp","pollux/po",
#pr                   "castor/ca", "mez/mz" or other suitable targets.
#pr                   (='no'/'yes')
#pr        noxlfimp = switch valid only under AIX on one of the IBM clusters at CMC.
#pr                   It's used to aid in getting better debugging trace in case of
#pr                   executable abort.
#pr                   (='no'/'yes')
#pr
#pr           p5lib = switch valid only under AIX on one of the IBM clusters at CMC.
#pr                   It's used to allow linking to P5 captured "essl/mass/blas" 
#pr                   libraries instead of the default set under "/usr/lib".
#pr                   (='no'/'yes')
#pr
#pr

#ex EXAMPLE:
#ex   
#ex     genpgm file1.vd $HOME/source/file2.vd ha ex fil_grpname='ccrn_shr' \
#ex            fdir=$HOME/source_aix/lspgm/.f_aix \
#ex            modver=gcm6u ilev=40 plv=40
#ex
#ex     The above example substitutes the variable array dimensions of
#ex     two source files, saves them as pure Fortran '.f' files, and
#ex     submits a batch job to IBM "hadar" to generate the corresponding
#ex     program executables in "float2" mode, where the generated executables
#ex     are based on array dimensions suitable for resolutions up to T48L40.
#ex     Group ownership of the files is possibly changed to 'ccrn_shr'.
#ex     The linking targets "gcm6u" model archive library.
#ex

#    Temporary sample for IBM@CMC:
#    genpgm add.vd fdir=`pwd` exdir=`pwd` xlfver=xlf10103 lvcode_dir=new_lvcode_dir98 nolist ex sp

#  * Reset field separators (otherwise those defined in the parent process
#  * will be used and these may cause problems if they include special 
#  * characters used in this script). 

IFS=' '
export IFS
# echo ' Not ready yet'
# exit
      
#  * Move into a temporary directory to execute the script.

### cwd=`pwd`
### Stamp="${HOSTID}_"`date +%Y%j%H%M%S`
### if [ "$OS" = 'Linux' -a "$SITE_ID" != 'DrvlSC' ] ; then
###  mkdir /tmp/tmp_genpgm_$$_$Stamp
###  cd /tmp/tmp_genpgm_$$_$Stamp
### else
###  mkdir $HOME/tmp/tmp_genpgm_$$_$Stamp
###  cd $HOME/tmp/tmp_genpgm_$$_$Stamp
### fi

#  * Obtain the path name for the Fortran source code and generate
#  * the list of variable dimensioned source files to be processed. 

for arg in $@ 
do
  case $arg in 
        -*) set $arg ; set_opt=$arg           ;; 
       *=*) eval $arg                         ;;
        ex) ex='yes'                          ;;
   hare|hr) mdest=${mdest:='hare'}     ;;
   brooks|br) mdest=${mdest:='brooks'}     ;;
   daley|dy) mdest=${mdest:='daley'}     ;;
   banting|ba) mdest=${mdest:='banting'}     ;;
   ppp1|p1) mdest=${mdest:='ppp1'}     ;;
   ppp2|p2) mdest=${mdest:='ppp2'}     ;;
   ppp3|p3) mdest=${mdest:='ppp3'}     ;;
   ppp4|p4) mdest=${mdest:='ppp4'}     ;;
   hadar|ha) mdest=${mdest:='hadar'}          ;;
   spica|sp) mdest=${mdest:='spica'}          ;;
   pollux|po) mdest=${mdest:='pollux'}        ;;
   castor|ca) mdest=${mdest:='castor'}        ;;
    mez|mz) mdest=${mdest:='mez'}             ;;
     lxsrv) mdest=${mdest:='lxsrv'}           ;;
    lxsrv2) mdest=${mdest:='lxsrv2'}          ;;
    lxwrk1) mdest=${mdest:='lxwrk1'}          ;;
    lxwrk2) mdest=${mdest:='lxwrk2'}          ;;
      febg) febg='yes'                        ;;
      hires) hires='hr'                       ;;
     noftp) noftp='yes'                       ;;
    nolist) nolist='yes'                      ;;
    nopack) nopack='yes'                      ;;
    noxlfimp) noxlfimp='yes'                  ;;
    p5lib) p5lib='yes'                        ;;
    float1) if [ "$float" = 'openmp' ] ; then
             float='float1 openmp'
            else
             float='float1'
            fi                                ;;
    float2) float='float2'                    ;;
    openmp) if [ "$float" = 'float1' ] ; then
             float='float1 openmp'
            else
             float='openmp'
            fi                                ;;
         *) file_list="$file_list $arg"      
  esac
done

# if [ "$hires" = 'hr' ] ; then
if [ -n "$hires" ] ; then
   echo "" ; echo "  Abort in GENPGM: Sorry, 'hires' switch is not valid! Please, correct..."
   exit 1
fi

genabs=${genabs:='genabs'}
nolist=${nolist:='no'}
nopack=${nopack:='no'}
noxlfimp=${noxlfimp:='no'}
if [ "$noxlfimp" = 'on' ] ; then
  noxlfimp='yes'
elif [ "$noxlfimp" = 'off' ] ; then
  noxlfimp='no'
fi
p5lib=${p5lib:='no'}
if [ "$p5lib" = 'on' ] ; then
 p5lib='yes'
elif [ "$p5lib" = 'off' ] ; then
 p5lib='no'
fi
if [ "$SITE_ID" = 'Dorval' -a -n "$xlfver" ] ; then
 xlfver="xlfver=$xlfver"
else
 xlfver=''
fi

if [ -n "$lvcode_dir" ] ; then
 if [ "$SITE_ID" = 'Dorval' -o "$SITE_ID" = 'DrvlSC' ] ; then
  if [ ! -d "$CCRNSRC/$lvcode_dir/." ] ; then
   echo "" ; echo "  genpgm: $CCRNSRC/$lvcode_dir is not a valid subdirectory!"
   exit 5
  fi
  lvcode_dir="lvcode_dir=$lvcode_dir"
 else
  echo "genpgm: lvcode_dir=$lvcode_dir is not valid on local site and will be ignored"
  lvcode_dir=''
 fi
fi
# HOSTIDf=`echo $HOSTID | cut -c 1-3`
HOSTIDf=`echo $HOSTID | sed -e 's/eccc.*-ppp/cs/g' -e 's/^ppp/cs/g' | cut -c 1-3`
if [ "$SITE_ID" = 'Dorval' -a "$mdest" = 'erg' ] ; then
 if [ "$HOSTIDf" = 'erg' ] ; then
  mdest="$HOSTID"
  febg='yes'
 else
  echo "Sorry, genpgm must be invoked from one of ERG nodes if mdest=erg !"
  exit 3
 fi
elif [ "$SITE_ID" = 'Victoria' -o "$SITE_ID" = 'Downsview' -o "$SITE_ID" = 'York' -o "$SITE_ID" = 'Utor1' -o "$SITE_ID" = 'UOFT' ] ; then
 mdest=${mdest:=$HOSTID}
fi

#  * Prompt for a destination if none was specified.

while [ -z "$mdest" ]
do
  echo "please enter a destination; ha/sp/po/ca/mz/hr/br/ba/dy/p1/p2/p3/p4: > \\c"
  read tmdest
  case $tmdest in
    hare|hr) mdest='hare'                  ;;
  brooks|br) mdest='brooks'                  ;;
    daley|dy) mdest='daley'                  ;;
  banting|ba) mdest='banting'                  ;;
    ppp1|p1) mdest='ppp1'                  ;;
    ppp2|p2) mdest='ppp2'                  ;;
    ppp3|p3) mdest='ppp3'                  ;;
    ppp4|p4) mdest='ppp4'                  ;;
   hadar|ha) mdest='hadar'                   ;;
   spica|sp) mdest='spica'                   ;;
  pollux|po) mdest='pollux'                  ;;
  castor|ca) mdest='castor'                  ;;
     mez|mz) mdest='mez'                     ;;
     lxsrv) mdest=${mdest:='lxsrv'}          ;;
    lxsrv2) mdest=${mdest:='lxsrv2'}         ;;
    lxwrk1) mdest=${mdest:='lxwrk1'}         ;;
    lxwrk2) mdest=${mdest:='lxwrk2'}         ;;
         *) echo "illegal destination ! "    ;;
  esac
done

#  * Exit if parameter for mdest not suitable.

if [ "$SITE_ID" = 'Dorval' -a "$mdest" != 'mez' -a "$mdest" != 'castor' -a "$mdest" != 'hadar' -a "$mdest" != 'spica' -a "$mdest" != 'pollux' -a "$HOSTIDf" != 'jou' ] ; then
  echo "Invalid argument for machine destination $mdest"
  exit 4
fi
if [ "$SITE_ID" = 'DrvlSC' -a "$mdest" != 'hare' -a "$mdest" != 'brooks'  -a "$mdest" != 'daley' -a "$mdest" != 'banting' -a "$mdest" != 'ppp1' -a "$mdest" != 'ppp2' -a "$mdest" != 'ppp3' -a "$mdest" != 'ppp4' -a "$mdest" != 'gpsc' ] ; then
  echo "Invalid argument for machine destination $mdest"
  exit 4
fi

#  * Check for the validity of "float" switch on "mdest" (if applicable)

if [ "$float" = 'float2' ] ; then
 if [ "$SITE_ID" = 'Dorval' -a "$mdest" != 'mez' -a "$mdest" != 'castor' -a "$mdest" != 'hadar' -a "$mdest" != 'spica' -a "$mdest" != 'pollux' -a "$HOSTIDf" != 'jou' ] ; then
   echo "" ; echo "  genpgm: Sorry, float2 switch can only be used on hadar,spica,castor,mez and pollux !"
   exit 7
 fi
 if [ "$SITE_ID" = 'DrvlSC' -a "$mdest" != 'hare' -a "$mdest" != 'brooks' -a "$mdest" != 'daley' -a "$mdest" != 'banting' -a "$mdest" != 'ppp1' -a "$mdest" != 'ppp2' -a "$mdest" != 'ppp3' -a "$mdest" != 'ppp4' -a "$mdest" != 'gpsc' ] ; then
   echo "" ; echo "  genpgm: Sorry, float2 switch can only be used on hare,brooks,daley,banting,ppp1,ppp2,ppp3,ppp4 and gpsc !"
   exit 7
 fi
 if [ \( "$SITE_ID" = 'Downsview' -o "$SITE_ID" = 'Victoria' \) -a "$OS" != 'AIX' -a "$OS" != 'Linux'  ] ; then
  echo "" ; echo "  genpgm: Sorry, float2 switch can only be used on AIX or Linux !"
  exit 8
 fi
fi

if [ \( "$float" = 'openmp' -o "$float" = 'float1 openmp' \) -a \(                                \
     \( "$SITE_ID" = 'Dorval' -a "$mdest" != 'mez' -a "$mdest" != 'castor' -a "$mdest" != 'hadar' -a "$mdest" != 'spica' -a "$mdest" != 'pollux' -a "$HOSTIDf" != 'jou' \) -o \
     \( "$SITE_ID" = 'DrvlSC' -a "$mdest" != 'hare' -a "$mdest" != 'brooks' -a "$mdest" != 'daley' -a "$mdest" != 'banting' -a "$mdest" != 'ppp1' -a "$mdest" != 'ppp2' -a "$mdest" != 'ppp3' -a "$mdest" != 'ppp4' -a "$mdest" != 'gpsc' \) -o \
     \( "$SITE_ID" = 'Downsview' -a "$OS" != 'Linux' \) -o    \
     \( "$SITE_ID" = 'Victoria' -a "$OS" != 'AIX' -a "$OS" != 'Linux' \)           \) ] ; then

  echo "" ; echo "  genpgm: Sorry, openmp is not a valid option with what was specified !"
  exit 9
fi

# setup for proper batch queue

queue=$mdest

if [ "$mdest" = "$HOSTID"  ] ; then
  febg=${febg:="$NONQS"}
  febg=${febg:='no'}
else
  febg=no
fi

#  * Set the path to the offical CCRN directory for Fortran source code
#  * based on destination. Also, set "machine" (used in pgmparm) to 1 
#  * if the code is to be compiled with 64-bit integers. Otherwise, 
#  * "machine" is set to 2 (i.e for 32-bit integers).

machine=1

BEHOMEX=${BEHOMEX=`echo $BEHOME | sed -e 's/home\/c3ccrn/sx\/crb\/home_ccrn\/acrn/' `}
if [ "$OS" = 'AIX' -o "$OS" = 'Linux' -o "$mdest" = 'pollux' -o "$mdest" = 'mez' -o "$mdest" = 'castor' -o "$mdest" = 'hadar' -o "$mdest" = 'spica' -o "$mdest" = 'mistral' -o "$mdest" = 'halo' -o "$HOSTIDf" = 'jou'  ] ; then
  if [ "$float" != 'float2' -a "$float" != 'openmp' ] ; then
   machine=2
  fi
  #HOSTIDf=`echo $HOSTID | cut -c 1-3`
  HOSTIDf=`echo $HOSTID | sed -e 's/eccc.*-ppp/cs/g' -e 's/^ppp/cs/g' | cut -c 1-3`
 #if [ "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'saiph' -o "$mdest" = 'maia' -o "$mdest" = 'zeta' -o "$mdest" = 'algol' \) -a \( "$HOSTID" = 'pollux' -o "$OS" = 'AIX' \)  ] ; then
  if [ "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'hadar' -o "$mdest" = 'spica' \) -a "$OS" = 'AIX' ] ; then
   fdir=${fdir:="$CCRNSRC/source_aix/lspgm/.f_aix"}
  elif [ "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'mez' -o "$mdest" = 'castor' -o "$HOSTIDf" = 'jou' \) -a "$OS" = 'Linux' ] ; then
   fdir=${fdir:="$CCRNSRC/source_linux64/lspgm/.f_linux"}
  elif [ "$SITE_ID" = 'Dorval' -a "$mdest" = 'pollux' -a "$HOSTIDf" = 'ib3' ] ; then
   fdir=${fdir:="$CCRNSRC/source_linux64/lspgm/.f_linux"}
  elif [ "$SITE_ID" = 'DrvlSC' -a "$OS" = 'Linux' ] ; then
   fdir=${fdir:="$CCRNSRC/source_linux64/lspgm/.f_linux"}
  else
   fdir=${fdir:="$CCRNSRC/source${OSbin}/lspgm/.f"}
  fi
else
  echo "Error: invalid machine destination $mdest"
  exit 1
fi

if [ "$mdest" = 'hadar' -o "$mdest" = 'spica' ] ; then
 Azminmem_mb=1000
 mem=${mem:="$Azminmem_mb"}
 if [ "$mem" -lt "$Azminmem_mb" ] ; then
   mem="$Azminmem_mb"
 fi
elif [ "$mdest" = 'hare' -o "$mdest" = 'brooks' -o "$mdest" = 'daley' -o "$mdest" = 'banting' -o "$mdest" = 'ppp1' -o "$mdest" = 'ppp2' -o "$mdest" = 'ppp3' -o "$mdest" = 'ppp4' -o "$mdest" = 'gpsc' ] ; then
 Azminmem_mb=2000
 mem=${mem:="$Azminmem_mb"}
 if [ "$mem" -lt "$Azminmem_mb" ] ; then
   mem="$Azminmem_mb"
 fi
fi

#  * Set the default time and memory limits for the batch submission job. 

time=${time:=900}
mem=${mem:=250}

# If running at Dorval site, allow group ownership option for
# the executables ...

if [ "$SITE_ID" = 'Dorval' ] ; then
 fil_grpname='ccrn_shr'
else
 unset fil_grpname
fi
if [ ! -d $fdir/. ] ; then
 (mkdir $fdir 2>/dev/null || : )
fi
chmod ug+rx $fdir
tspath=`expr $fdir : '\(.*\)/'`
tsdir=`expr //$fdir : '.*/\(.*\)'`

if [ "$float" = 'float1' -o "$float" = 'float1 openmp' ] ; then
  machine=2
fi 

cwd=`pwd`
Stamp="${HOSTID}_"`date +%Y%j%H%M%S`
if [ "$OS" = 'Linux' -a "$SITE_ID" != 'DrvlSC' ] ; then
 mkdir /tmp/tmp_genpgm_$$_$Stamp
 cd /tmp/tmp_genpgm_$$_$Stamp
else
 mkdir $HOME/tmp/tmp_genpgm_$$_$Stamp
 cd $HOME/tmp/tmp_genpgm_$$_$Stamp
fi

#  * Set the defaults for the parameters used to compute array dimensions
#  * in program pgmparm. 

## if [ -n "$hires" ] ; then
     ilev=${ilev:=100}
     lon=${lon:=192}
     lat=${lat:=96}
     lrt=${lrt:=64}
     lmt=${lmt:=64}
     plv=${plv:=100}
     tsl=${tsl:=18528}
## else
##   ilev=${ilev:=30}
##   lon=${lon:=128}
##   lat=${lat:=64}
##   lrt=${lrt:=48}
##   lmt=${lmt:=48}
##   plv=${plv:=30}
##   tsl=${tsl:=14601}
## fi

typ=${typ:=2}
bln=${bln:=360}
blt=${blt:=181}

#  * Generate a temporary file "pgm_card" which contains an input card image  
#  * that is needed by the program "pgmparm". Awk is used to format the input 
#  * card image as well as to ensure that the input values are in the correct 
#  * range.

cat <<*EOF > input_par
$ilev $lon $lat $lrt $lmt $typ $plv $bln $blt $tsl $machine
*EOF

$AWK '
{
  printf("          ")
  for (i = 1; i <= NF-2; i++ ) {
    if ( $i < 0 || $i > 99999 ) {
      print "\nError: " $i " is not valid"
      exit (i+100)
    }
    printf("%5d",$i) 
  }
  if ( $10 < 0 || $10 > 9999999999 ) {
    print "\nError: " $10 " is not valid"
    exit (110)
  }
  printf("%10d",$10) 
  if ( $11 != 1 && $11 != 2 ) {
    print "\nError: " $11 " is not valid"
    exit (111)
  }
  printf("%5d\n",$11) 
} 
'                                input_par > pgm_card

#  * Exit if error was detected in while checking the input parameters.

if [ "$?" -ne 0 ] ; then
  cat input_par
  cat pgm_card
  exit 2
fi

#  * Inspect input values before continuing with script.

echo "           ilev  lon  lat  lrt  lmt  typ  plv  bln  blt       tsl machine"
cat pgm_card
echo 
echo 'Are these values acceptable (y or n)?\c'

read response
if [ -n "$response" -a "$response" != 'y' ] ; then
  exit 3
fi 

#  * Generate a file "parameters" which contains the parmsub parameters
#  * needed to replace the variable array dimensions in the program source
#  * code.

pgmparm <pgm_card >parameters
echo
cat parameters
echo

#  * Loop over all source files.

for name in $file_list
do            

  #  * Extract name and path information from the source filename. The 
  #  * default directory containing the source file is set to the 
  #  * directory from which the script was invoked. 

  path=`expr $name : '\(.*\)/'`
  srcfile=`expr //$name : '.*/\(.*\)'`

  path=${path:=$cwd}

  #  * Extract the name of the source file without the '.vd' extension.

  pgm=`expr "$srcfile" : '\(.*\)\.vd'`  

  #  * Extract the name of the source file without the '.f' extension.

  pgmf=`expr "$srcfile" : '\(.*\)\.f'`  

  #  * Generate the Fortran source (but only if the extraction of the program 
  #  * name is successful).

  if [ -n "$pgm" -o -n "$pgmf" ] ; then
   if [ -n "$pgm" ] ; then

    #  * Replace the parmsub parameters in the variable dimension source
    #  * code using the input file "parameters".

    parmsub $path/$srcfile ${pgm}.f parameters > output

    #  * If "parmsub" aborted, move the output file to the directory from 
    #  * which the script was executed and quit the script.

    if [ "$?" -ne 0 ] ; then
      mv output $OUTPUTQ/genpgm_error$$
      exit 4
    fi  
   else

    #  * In the case of '.f' file simply perform a copy, and reset "pgm". 

    cp $path/$srcfile ${pgmf}.f 
    pgm=$pgmf

   fi
     
    #  * Strip trailing blanks from every line of the program and set 
    #  * the file permissions. Also, if the machine is the MIPS place the
    #  * source code in the requested directory. The equivalent action 
    #  * for machines other than the MIPS is done after the loop through
    #  * a single call to ftp (unless the "noftp" switch is set, in which 
    #  * case, the file is simply placed in the requested directory). 

    if [ "$SITE_ID" = 'DrvlSC' ] ; then 
      sed 's/ *$//' ${pgm}.f > $fdir/${pgm}.f 
      chmod 644 $fdir/${pgm}.f
    elif [ "$mdest" != 'mez' -a "$mdest" != 'castor' -a "$mdest" != 'spica' -a "$mdest" != 'hadar' -a "$HOSTIDf" != 'jou' ] ; then
      sed 's/ *$//' ${pgm}.f > $fdir/${pgm}.f 
      if [ "$SITE_ID" = 'Dorval' ] ; then
        chgrp $fil_grpname $fdir/${pgm}.f
      fi
      chmod 644 $fdir/${pgm}.f
    elif [ "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'hadar' -o "$mdest" = 'spica' \) -a "$OS" = 'AIX' ] ; then
      sed 's/ *$//' ${pgm}.f > $fdir/${pgm}.f 
      chgrp $fil_grpname $fdir/${pgm}.f
      chmod 644 $fdir/${pgm}.f
    elif [ "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'mez' -o "$mdest" = 'castor' -o "$mdest" = 'pollux' -o "$HOSTIDf" = 'jou' \) -a "$OS" = 'Linux' ] ; then
      sed 's/ *$//' ${pgm}.f > $fdir/${pgm}.f 
      chgrp $fil_grpname $fdir/${pgm}.f
      chmod 644 $fdir/${pgm}.f
    else
      sed 's/ *$//' ${pgm}.f > sed.out
      if [ "$noftp" = 'yes' ] ; then
        if [ "$SITE_ID" = 'Dorval' ] ; then
          chgrp $fil_grpname sed.out
        fi
        chmod 644 sed.out
        mv sed.out $fdir/${pgm}.f
      else
        mv sed.out ${pgm}.f
        if [ "$SITE_ID" = 'Dorval' ] ; then
          chgrp $fil_grpname ${pgm}.f
        fi
        chmod 644 ${pgm}.f
      fi
    fi

    #  * Generate a list of Fortran program files to be compiled and  
    #  * linked if executables are to be produced. 

    pgm_list="${pgm}.f $pgm_list" 
 
  else
    
    echo "Warning: file must have a .vd/.f extension -- file $srcfile skipped"

  fi

done

#  * If the target machine is not the MIPS, then initiate a ftp session
#  * to transfer over the source code and set the file permissions.
#  * This is not done if the noftp switch is set.

# if test \( "$mdest" = 'mez' -o "$mdest" = 'castor' -o "$mdest" = 'saiph' -o "$mdest" = 'maia' -o "$mdest" = 'zeta' -o "$mdest" = 'algol' -o "$mdest" = 'hadar' -o "$mdest" = 'spica' \) -a "$noftp" != 'yes' ; then
#   echo "cd $fdir" > ftp.in
#   for pgmx in $pgm_list
#   do
#    echo "put $pgmx" >> ftp.in
#   done
#   echo "quit" >> ftp.in
#   ftp -i $mdest < ftp.in > ftp.out
#   if [ "$?" -ne 0 ] ; then
#     echo "Error: ftp problem in genpgm - check for output in .queue"
#     mv ftp.out $OUTPUTQ/genpgm_err$$
#     exit 5
#   else
#    \rm ftp.out ftp.in
#   fi
# fi
if [ \( "$SITE_ID" = 'Dorval' -a \( "$mdest" = 'mez' -o "$mdest" = 'castor' -o "$mdest" = 'hadar' -o "$mdest" = 'spica' -o "$HOSTIDf" = 'jou' \) \) -o "$SITE_ID" = 'DrvlSC' ] ; then
 for pgmx in $pgm_list
  do
    chmod 644 $pgmx
   # cat $pgmx > $fdir/$pgmx
     cp $pgmx $fdir
   # scp $pgmx "$mdest:$fdir"
  done
fi

#  * Generate and submit batch script to generate executables from the 
#  * Fortran source code if requested. 
  
if [ "$ex" = 'yes' -a "$noftp" != 'yes' ] ; then

  if [ -n "$exdir" ] ; then
    expath="dir=$exdir"
  fi
  if [ "$SITE_ID" = 'Dorval' ] ; then
    Tfil_grpname="fil_grpname=$fil_grpname" 
  else
    Tfil_grpname=""
  fi

  cat <<..*EOF > BATCH_job
  #! /bin/sh
  echo ; echo "                  Beginning of \${HOSTID} job:" \`date\` ; echo
  cd $fdir
  if [ "\$OS" = 'AIX' -a \`hostname\` = `hostname` ] ; then
   LOPLOT=$LOPLOT
   export LOPLOT
  fi
  if [ "\$OS" = 'Linux' -a \`hostname\` = `hostname` ] ; then
   LOPLOT=$LOPLOT
   export LOPLOT
  fi
  modver="$modver"
  modver=\${modver:=\$DEFMODL}

  if [ -n "\$modver" ] ; then
#  $genabs $set_opt $pgm_list $expath $hires $float $Tfil_grpname $xlfver $lvcode_dir modver=\$modver nopack=$nopack nolist=$nolist
   $genabs $set_opt $pgm_list $expath        $float $Tfil_grpname $xlfver $lvcode_dir modver=\$modver nopack=$nopack nolist=$nolist noxlfimp=$noxlfimp p5lib=$p5lib
  else
#  $genabs $set_opt $pgm_list $expath $hires $float $Tfil_grpname $xlfver $lvcode_dir nopack=$nopack nolist=$nolist
   $genabs $set_opt $pgm_list $expath        $float $Tfil_grpname $xlfver $lvcode_dir nopack=$nopack nolist=$nolist noxlfimp=$noxlfimp p5lib=$p5lib
  fi
..*EOF

  if [ "$febg" = 'no' ] ; then
  cat <<..*EOF >> BATCH_job
  ( rmllfls || : )
  exit
..*EOF
  Cwd=`pwd`  
  mv BATCH_job $HOME/tmp/BATCH_job_genpgm_$Stamp_$$
# qsub -q $queue BATCH_job -lT $time -lM ${mem}mb -r genabs -eo \
  cd $HOME/tmp
  $CCCQSUB -q $queue BATCH_job_genpgm_$Stamp_$$ -lT $time -lM ${mem}mb -r genabs -eo \
       -o $OUTPUTQ/$genabs.$$ 
  cd $Cwd 
  \rm $HOME/tmp/BATCH_job_genpgm_$Stamp_$$
  else

   if [ "$SITE_ID" = 'Dorval' ] ; then
    
    case ${HOSTID} in
     c1f*|c1h*|c1r*|c1s*) Aixtrgt='spica'     ;;
     c2f*|c2h*|c2r*|c2s*) Aixtrgt='hadar'     ;;
    #c3f*) Aixtrgt='rigel'     ;;
     c4f*) Aixtrgt='maia'      ;;
     c6f*) Aixtrgt='saiph'     ;;
     c7f*) Aixtrgt='zeta'      ;;
     c8f*) Aixtrgt='algol'     ;;
     ib*) Aixtrgt='dorval-ib' ;;
     al*) Aixtrgt='alef'      ;;
     erg*) Aixtrgt='erg'      ;;
     *) Aixtrgt='azur'      ;;
    esac

   elif [ "$SITE_ID" = 'DrvlSC' ] ; then
    
    case ${HOSTID} in
     xc1*) Aixtrgt='hare'     ;;
     xc2*) Aixtrgt='brooks'     ;;
     xc3*) Aixtrgt='banting'     ;;
     xc4*) Aixtrgt='daley'     ;;
     sc1*) Aixtrgt='ppp1'     ;;
     sc2*) Aixtrgt='ppp2'     ;;
     pp3|cs3*|hpcr3* ) Aixtrgt='ppp3'     ;;
     pp4|cs4*|hpcr4* ) Aixtrgt='ppp4'     ;;
     usr-svc-sci-cnt*|gpsc-*) Aixtrgt='gpsc'     ;;
     *) Aixtrgt='azur'      ;;
    esac
   fi
   if [ "$HOSTID" = "$mdest" -o "$Aixtrgt" = "$mdest" ] ; then

    chmod u+x BATCH_job
    if [ "$OS" = 'Linux' -a "$SITE_ID" != 'DrvlSC' ] ; then
     mv BATCH_job  /tmp/tmp_genabs_job$$
     echo "rm -f /tmp/tmp_genabs_job$$" >> /tmp/tmp_genabs_job$$
     echo "exit" >> /tmp/tmp_genabs_job$$
     nohup /tmp/tmp_genabs_job$$ > $OUTPUTQ/$genabs.$$ 2>$OUTPUTQ/$genabs.$$ &
    else
     mv BATCH_job  $CCRNTMP/tmp_genabs_job$$
     echo "rm -f $CCRNTMP/tmp_genabs_job$$" >> $CCRNTMP/tmp_genabs_job$$
     echo "exit" >> $CCRNTMP/tmp_genabs_job$$
     nohup $CCRNTMP/tmp_genabs_job$$ > $OUTPUTQ/$genabs.$$ 2>$OUTPUTQ/$genabs.$$ &
    fi

   else

    echo "genpgm: you have to run genpgm on $mdest for background mode!"

   fi

  fi

fi

#  * Move back into parent directory and clean up temporary directory
#  * before exiting from script.

cd ..
\rm -r tmp_genpgm_$$_$Stamp

exit
