#!/bin/bash

[ $IRSPP_HOME ] || { echo "Please define environment variable IRSPP_HOME"; exit 1; }

[ -f $IRSPP_HOME/bin/irspp_env.sh ] || { echo "Error: cannot find $IRSPP_HOME/bin/irspp_env.sh"; exit 1; }

. $IRSPP_HOME/bin/irspp_env.sh

TOPDIR=$(cd ..; pwd)

#########################################
#Part 1: generate a transformation matrix
#########################################

#input and output files

infile_eum=$TOPDIR/ancillary/CM__PCA-USER_MTS1+IRS_20191112180000_static.nc
infile_user=$TOPDIR/output/irs_pcs.nc
outfile=$TOPDIR/output/irs_transform.nc

[ -f $infile_user ] || { echo "Error: cannot find $infile_user"; exit 1; }

#Run the executable

irs_transform_pcs.exe -i $infile_eum -j $infile_user -o $outfile
status=$?

[ $status = 0 ] && echo "$0 part 1 finished" || { echo "irs_transform_pcs.exe failed with status $status"; exit $status; }

#########################################
#Part 2: Apply transformation to EUMETSAT's PC file
#########################################

infile_pc=$TOPDIR/input/W_XX-EUMETSAT-Darmstadt,SND+SAT,MTS1+IRS-1B-PC--Q4--CHK-BODY--DIS-NC4E_C_EUMT_20200604143345_IDPFS_DEV_20160315125300_20160315125310_N__C_0052_0049.nc
namelistfile=irs_transform.nl
outfile_bufr=$TOPDIR/output/irs_transform.bufr

append=Yes    #Set to Yes if you want reconstructed radiances in netCDF

#Note: to avoid making changes to the input dataset we create a copy in the output directory

if [ $append = Yes ]; then
  inoutfile_pc=$TOPDIR/output/$(basename $infile_pc)
  inoutfile_pc=${inoutfile_pc%.nc}_transformed.nc
  cp -p $infile_pc $inoutfile_pc
  chmod 644 $inoutfile_pc
fi

#Run the executable

if [ $append = Yes ]; then
  irs_main.exe -io $inoutfile_pc -n $namelistfile -o $outfile_bufr
else
  irs_main.exe -i $infile_pc -n $namelistfile -o $outfile_bufr
fi

status=$?

[ $status = 0 ] && echo "$0 part 2 finished" || { echo "irs_main.exe failed with status $status"; exit $status; }
