#!/bin/sh

# Process L1A MODIS data to L2
# Create GEO file and subset image to area of interest
# Apply atmospheric correction and process to Rrs (1km)
# and TSM (250m, Miller & McKee 2004)
#
# THIS MUST BE RUN FROM A DIRECTORY MOUNTED ON A NON-FAT DRIVE

echo 'Processing ' $1

for FILE in *L1A_LAC.x.hdf
do
 #FILE=$1
   FILEBASE=`echo $FILE |awk -F.L1A_LAC.x.hdf '{ print $1}'`
   echo 'Begin processing. Filebasename:'
   echo ${FILEBASE}

 # Input files:
 # L1A will have 250m, 500m, and 1000m in the appropriate channels
 L1AFILE=${FILEBASE}.L1A_LAC.x.hdf
 GEOFILE=${FILEBASE}.GEO
 # L1B_LAC will have the hi-res channels, but all will be 1000m; _HKM and _QKM are also created
 L1B1KMFILE=${FILEBASE}.L1B_1KM
 L1BHKMFILE=${FILEBASE}.L1B_HKM
 L1BQKMFILE=${FILEBASE}.L1B_QKM
 L2FILE=${FILEBASE}.L2_LAC_all
 L3bFILE=${FILEBASE}.L3b_LAC_all
 
 # process the L1A to GEO (These scripts reside in the seadasx.x/run/scripts directory,
 #  the path to which is set by seadas.env)
 echo 'modis_GEO.py ' $L1AFILE '-o' $GEOFILE
 modis_GEO.py $L1AFILE -o $GEOFILE

 # process the L1A/GEO files to L1B
 echo 'modis_L1B.py' $L1AFILE $GEOFILE '-o' $L1B1KMFILE '-k' $L1BHKMFILE '-q' $L1BQKMFILE
 modis_L1B.py $L1AFILE $GEOFILE -o $L1B1KMFILE -k $L1BHKMFILE -q $L1BQKMFILE 

 # determine ancillary data
 #echo 'Getting ancillary data'
 getanc.py -c  $L1B1KMFILE

 echo 'Processing ' $L1B1KMFILE 'to Level 2..' $L2FILE
 # aer_opt = -9 sets to the Wang&Shi NIR/SWIR switching with Turbidity
 #   Index threshold of 1.3.
 # ctl_pt_incr=1 sets control point increment to 1 pixel; i.e. save navigation info for each pixel (default=8)

 #l2gen,7,ifile=$L1BQKMFILE,geofile=$GEOFILE,ofile1=$L2FILE,l2prod=iops
 l2gen par=L2all.par ifile=$L1B1KMFILE geofile=$GEOFILE ofile1=$L2FILE

 echo 'Space binning' $L2FILE
 l2bin infile=$L2FILE ofile=$L3bFILE resolve=1 prodtype=regional noext=1

done
