#! /bin/bash

PATH=${PATH}:/home/evan/bin
export PATH

# base folder where everything is stored. Change this!
current_folder=/home/evan/experiments/naice_setup 

 

time_folder=$1
margin_model=$2
shear_stress_model=$3
old_icemodel=$4
iteration=$5
earth_model=$6
initiation_distance=$7
elevation_contour_interval=$8

#inode=$3
#earth_model=$4
#
#iteration=$6
#job_number=$7


log_file_extension=${shear_stress_model}_${margin_model}

title="${iteration}_${earth_model}_${shear_stress_model}_${margin_model}"
ice_file="naice_${title}"

tempdir="${current_folder}/temp" # this also needs to be changed before running the script

mkdir ${tempdir}
tempdir="${tempdir}/${shear_stress_model}_${margin_model}_${time_folder}_${iteration}"
mkdir ${tempdir}

cd ${tempdir}


# run icesheet to produce the ice model
mkdir ice_models


cp -R ${current_folder}/margins/$margin_model/${time_folder} ${tempdir}/ice_models/


# create the shear stress file

cp ${current_folder}/run/create_shear_stress_file.sh .
cp ${current_folder}/run/${shear_stress_model}.csv .
cp ${current_folder}/run/make_models.sh .
cp ${current_folder}/run/convert_grid.sh .


sh create_shear_stress_file.sh ${time_folder} ${shear_stress_model}

#cd shear_stress_3

rm deformation.txt

# if this isn't the first iteration, make the deformation files

# note that this is set up for using ANU formatted files. I have included the files needed for the default run in the folder def_mod.

# If you want to use your own set up (i.e. you have your own program to calculate the deformation and sea level change due to
# GIA, rewrite this section. "deformation.txt", which is used later on, is simply a text file like:
#           longitude   latitude   deformation (in m).

if [ ${iteration} -gt "0" ]
then

 	echo "creating deformation files"

	mkdir output

	cp ${current_folder}/def_mod/${ice_file}.def output

	site_to_txt output/${ice_file}.def ${time_folder} 


	if [ -e deformation.txt ]
	then
		echo "site_to_txt worked"  
	else
		echo "site_to_txt did not work" 
		exit 0

	fi
fi


bash make_models.sh ${time_folder} ${initiation_distance} ${elevation_contour_interval} ${earth_model} ${old_icemodel}

# moves the raw output 

echo copying files back


cp -R -f ${tempdir}/ice_models/$time_folder ${current_folder}/run/${shear_stress_model}_${margin_model}_${iteration}


echo "finished terra_init4.sh " ${time_folder} 

# after running the script, it deletes all the temp files, if you don't want this to happen, comment this line

rm -R ${tempdir}
