#!/bin/bash
#-----------------

# -- load netcdf
module 'load netcdf/4.3.2'

# -- set environment
export LAGRANTO="${HOME}/lagranto.ocean/"

# -- set data dir
ddir="/atmosdyn/schemms/oras5/cdf"

# -- experiement data dir
odir=${ddir}/"2009.2010/backward"
mkdir -pv $odir
cd $odir 

find -type l -delete

echo "working in: " $PWD

# ---- start date
date="20091217_00"

# -- lats/lons
lons=( $(seq -50 -1 -60 ) )
lats=( $(seq  50  1  60 ) )

# --- LOOP
for lat in ${lats[@]}; do
for lon in ${lons[@]}; do


# ---- end date 
fdat=$( tim2dat -d -120 $date )
fdat=$( tim2dat -d -5 $fdat  )

# --- link bathymetry file
ln -s ${ddir}/bath .

# -- current start date of trajectories
idat=$date

# -- link all necessary fields for time period
while [[ ${idat} != ${fdat} ]]; do

            echo $idat
            # -- date of this file
            y=$(echo $idat | cut -c1-4)
            m=$(echo $idat | cut -c5-6)
            d=$(echo $idat | cut -c7-8)
            h=$(echo $idat | cut -c9-10)

            # -- link start file
            ln -s ${ddir}/P${idat} . &> /dev/null
            ln -s ${ddir}/S${idat} . &> /dev/null

            # -- go to next time step
            idat=$( tim2dat -d -5 $idat )

done
fdat=$( tim2dat -d +5 $fdat  )

# ---- create the startfile

# -- Examples
#create_startf.ocean ${date} startf.2 'box.grid(-52,-53,55,55)@profile(0.6,10,20)@m'
#create_startf.ocean ${date} startf.2 'line(-55,-47,54,59,40)@profile(0.6,10,20)@m'
#create_startf.ocean ${date} startf.2 'circle.grid(-58,58,50)@profile(0.6,3,6)@m'
create_startf.ocean ${date} startf.2 'circle.grid('${lon}','${lat}',25)@grid(0,2)@m'

# --- start calculation and output all 24 hours / computing time steps is 12h instead of 10h
caltra.ocean ${date} ${fdat} startf.2 traj.1 -j -o 1440

# --- Create the Tracevars file ---
\rm tracevars  &> /dev/null
cat >> tracevars << end_trace
U    1.  0 P
V    1.  0 P
T    1.  0 P
HGT  1.  0 S
HFLX 1.  0 S
SST  1.  0 S
ICE  1.  0 S
SSS  1.  0 S
WFLX 1.  0 S
W10M 1.  0 S
SAFLX 1. 0 S
THCL 1. 0 S
end_trace

# -- trace some variables
trace.ocean traj.1 LSL${date}_${lon}_${lat}_backward

# ---
find -type l -delete

# --- END
done
done

exit 0
