#!/bin/bash
#SBATCH --job-name=jobPEM2
#SBATCH --account=cin0391
### GENOA nodes accommodate 96 cores
#SBATCH --constraint=GENOA
### Number of Nodes to use
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=1
#SBATCH --threads-per-core=1 # --hint=nomultithread
###SBATCH --exclusive
#SBATCH --output=jobPEM_%A.out
#SBATCH --time=1:00:00

# A few parameters that might need be changed depending on your setup:
# Path to the arch.env to source
source ../trunk/LMDZ.COMMON/arch.env

read i_myear n_myear convert_years iPCM iPEM nPCM nPCM_ini < info_PEM.txt
cp run_PEM.def run.def

echo "Reshaping PCM data with XIOS is starting."
########################################################################
./reshape_XIOS_output_32x24x26_phymars_seq.e
########################################################################

if [ ! -f "data_PCM_Y1.nc" ] || [ ! -f "data_PCM_Y2.nc" ]; then # Check if it ended abnormally
    echo "Error: the reshaping executable crashed!"
    exit 1
fi
echo "Run PEM $iPEM is starting."
########################################################################
./pem_32x24x26_phymars_seq.e > out_runPEM${iPEM} 2>&1
########################################################################

if [ ! -f "restartfi.nc" ] || [ ! tail -n 1 out_runPEM${iPEM} | grep -iq "so far, so good" ]; then # Check if it ended abnormally
    echo "Error: the run PEM $iPEM crashed!"
    exit 1
fi
# Copy data files and prepare the next run
mv out_runPEM${iPEM} out_PEM/run${iPEM}
mv diagpem.nc diags/diagpem${iPEM}.nc
if [ -f "diagsoilpem.nc" ]; then
    mv diagsoilpem.nc diags/diagsoilpem${iPEM}.nc
fi
cp restartpem.nc starts/restartpem${iPEM}.nc
mv restartpem.nc startpem.nc
cp restartfi.nc starts/restartfi_postPEM${iPEM}.nc
mv restartfi.nc startfi.nc
if [ -f "restart.nc" ]; then
    cp restart.nc starts/restart_postPEM${iPEM}.nc
    mv restart.nc start.nc
elif [ -f "restart1D.txt" ]; then
    cp restart1D.txt starts/restart1D_postPEM${iPEM}.txt
    mv restart1D.txt start1D.txt
fi

./launchPEM.sh new
