#!/bin/sh
#$ -o /exports/csce/eddie/geos/groups/LURG/models/PLUM/output/qlogs
#$ -e /exports/csce/eddie/geos/groups/LURG/models/PLUM/output/qlogs
#$ -l h_vmem=8G 
#$ -R y


common_prop_file=/exports/csce/eddie/geos/groups/LURG/models/PLUM/output/common_properties
output_dir=/exports/csce/eddie/geos/groups/LURG/models/PLUM/output
filename="/exports/csce/eddie/geos/groups/LURG/models/PLUM/$1"

if [[ $* == *-O* ]]; then overwrite=1
else overwrite=0
fi

if [ "$#" -lt 1  ]; then
   echo "Need to specify scenario table file"
   exit
fi

echo "Generating scenarios into $output_dir"

while read -r datarow
do
  IFS=',' read -r -a array <<< "$datarow"

  if [ -z "$header" ]; then
     header=( "${array[@]}" )
  else
     ensemble="${array[0]}"
     scenario="${array[1]}"
     scenario_dir=$output_dir/$ensemble/$scenario
     echo "$scenario for $ensemble in $scenario_dir"

     if [ ! -d "$output_dir/$ensemble" ]; then
        mkdir $output_dir/$ensemble
     fi

     if [ ! -d "$scenario_dir" ]; then
        mkdir $scenario_dir
     elif [ $overwrite -ne 1 ]; then
        echo "Already have scenario $scenario, set -O to overwrite existing scenarios"
        continue;
     fi

     config_file=$scenario_dir/config.properties
     cp $common_prop_file $config_file

     for index in "${!array[@]}"
     do
        echo "${header[index]}"="${array[index]}" >> $config_file
     done
	 
     echo "$scenario generated"
  fi
  	
done < $filename

source /etc/profile

if [[ $* == *-ys* ]]; then
   if [[ $* == *-ys1* ]]; then singleYieldShockFile=1
   else singleYieldShockFile=0
   fi
   echo "Running R yield shock script"
   module load R
   R < /exports/csce/eddie/geos/groups/LURG/models/PLUM/plumv2/scripts/CreateYieldShockMaps.R  --no-save --args $1 $singleYieldShockFile
else
   echo "Not running R yield shock script"
fi

if [[ $* == *-s* ]]; then
   echo "Running R shock script"
   module load R
   R < /exports/csce/eddie/geos/groups/LURG/models/PLUM/plumv2/scripts/createShockFiles.R  --no-save --args $1
else
   echo "Not running R shock script"
fi