#!/usr/bin/ksh
#. $HOME/.idlspm/.global.ksh
. $WFU_PATH/global.site.ksh
DISPLAY=$batch_display:0.0
export DISPLAY
#-------------------------------------------------------------------
# Script: autolocsort_excite_paradigm 
#
# Location: /fmri2/fmri
#
# Purpose: Reconstruction and processing of GE fMRI images after extraction.
#
# How it works: 
#
#	This script is invoked from the new 'extract1' script (which runs on the
#	scanner) when the MoJoe extraction process is run. It unpacks the tar file
#	of images that was sent to the user, runs Matlab program wfu_cmd_ge_to_analyze.m
#	to create Analyze-format files from the individual image files, then invokes
#	IDL to run the following:
#
#		1. locsort.pro (to build .loc files)
#		2. auto_process.pro (to do the fMRI cradle-to-grave processing)
#
#===================================================================
# C H A N G E   L O G
#
# BAS	060704	Fixed so no longer removes existing LOCS folder.
#
# AHB   120204  No longer produces .error file
#
# JAM   120304  Added the process_options (second argument)
#		0 or non-existent = do it all
#		1 = notar
#		2 = notar and no Dicom Analyze conversion		 
#
# JAM	120904  Inserted wait for pfiles to be reconstructed
# KLP   121504  Added test to see if tar file is a regular file before rm -rf
# AHB   121604  Changed references from bpm to wfu
# AHB   122104  Changed # input arguments test from 1 to 2
# KLP   122204  Added reference to either mojoe_extract.info OR .sinfo
# KLP   122904  Removed & so cpu_finder will run in the foreground
#               Added cd to batchdir before nixcmd call
# KLP   012005  Changed wait_for_pfiles script path
# KLP   030705  Added check for paradigms; if none or undefined, don't process
# KLP   040605  Added no stop on tar messages re "future" or "record size"
# KLP   020507  Added check for .gz extension on input tar file
# KLP   021407  If present, e-mail pasl/figures/*_CBFm.jpg to user
# KLP   022207  Added SPM99 or SPM5 autoprocessing path choice
# KLP   051607  added extract_running flag; use locs dir or extract tar to tmp;
#               keep tar file, but remove tmp; extract is always additive;
#               a 2nd extract will wait till running extract is done; 
#               two waiting extracts will cause the last one to exit with error;
#               a waiting extract will force running extract to exit early
# KLP   052307  Add the waiting check BETWEEN extra steps and post processing
# KLP   061907  Add qcFigures filter for mail_image
# KLP   062607  Move any series99 screen save files before deleting the tmp directory
# KLP   092707  If clinical/pasl, send an error mail message when no pasl dir created
# BCW   070208  Added DHSmind emails.
# BCW   120208	Added anatdir (as a mirror of dircon.anatdir)
#-----------------------------------------------------------------------------
function leave_autolocsort {
rm -rf $datadir/log/extract.running
echo "extract done" > $datadir/log/extract.done
now=`date`
echo $now __EXIT >> $datadir/log/timing.log
exit
}
function check_autolocsort_waiting {
wait_nfiles=`find $datadir/log -name "extract_*.waiting" | wc -w`
if (test $wait_nfiles -gt 0) then
    now=`date`
    echo $now autolocsort_excite $$: exiting, another extract waiting >> $datadir/log/autolocsort_excite.log 
    leave_autolocsort
fi
}

