#!/bin/sh

umask 002

filename="$1"
common_calib_file=/exports/csce/eddie/geos/groups/LURG/models/PLUM/output/hind1970/common_p_calib.txt
common_run_file=/exports/csce/eddie/geos/groups/LURG/models/PLUM/output/hind1970/common_p_run.txt
output_dir=/exports/csce/eddie/geos/groups/LURG/models/PLUM/output/hind1970

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
#        mkdir $scenario_dir/calib
     elif [ $overwrite -ne 1 ]; then
        echo "Already have scenario $scenario, set -O to overwrite existing scenarios"
        continue;
     fi

     calib_config_file=$scenario_dir/calib/config.properties
#     cp $common_calib_file $calib_config_file
#     echo "OUTPUT_DIR=$scenario_dir/calib" >> $calib_config_file

#     for index in "${!array[@]}"
#     do
#        echo "${header[index]}"="${array[index]}" >> $calib_config_file
#     done

     run_config_file=$scenario_dir/config.properties
     cp $common_run_file $run_config_file
     echo "OUTPUT_DIR=$scenario_dir" >> $run_config_file
#     echo "SERIALIZED_LAND_USE_FILE=$scenario_dir/calib/landUseRaster.ser" >> $run_config_file
#     echo "CLUSTERED_YIELD_FILE=$scenario_dir/calib/cluster.asc" >> $run_config_file

     for index in "${!array[@]}"
     do
        echo "${header[index]}"="${array[index]}" >> $run_config_file
     done

     echo "$scenario generated"
  fi
done < $filename

