#!/usr/bin/ksh
#
# overplot.ksh 
#
# Make a variety of plots used for instrument overviews
#
#			Author: Tim Quinn
# 		Created: Sep 2007
#
#			Arguments:	Check usage statement below
#
#			Updates:
#


#
## Set environment variables


    . /home/thmsoc/gaia2_test/overplot_gaia.bourne
#   . $THMSOC/src/config/soc_it_to_me.config
    . /home/thmsoc/gaia2_test/soc_it_to_me.config

#
## Handle input arguments
## Notes: Instruments to reprocess should be: 
## over, esa, fgm, sst, memory, fitmom, or fitgmom.
## Also, make sure to use a trailing slash with plot_dir
#
	USAGE="usage: overplot.ksh [-d date] [-n num_days] [-r reprocess] [-p plot_dir] [-i instr_to_process] [instr1...instrN]"
	while getopts :d:n:p:ri arguments
	do
		case $arguments in
			d) date_arg="date='$OPTARG'";;
			n) num_days_arg=", num_days='$OPTARG'";;
			p) plot_dir_arg=", plot_dir='$OPTARG'";;
			r) reprocess_arg=", /reprocess";;
			i) instr_to_process=yes;;
			\?) print "$OPTARG is not a valid switch."
					print "$USAGE";;
		esac
	done
	((position_occupied_by_switches = OPTIND - 1))
	shift $position_occupied_by_switches

#
## Set logfile
#
	processdate=$(date '+%y%m%d')
	LOGFILE=${LOGDIR}/overplots/make_over_${processdate}_$$
	echo ":$$:make_over:" >> $LOGFILE
	echo ":$$:make_over:Starting script overplot at $(date)" >> $LOGFILE

#
## Check if selected plot types are to be reprocessed
#
	if [[ -n $instr_to_process ]]
	then
		n=0
		for instrument in "$@"
		do
			if (($n == 0))
			then
				instr_list="'$instrument'"
			else
				instr_list="${instr_list}, '$instrument'"
			fi
			n=$(( $n + 1 ))
		done
		if (($n == 1))
		then
			instr_to_process_arg=", instr_to_process = $instr_list"
		else
			instr_to_process_arg=", instr_to_process = [$instr_list]"
		fi
	fi

#
## Check OS for IDL setting
#
	os=$(uname -s)
	if [[ $os = "SunOS" ]]
	then
		bitset="-32"
	else
		bitset=""
	fi

#
## Set IDL variables to pass to the batch file
#
	if [[ -z $date_arg ]]
	then
		date_arg="date='$(date -u +%Y-%m-%d)'"
	fi
	if [[ -z $plot_dir_arg ]]
	then
		plot_dir_arg=", plot_dir='${OVERPLOTS}/scratch/'"
	fi
	just_dir=$(echo $plot_dir_arg| awk -F\' '{print $2}')
	cd $just_dir

#
## Create IDL batch file
#
	rm -f thm_over_shell.bm
	line="thm_over_shell, ${date_arg}${num_days_arg}${plot_dir_arg}${reprocess_arg}${instr_to_process_arg}"
	echo $line > thm_over_shell.bm
	echo exit >> thm_over_shell.bm

#
## Now run idl with batch file
#
	echo ":$$:make_over:" >> $LOGFILE
	echo ":$$:make_over: Starting IDL batch file at $(date)" >> $LOGFILE

	idlerror=
	processStart=$(date -u '+%Y-%m-%d %T')
	idl $bitset thm_over_shell.bm > ${LOGDIR}/overplots/IDLRUN_${processdate}_$$ 2>&1
	idlrun=$?
	processStop=$(date -u '+%Y-%m-%d %T')
	chkfile=$(grep "Got Error Message" ${LOGDIR}/overplots/IDLRUN_${processdate}_$$)

#
## Check if IDL finished OK
#
	if (( $idlrun != 0 )) || [[ -n $chkfile ]]
	then
		idlerror="1"
		echo ":$$:make_over:" >> $LOGFILE
		echo ":$$:make_over:ERROR detected in IDL Process" >> $LOGFILE
		printf "%s\n" "script: $0" \
		"Warning: IDL run did not finish successfully. Check ${LOGDIR}/overplots/IDLRUN_${processdate}_$$" |
		mailx -s "THEMIS Overplot Production Failure" $SOC_EMAIL jimm@ssl.berkeley.edu
	fi
	
#
## Count the number of files produced and enter information
## into the database
#
	numFiles=$(find . -name \*png | grep -c png)
	#runId=$($THMSOC/src/php/overplotstats.php $processStart $processStop $numFiles)

#
## Process files produced by IDL run
#

   files=`ls`
   if [[ ! -n $files ]]
   then
     idlerror="1"
	 echo ":$$:make_over:" >> $LOGFILE
	 echo ":$$:make_over:ERROR - IDL run did not produce any $id files" >> $LOGFILE
	 printf "%s\n" "script: $0" \
	 "Warning: IDL run did not produce any files. Check ${LOGDIR}/overplots/IDLRUN_${processdate}_$$" |
	   mailx -s "THEMIS Overplot Production Failure" $SOC_EMAIL jimm@ssl.berkeley.edu
   fi
   
   #
   ## Now move each file to the archive directory
   # 
   for file in $files 
   do
	 if [[ -n `ls $file | grep "^20" 2>> $LOGFILE` ]]
      then
        plotYear=$(echo $file | awk -F- '{print $1}')
        plotMonth=$(echo $file | awk -F- '{print $2}')
        plotDay=$(echo $file | awk -F- '{print $3}')    
      elif [[ -n `ls $file | grep "^th"` ]]
      then
        plotYear=$(echo $file | awk -F_ '{print substr($4,1,4)}')
        plotMonth=$(echo $file | awk -F_ '{print substr($4,5,2)}')
        plotDay=$(echo $file | awk -F_ '{print substr($4,7,2)}')
      else
        continue
      fi  
      fileSize=$(ls -l $file |awk '{print $1}' 2>> $LOGFILE)
      echo "Moving file: $file to ${OVERPLOTS}/${plotYear}/${plotMonth}/${plotDay}" >> $LOGFILE
      mkdir -p ${OVERPLOTS}/${plotYear}/${plotMonth}/${plotDay}
      mv -f $file ${OVERPLOTS}/${plotYear}/${plotMonth}/${plotDay}
#      $THMSOC/src/php/overplotfiles.php $runId $file $fileSize
    
	done

#
## Cleanup
#
	if [[ -z $idlerror ]]
	then
		rm -f ${LOGDIR}/overplots/IDLRUN_${processdate}_$$
	fi
	
    rm -f /var/tmp/make_over_lock
	
exit 0