echo Hostname: $HOST
#----------------------------
#Set the display server here
#----------------------------
anatdir=nifti
mydisplay=$batch_display
homedir=`pwd`
fileid=`echo $$`
label=`date '+%m_%d_%y'`
tarfile=$1
process_options=$2
forceflag=' '
#autolocsort_excite tar($1) process($2) clear_option($3)
if (test $# -le 1) then
#if (test $# -le 2) then
	process_options=0
fi
if (test $process_options -gt 0) then
 	forceflag=',/force'
fi
# default is that the analyze dir is not cleared and all extracts are additive
clear_option=$3
if (test $# -le 2) then
    clear_option=0
fi
#------------------------------------
# Get data path name and switch to it:
#------------------------------------
datadir=`dirname $tarfile`

echo __HOST $HOST >> $datadir/log/timing.log
if (test ${#datadir} -le 0) then
    now=`date`
    echo $now autolocsort_excite $$: tarfile $tarfile not found >> $datadir/log/autolocsort_excite.log
    echo $now __EXIT >> $datadir/log/timing.log
    exit
fi

if (test -f $datadir/log/extract.running) && (! test -f $datadir/log/extract.done) then
    let wait_nfiles=`find $datadir/log -name "extract_*.waiting" | wc -w`
    if (test $wait_nfiles -eq 0) then
        now=`date`
        echo $now autolocsort_excite $$: waiting for running extract to exit >> $datadir/log/autolocsort_excite.log
        echo "extract waiting" > $datadir/log/extract_$$.waiting
        wait_for $datadir/log/extract.done $datadir/log
        let wait_nfiles=`find $datadir/log -name "extract_*.waiting" | wc -w`
        rm -f $datadir/log/extract_$$.waiting
        if (test $wait_nfiles -gt 1) then
            now=`date`
            echo $now autolocsort_excite $$: after waiting, mail_error_msg unresolved_extract_duplicate $$ >> $datadir/log/autolocsort_excite.log           
            echo "two extracts are waiting while one is already running" >> $datadir/log/kill
            /fmri2/fmri/mail_error_msg unresolved_extract_duplicate $datadir
            leave_autolocsort
        fi
        now=`date`
        echo $now autolocsort_excite $$: cleared extract_$$.waiting to run now >> $datadir/log/autolocsort_excite.log
    else
        now=`date`
        echo $now autolocsort_excite $$: other process already waiting, mail_error_msg unresolved_extract_duplicate $$ >> $datadir/log/autolocsort_excite.log
        echo "two extracts are waiting while one is already running" >> $datadir/log/kill
        /fmri2/fmri/mail_error_msg unresolved_extract_duplicate $datadir
        leave_autolocsort
    fi
fi
echo "extract running" >> $datadir/log/extract.running
rm -rf $datadir/log/extract.done
cd $datadir
#-------------------------------------------------------------------
# Unpack the image files. (Errors will go to tempfile.txt)
#-------------------------------------------------------------------
now=`date`
echo $now __BEGIN: untar, unzip >> $datadir/log/timing.log
#tar -xvf $tarfile 1>/dev/null 2>tempfile.txt
if (test $process_options -eq 0) then
    if (! test -f $tarfile) then
        now=`date`
        echo $now autolocsort_excite $$: file $tarfile not found >> $datadir/log/autolocsort_excite.log
        leave_autolocsort
    fi
#
# if .flist extension, treat input file as a list of tar files to be extracted all at once
#
    ext=${tarfile##*.}
    if (test $ext = "flist") then
        names=`cat $tarfile`;
    else
        names=$tarfile;
    fi
#
# extract from one or more tar files
# 
    for tarfile in $names; do
#
        if (! test -f $tarfile) then
            now=`date`
            echo $now autolocsort_excite $$: file $tarfile not found >> $datadir/log/autolocsort_excite.log
            leave_autolocsort
        fi
        now=`date`
        echo $now autolocsort_excite $$: extracting file $tarfile >> $datadir/log/autolocsort_excite.log
#
# if .gz extension, gunzip before tar extract
#
        ext=${tarfile##*.}
        if (test $ext = "gz") then
            gunzip < $tarfile | tar -xvf - 1>/dev/null 2>tempfile.txt
        else
            tar -xvf $tarfile 1>/dev/null 2>tempfile.txt
        fi
        if (test -s tempfile.txt) then
        #log directory should exist under current (data) directory at this point:
            echo autolocsort_excite: error running tar command to unpack $tarfile >> $datadir/log/autolocsort_excite.log
            cat tempfile.txt >> $datadir/log/autolocsort_excite.log
###	    rm -rf tempfile.txt
###	    exit;
#
#-- don't stop if error report file contains only "in the future"
#-- or "block size" info messages sent to STDERR
#
            nerror=`wc -l tempfile.txt | awk '{print $1}'`
            nfuture=`grep -c -i "in the future" tempfile.txt`
            nrec=`grep -c -i "record size" tempfile.txt`
            let nokay=nfuture+nrec
            if (test $nerror -ne $nokay) then
                rm -rf tempfile.txt
                #exit
                leave_autolocsort
            else
                echo '... ignoring errors; all related to future time stamps or record size' >> $datadir/log/autolocsort_excite.log
            fi
###            
        fi
    done
else
    if (! test -s $datadir/locs) then
        echo '... if no tmp.tar or tmp.tar.gz file is specified, then a locs dir must exist for processing' >> $datadir/log/autolocsort_excite.log
        leave_autolocsort
    fi
fi
#----------------------------------------------------------
# Remove tempfile.txt, keep tarfile:
#----------------------------------------------------------
#if (test -f $tarfile) then
#    rm -rf $tarfile 1>/dev/null 2>/dev/null
#fi
rm -rf tempfile.txt 1>/dev/null 2>/dev/null

#----------------------------------------------------------
# Create locs dir if doesn't exist, then copy files from tmp to locs:
#----------------------------------------------------------
#mkdir locs 1>/dev/null 2>/dev/null
#mv tmp/* locs 1>/dev/null 2>/dev/null
#cp -r tmp/* locs
#rm -rf tmp 1>/dev/null 2>/dev/null
#
# No, just leave the current dir name as tmp and erase it 
# after DICOM conversion.
#
now=`date`
echo $now __END__: untar, unzip >> $datadir/log/timing.log
dicomdir=$datadir/tmp

cd $datadir
#--------------------------------------------------------------------------------------------
# Run the Matlab program (wfu_DICOM.m) that converts the images to Analyze format:
# (will log error and informational messages to wfu_dicom_to_analyze.log under log directory)
#--------------------------------------------------------------------------------------------
#startMatlab='/usr/local/matlab6.5/bin/matlab -nojvm -nosplash'
#startMatlab='/ansir1/matlab/bin/matlab -nojvm -nosplash'
startMatlab=$batch_matlab
uniqueID=`echo $$`
displayLog='-logfile '$datadir/log/autolocsort_excite_$uniqueID.log
#bpmStartup='wfu_bpm_startup([],2);'
#wfuStartup='wfu_startup([],2);'
wfuStartup='wfu_startup([],5);'
#wfuDICOM="wfu_DICOM('$datadir/locs');"
###wfuDICOM="wfu_DICOM('$datadir/tmp','$datadir/analyze',$clear_option);"
if (test -d $datadir/locs) then
    dicomdir=$datadir/locs
else
    dicomdir=$datadir/tmp
fi
###wfuDICOM="wfu_DICOM('$dicomdir','$datadir/analyze',$clear_option);"
#wfuDICOM="[indirStep,outdirStep]=wfu_DICOM('$dicomdir','$datadir/analyze',$clear_option);"
wfuDICOM="[indirStep,outdirStep]=wfu_DICOM('$dicomdir','$datadir/$anatdir',$clear_option);"
leaveMatlab='exit;'
#GO=$startMatlab' '$displayLog' -r '$bpmStartup$wfuDICOM$leaveMatlab
GO=$startMatlab' '$displayLog' -r '$wfuStartup$wfuDICOM$leaveMatlab
echo $GO
# execute dicom-->analyze/nifti conversion
if (test $process_options -lt 2) then
#
# execute the MATLAB DICOM to Analyze conversion code
#
#	echo ... calling MATLAB DICOM to Analyze conversion code
	echo ... calling MATLAB DICOM to $anatdir conversion code
        now=`date`
        echo $now __BEGIN: DICOM conversion >> $datadir/log/timing.log
	$GO
        now=`date`
        echo $now __END__: DICOM conversion >> $datadir/log/timing.log
fi
#
# move any series99 screen save files before deleting the tmp directory
#
/fmri2/fmri/get_series99 $datadir
#
rm -rf $datadir/tmp
check_autolocsort_waiting
#
# do the extra steps separately so we can check for another extract waiting first
#
displayLog='-logfile '$datadir/log/extra_processing_steps_$uniqueID.log
#wfuSTEP="wfu_extra_processing_steps('$dicomdir','$datadir/analyze');"
wfuSTEP="wfu_extra_processing_steps('$dicomdir','$datadir/$anatdir');"
GOSTEP=$startMatlab' '$displayLog' -r '$wfuStartup$wfuSTEP$leaveMatlab
echo $GOSTEP
# execute dicom-->analyze conversion
if (test $process_options -lt 2) then
	echo ... calling MATLAB wfu_extra_processing_steps
        now=`date`
        echo $now __BEGIN: extra steps >> $datadir/log/timing.log
	$GOSTEP
        now=`date`
        echo $now __END__: extra steps >> $datadir/log/timing.log
fi
### TEMP MAY7 early exit
#echo ... continue on to post-processing from here
#leave_autolocsort
###
check_autolocsort_waiting
#--------------------------------------------------------------------------------------------
# Run post-processing
#--------------------------------------------------------------------------------------------
#startMatlab='/usr/local/matlab6.5/bin/matlab -nojvm -nosplash'
#startMatlab='/ansir1/matlab/bin/matlab -nojvm -nosplash'
startMatlab=$batch_matlab
displayLog='-logfile '$datadir/log/postprocess_$uniqueID.log
#bpmStartup='wfu_bpm_startup([],2);'
wfuStartup='wfu_startup([],5);'
wfuPostProcess="wfu_postprocess('$datadir',[1,1,1,1]);"
leaveMatlab='exit;'
GOPOST=$startMatlab' '$displayLog' -r '$wfuStartup$wfuPostProcess$leaveMatlab
echo $GOPOST
# execute post-processing
if (test $process_options -lt 2) then 
    echo ... calling MATLAB wfu_postprocess
    now=`date`
    echo $now __BEGIN: postprocess >> $datadir/log/timing.log
    $GOPOST
    now=`date`
    echo $now __END__: postprocess >> $datadir/log/timing.log
#   /fmri2/fmri/mail_image $datadir "pasl_S*/figures/*_CBFm.jpg" CBFm $$_1
    pasldir=`find $datadir -name "pasl_*"`
    if (test ${#pasldir} -gt 0) then
        #/fmri2/fmri/mail_image $datadir "pasl_*/figures/*_CBFm.jpg" CBFm $$_1
        now=`date`
        echo $now __BEGIN: pasl mail >> $datadir/log/timing.log
#				2008-04-11 BCW because of a change in names for rp*.jpg files
#        /fmri2/fmri/mail_image $datadir "pasl_*/figures/*_CBFm.jpg pasl_*/qcFigures/rp*_PASL.jpg" CBFm $$_1
        /fmri2/fmri/mail_image $datadir "pasl_*/figures/*_CBFm.jpg pasl_*/qcFigures/rp*Translation.jpg" CBFm $$_1
        now=`date`
        echo $now __END__: pasl mail >> $datadir/log/timing.log
# if this is clinical pasl, send a warning that no pasl directory was created
    else
        forclinical=`echo $datadir | grep -c clinical/pasl`
		    fordhsmind=`echo $datadir | grep -c dbowden/dhs_mind`
        if (test $forclinical -gt 0 || test $fordhsmind -gt 0) then
            mail_image $datadir no_pasl_directory_created error
        fi
    fi
fi
check_autolocsort_waiting

norecon=0
#----------------------------------
# Check if this is monkey data 
# If it is then set norecon=1 for now 
#----------------------------------
monkey_flag=`echo $tarfile | grep monkey`
len=${#monkey_flag}
if test $len -gt 0
	then norecon=1
fi
#----------------------------------
# STOP NOW WITHOUT ANY PROCESSING?
# Check if all paradigm numbers = 0
# If yes, don't process.
#----------------------------------
#--------------------------------------------------------------------------------------------
#startMatlab='/usr/local/matlab6.5/bin/matlab -nojvm -nosplash'
#startMatlab='/ansir1/matlab/bin/matlab -nojvm -nosplash'
startMatlab=$batch_matlab
log_process_report=$datadir/log/process_data_$uniqueID.log
displayLog='-logfile '$log_process_report
wfuStartup='wfu_startup([],5);'
wfuPROCESSING="wfu_autoprocessing('$datadir');"
leaveMatlab='exit;'
GO2=$startMatlab' '$displayLog' -r '$wfuStartup$wfuPROCESSING$leaveMatlab
echo $GO2
# execute processing check in MatLab
echo ... calling wfu_autoprocessing to determine IDL/SPM5 path
now=`date`
echo $now __BEGIN: wfu_autoprocess >> $datadir/log/timing.log
$GO2
now=`date`
echo $now __END__: wfu_autoprocess >> $datadir/log/timing.log
#
run_processing=0
if (test -a $log_process_report) then
    reply=`grep ProcessData $log_process_report | cut -f2`
    if (test ${#reply} -gt 0)
	then run_processing=`echo $reply`
    fi
fi
if (test $run_processing -eq 0) then
    echo 'No non-zero paradigms' >> $datadir/log/kill
    #exit
    leave_autolocsort
fi
#
# insert a quick check for recon errors here before setting up autoprocessing
#
#nstate2=`grep State $datadir/*.P?????.info 2>/dev/null | awk '{print $2}' | grep "2" | wc -l`
nstate2=`grep State $datadir/*.info 2>/dev/null | awk '{print $2}' | grep "2" | wc -l`
if (test $nstate2 -gt 0) then
    echo 'Reconstruction error' >> $datadir/log/kill
    #exit
    leave_autolocsort
fi
#--------------------------------------------------------------------------------------------
check_autolocsort_waiting

#----------------------------------------
# Set up for pfile wait and batch IDL processing to come:
#----------------------------------------
mkdir $datadir/log 2>/dev/null
logdir=$datadir/log
cd $logdir
mkdir batch 2>/dev/null
batchdir=$logdir/batch
batchque=$batchdir/batch_que
uxfile=$batchdir/autowait_u$$
outputfile=`echo $batchdir/output_unix`
echo ' ' > $outputfile
cd $batchdir
#---------------------------------------
# create the batch autoprocess scripts and
# copy the quickstart file
#---------------------------------------
echo "#!/usr/bin/ksh" > $uxfile
#echo '. $HOME/.idlspm/.global.ksh' >> $uxfile
echo '. $WFU_PATH/global.site.ksh' >> $uxfile
echo "datadir=$datadir" >> $uxfile
echo "batchdir=$batchdir" >> $uxfile
echo "batchque=$batchque" >> $uxfile
echo "logdir=$logdir" >> $uxfile
echo "uxfile=$uxfile" >> $uxfile


#echo 'email=`grep email $logdir/mojoe_extract.info | awk ' "'{print " '$2' "}'"'`' >> $uxfile
echo 'email="" >> $uxfile'
if (test -a $logdir/mojoe_extract.sinfo) then
    echo 'email=`grep email $logdir/mojoe_extract.sinfo | awk ' "'{print " '$2' "}'"'`' >> $uxfile
else
    if (test -a $logdir/mojoe_extract.info) then
	echo 'email=`grep email $logdir/mojoe_extract.info | awk ' "'{print " '$2' "}'"'`' >> $uxfile
    fi
fi
#
echo 'len=${#email}'				>> $uxfile
echo 'if test $len -eq 0'			>> $uxfile
echo '	then email=`grep @ $logdir/mojoe_capture.log`'	>> $uxfile
echo 'fi'					>> $uxfile
echo 'echo $email > $batchdir/batch_email'	>> $uxfile
echo "outputfile=$outputfile" >> $uxfile

pfile_success=pfile_recon_complete
wait_hours=3
wait_for_pfiles=$script_path/wait_for_pfiles
#wait_for_pfiles=/raid/neuro/kpearson/scripts/wait_for_pfiles

echo "pfile_success=$pfile_success" >> $uxfile
echo "wait_hours=$wait_hours" >> $uxfile 
echo "wait_for_pfiles=$wait_for_pfiles" >> $uxfile

echo 'rm -rf $batchdir/$pfile_success' >> $uxfile
echo '$wait_for_pfiles $datadir $batchdir $pfile_success $wait_hours 2>> $outputfile &' >> $uxfile
echo '$script_path/wait_for $batchdir/$pfile_success $batchdir 2>> $outputfile' >> $uxfile
echo 'cd $batchdir' >> $uxfile
echo '$script_path/nixcmd $batchque' >> $uxfile
#echo '$script_path/cpu_finder $uxfile >> $outputfile 2>>$batchdir/output_cpufinder &' >> $uxfile
echo '$script_path/cpu_finder $uxfile >> $outputfile 2>>$batchdir/output_cpufinder' >> $uxfile
echo "exit" >> $uxfile

chmod 777 $uxfile
echo $uxfile > $batchque
echo 2 > $batchdir/batch.flist
echo $uxfile >> $batchdir/batch.flist


#----------------------------------------
# Set up for batch IDL processing to come:
#----------------------------------------
uxfile=$batchdir/autoprocess_u$$
mxfile=`echo $batchdir/autolocsort_idl$fileid`
outputfile=`echo $batchdir/locsort_output.$label.$fileid`
echo ' ' > $outputfile
cd $batchdir

#---------------------------------------
# create the batch autoprocess scripts and
# copy the quickstart file
#---------------------------------------
matlab_mxfile=`echo $batchdir/autoprocess_x.m`
matlab_outputfile=`echo $batchdir/matlab_output.$label.$fileid`

echo "#!/usr/bin/ksh" > $uxfile
echo ' echo Running on `hostname` >> '  $batchdir/batch_log 
#echo '. $HOME/.idlspm/.global.ksh' >> $uxfile
echo '. $WFU_PATH/global.site.ksh' >> $uxfile
echo 'umask $batch_umask' >> $uxfile
echo ' ' >> $uxfile
echo 'ref_values=`$script_path/processing_stream '$datadir'`' >> $uxfile
echo 'spm_proc_type=`echo $ref_values | cut -d '"' '"' -f1,1`' >> $uxfile
echo 'email=`echo $ref_values | cut -d '"' '"' -f2,2`' >> $uxfile
### do not fix this
###echo 'spm_proc_type=5' >> $uxfile
echo "batchdir=$batchdir" >> $uxfile
echo 'if (test ${#email} -gt 0) then' >> $uxfile
echo '    if (test $email != "nobody") then' >> $uxfile
echo '        if (! test -f $batchdir/batch_email) then' >> $uxfile
echo '            echo $email > $batchdir/batch_email' >> $uxfile
echo '        fi' >> $uxfile
echo '    fi' >> $uxfile
echo 'fi' >> $uxfile
echo "logdir=$logdir" >> $uxfile
echo "uxfile=$uxfile" >> $uxfile
#echo "mxfile=$mxfile" >> $uxfile
echo "mydisplay=$mydisplay" >> $uxfile
#echo "outputfile=$outputfile" >> $uxfile
#echo '$script_path/launch_idlx  $mydisplay $mxfile $outputfile 19'  >> $uxfile
#echo 'running=`ls $batchdir  | grep running`' >> $uxfile
echo 'if (test $spm_proc_type -eq 5) then' >> $uxfile
echo "    mxfile=$matlab_mxfile" >> $uxfile
echo "    outputfile=$matlab_outputfile" >> $uxfile
echo '    $script_path/launch_matlabx $mydisplay $mxfile $outputfile 19'  >> $uxfile
echo 'else' >> $uxfile
echo '    . $HOME/.idlspm/.global.ksh' >> $uxfile
echo "    mxfile=$mxfile" >> $uxfile
echo "    outputfile=$outputfile" >> $uxfile
echo '    $script_path/launch_idlx $mydisplay $mxfile $outputfile 19'  >> $uxfile
echo 'fi' >> $uxfile
echo 'running=`ls $batchdir | grep running`' >> $uxfile
echo 'len=${#running}' >> $uxfile
echo 'if test $len -eq 0' >> $uxfile
echo '   then exit' >> $uxfile
echo 'fi' >> $uxfile
echo '$script_path/cpu_finder $uxfile >> $batchdir/output_unix 2>>$batchdir/output_cpufinder' >> $uxfile
echo "exit" >> $uxfile

chmod 777 $uxfile
echo $uxfile >> $batchque
o_quick_start=$script_path/quick_start
quick_start=$batchdir/quick_start
cp $o_quick_start $quick_start
chmod 777 $quick_start
echo $uxfile >> $batchdir/batch.flist


#----------------------------------
#Create the Matlab autoprocess_x.m script:
#----------------------------------
echo "%-------Autogenerated SPM5 Batch Processing Script"  > $matlab_mxfile
echo "%-------  `date`    "				>> $matlab_mxfile
echo "%-------  `hostname`  " 				>> $matlab_mxfile
echo ' ' 				>> $matlab_mxfile
echo "licensefilein = [];" 		>> $matlab_mxfile
echo "batchdir   = '$batchdir';" 	>> $matlab_mxfile
echo "subjectdir = '$datadir';" 	>> $matlab_mxfile
echo ' '				>> $matlab_mxfile

# ?? needed ?? YES! this or gospm(5) to make spm_select work in the matlab call to
#not good# echo "addpath(genpath('$WFU_SPM5'));"  >> $matlab_mxfile  #for distributed SPM5 pipeline !!not good!!
echo 'wfu_startup([],5);' >> $matlab_mxfile  #for distributed SPM5 pipeline
#echo 'gospm(5);' >> $matlab_mxfile	#for internal pipeline

echo ' '                                >> $matlab_mxfile
#echo "%addpath(genpath('$WFU_PATH'));" 	>> $matlab_mxfile
#echo "%addpath('$WFU_PATH/WFU_batch');"	>> $matlab_mxfile 
echo ' ' 				>> $matlab_mxfile
echo "[reply,licensefile] = wfu_batch_license(licensefilein,0,batchdir);" >> $matlab_mxfile
echo "if ~reply "			>> $matlab_mxfile
echo "	exit; "				>> $matlab_mxfile
echo "end" 				>> $matlab_mxfile
echo "licensefilein = licensefile" 	>> $matlab_mxfile
echo ' '				>> $matlab_mxfile
#echo "%spm_defaults;" 			>> $matlab_mxfile
echo "disp('Launching $batchdir/autoprocess_x.m');"  >> $matlab_mxfile
echo "wfu_autoSPM5(subjectdir,1)"	>> $matlab_mxfile
echo "fatalerr = wfu_batch_error('$matlab_mxfile');" >> $matlab_mxfile
echo "if fatalerr" 			>> $matlab_mxfile
echo "	exit;" 				>> $matlab_mxfile
echo "end" 				>> $matlab_mxfile
echo "pause(5);" 			>> $matlab_mxfile
echo ' '				>> $matlab_mxfile
echo "[reply,licensefile] = wfu_batch_license(licensefilein,1,batchdir);" >> $matlab_mxfile
echo "if reply" 			>> $matlab_mxfile
echo "	wfu_nixcmd('$uxfile');" 	>> $matlab_mxfile
echo "end" 				>> $matlab_mxfile
echo ' '				>> $matlab_mxfile
echo "disp(['Completed ','$matlab_mxfile']);" >> $matlab_mxfile
echo "exit;"				>> $matlab_mxfile

#----------------------------------
#Create the IDL autolocsort_lx script:
#----------------------------------
echo "!quiet = 1" > $mxfile
echo "print,'---------------------Entered IDLX------------------------'" >> $mxfile
echo "cd, current = here" >> $mxfile
echo "cd, '$idlspm_path'" >> $mxfile
echo "@bootfmri" >> $mxfile
echo "@bootspmx" >> $mxfile
echo "cd, here" >> $mxfile
echo "print,'requesting license'"  >> $mxfile
echo "licensefile=''" >> $mxfile
echo "batchdir='$batchdir/'" >> $mxfile
echo "reply = batch_license(licensefile=licensefile,kill=0,batchdir=batchdir)" >> $mxfile
echo "if not(reply) then exit" >> $mxfile
echo ";# --------------------------------------------------#;" >> $mxfile
echo ";# Use idl to create .locs files                     #;" >> $mxfile
echo ";# --------------------------------------------------#;" >> $mxfile
#echo "print,'---------------------Doing locsort------------------------'" >> $mxfile
#echo "outpath='$datadir'" >> $mxfile
#echo "locsort,inpath=outpath+'/locs'" >> $mxfile

echo ";# --------------------------------------------------#;" >> $mxfile
echo ";# Use idl to start the fmri processing              #;" >> $mxfile
echo ";# --------------------------------------------------#;" >> $mxfile
echo "print,'---------------------Entering Auto_process------------------------'" >> $mxfile
echo "outpath='$datadir'" >> $mxfile
echo "auto_process,datapath=outpath+'/' $forceflag" >> $mxfile

echo "helpstruc,!error_state" >> $mxfile
echo "print,!error_state.msg" >> $mxfile
echo "reply = batch_error('$uxfile');" >> $mxfile
echo "print,'batch_error = ' + strtrim(reply,2)" >> $mxfile
echo "wait,5" >> $mxfile
echo 'reply = batch_license(licensefile=licensefile,kill=1,batchdir=batchdir)' >> $mxfile
echo "print,'license_reply = ' + strtrim(reply,2)" >> $mxfile
echo "if reply then execute_nix, '$uxfile'" >> $mxfile


echo "print,'---------------------EXIT IDLX------------------------'" >> $mxfile
#in IDL4 we need to flush the buffer to print it
echo "if !version.release eq '5.4' then flush,-1" >> $mxfile
echo "exit" >> $mxfile


check_autolocsort_waiting
$quick_start



#exit
leave_autolocsort
