#!/usr/bin/ksh
. $WFU_PATH/global.site.ksh
#------------------------------------------------------------------------------------------
# This program will check the completion status for all RUNS for a subject
# It will also launch a fixed effects analysis if the fixed_effects file is detected
#  $1 = datadir - the main subject directory  (not the batchdir)
#  $2 = the completion log directory (where the batch autogenerate scripts will be placed)
#-------------------------------------------------------------------------------------------

datadir=$1
completion_dir=$2
cd $completion_dir
nruns=`cat TOTAL_RUNS`
completed_SNR=`ls *SNR*_completed 2>/dev/null | grep -c SNR`
completed_STATS=`ls *STATS*_completed 2>/dev/null | grep -c STATS`
completed_snr_flag=0
completed_stats_flag=0
len=${#nruns}
if test $len -eq 0
	then nruns=1000
	echo NO TOTAL_RUNS FILE DETECTED
	exit
fi

if test $nruns -eq $completed_SNR
	then completed_snr_flag=1
	echo SNR completed
fi

if test $nruns -eq $completed_STATS
	then completed_stats_flag=1
	echo STATS completed
fi

em1=`cat $completion_dir/batch_email`
len=${#em1}
if test $len -eq 0
	then em1=$email_address
fi
email_address=$em1

fname=`basename $datadir`

if test $completed_snr_flag -eq 1
	then  fe_flag=`ls *.se_ref 2>/dev/null | grep -c se_ref`
	if test $fe_flag -gt 0 
		then  fe_flag_launched=`ls fixed_effects_launched* 2>/dev/null | grep -c fixed_effects`
		if test $fe_flag_launched -eq 0
			then echo "SNR FILES for $nruns RUNS GENERATED FOR $datadir" > $completion_dir/fixed_effects_launched
			echo $completion_dir/fixed_effects_launched
			$script_path/auto_fe_batch $datadir $completion_dir			
			subject_line=`echo FIXED_EFFECTS_LAUNCHED_FOR_$fname`
			$script_path/mail_file $completion_dir/fixed_effects_launched $subject_line $email_address
		fi
	fi
fi

fe_flag_done=`ls *fixed_effects_completed* 2>/dev/null | grep -c fixed_effects`
if test $completed_stats_flag -eq 1
	then stats_flag_sent=`ls stats_completed* 2>/dev/null | grep -c stats_completed`
	if test $stats_flag_sent -eq 0
		then echo "STATS FILES for $nruns RUNS COMPLETED FOR $datadir" > $completion_dir/stats_completed
		subject_line=`echo ALL_$nruns..STATS_RUNS_COMPLETED_FOR_$fname`
		$script_path/mail_file $completion_dir/stats_completed $subject_line $email_address
		if test $fe_flag_done -eq $fe_flag 
			then  compress_runs $datadir
		fi
	fi
fi
exit
