#!/bin/bash
set -e # Stop if any error occurs 

# Specification of file names etc.
uvspec_input_template="uvspec.inp.template_2para"  # Template for the uvspec input file
uvspec_command="uvspec"                              # Enter complete path to uvspec executable if uvspec is found by the system (or adjust PATH system variable)
uvspec_input_file="uvspec.inp.tmp"                   # Temporary uvspec input file
output_file="lookup_table_2para.txt"                       # File with the simulation results
plotting_script="plot_result_2para.py"               # Python script for plotting the results


# List of variable input parameters
parameter1_list=`seq 0.0 0.01 1.0`    # equidistant grid using external command "seq start step end"
parameter1_name="AOT"                 # Name of the variable parameter; needs to match the placeholder in the input template

parameter2_list=`seq 0 2 88`          # equidistant grid using external command "seq start step end"
parameter2_name="SZA"                 # Name of the variable parameter; needs to match the placeholder in the input template

# Write header with the umu and phi information to the output_file
umus=`cat ${uvspec_input_template} | sed -n -e '/umu /p' | cut -f 1 -d'#' | cut -b 5-`
phis=`cat ${uvspec_input_template} | sed -n -e '/phi /p' | cut -f 1 -d'#' | cut -b 5-`
echo -n "# ${parameter1_name}, ${parameter2_name}" > $output_file 
for umu in ${umus}
do 
  for phi in ${phis}
  do 
    echo -n ", umu ${umu} phi ${phi}" >> ${output_file}
  done
done
echo "" >> ${output_file}


# Loop over uvspec with one varying input parameter
for parameter1 in ${parameter1_list}
do
  for parameter2 in ${parameter2_list} 
  do
    cp ${uvspec_input_template} ${uvspec_input_file}                               # Copy template file
    sed -i s/\<${parameter1_name}\>/${parameter1}/g ${uvspec_input_file}           # Replace the placeholder by the actual parameter
    sed -i s/\<${parameter2_name}\>/${parameter2}/g ${uvspec_input_file}           # Replace the placeholder by the actual parameter
    echo ${parameter1} ${parameter2} `${uvspec_command} < ${uvspec_input_file}` >> ${output_file} # Execute uvspec and append results to file
  done
done 
echo "   Calculations finished!"


# Plot using Python's Matplotlib module
echo -n "Press the 'p' key to plot the results..."
read -n 1 -s c
if [ "${c}" == "p" ];
then
  python ${plotting_script} ${output_file}
fi
echo
