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

# Specification of file names etc.
uvspec_input_template="uvspec.inp.template_1para"  # 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_1para.txt"                       # File with the simulation results
plotting_script="plot_result_1para.py"               # Python script for plotting the results


# Three alternatives for providing the list of variable input parameters
parameter_list=`cat list_aot`        # read list from external file list_aot
parameter_list="0.0 0.1 0.2 0.5 1.0" # directly entered
parameter_list=`seq 0.0 0.001 1.0`   # equidistant grid using external command "seq start step end"

parameter_name="AOT"                 # 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 "# ${parameter_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 parameter in ${parameter_list}
do
  cp ${uvspec_input_template} ${uvspec_input_file}                               # Copy template file
  sed -i s/\<${parameter_name}\>/${parameter}/g ${uvspec_input_file}             # Replace the placeholder by the actual parameter
  echo ${parameter} `${uvspec_command} < ${uvspec_input_file}` >> ${output_file} # Execute uvspec and append results to file
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
