#!/bin/csh -f
############################################################
# Name:    selxavg
############################################################

set fmrianalver = `cat $FMRI_ANALYSIS_DIR/docs/version`;
set SELXAVG_VER = '\$Id: selxavg,v 1.33 2000/11/07 23:14:26 greve Exp greve $';

set inputargs = "$argv"

set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $SELXAVG_VER
  exit 0;
endif

set PWDCMD = `getpwdcmd`;

if ( $#argv == 0 ) then
  echo "USAGE: selxavg [-options] -i instem1 -p parfile 1 [-i instem2 -p parfile2 ...] -o outstem";
  echo "   instem1   - prefix of input file for 1st run";
  echo "   parfile1  - path of parfile for 1st run";
  echo "   [-tpexclfile file1] - file with timepoints of 1st run to exclude"
  echo "   [instem2] - prefix of input file for 2nd run";
  echo "   [parfile2]- path of parfile for 2st run";
  echo "   [-tpexclfile file2] - file with timepoints of 2nd run to exclude"
  echo "   outstem   - prefix of .bfloat output files"
  echo "      NOTE: you must specify all runs to process now";
  echo "Options:";
  echo "   -TR <float>           : temporal scanning resolution in seconds ";
  echo "   -TER <float>          : temporal estimation resolution <TR>";
  echo "   -timewindow <float>   : length of hemodynamic response in seconds <20>";
  echo "   -prestim <float>      : part of timewindow before stimulus onset (sec)";
  echo "   -nobaseline           : do not remove baseline offset "
  echo "   -detrend              : remove baseline offset and temporal trend"
  echo "   -rescale <float>      : rescale target (must run inorm first)";
  echo "   -nskip <int>          : skip the first n data points in all runs"
  echo "   -hanrad <float>       : radius of Hanning spatial filter (must be >= 1)"
  echo "   -gammafit delta tau   : fit HDR amplitude to a gamma function ";
  echo "   -timeoffset <float>   : offset added to time in par-file in seconds <0>";
  echo "   -nullcondid <int>     : Number given to the null condition <0>";
  echo "   -firstslice <int>     : first slice to process <auto>";
  echo "   -nslices <int>        : number of slices to process <auto>";
  echo "   -percent pscstem      : compute and save percent signal change in pscstem";
  echo "   -nonwhite <int>       : don't assume white noise (spec n autocor)";
  echo "   -ecovmtx  stem        : compute and save residual error covariance";
  echo "   -ecvmsn   stem        : residual error covariance, with spat norm";
  echo "   -lambda   stem        : normalized noise coviance matrix";
  echo "   -basegment            : force segmentation brain and air (with nonwhite)";
  echo "   -mail                 : send mail to user when finished"
  echo "   -eresdir dir          : directory in which to save eres vols";
  echo "   -signaldir  dir       : directory in which to save signal vols";
  echo "   -monly mfile          : don't run, just generate a matlab file";
  echo "   -synth seed           : synthesize data with white noise (seed = -1 for auto)";
  echo "   -parname name         : use parname in each input directory for paradigm file"
  echo "   -cfg file             : specify a configuration file";
  echo "   -umask umask          : set unix file permission mask"
  echo "   -version              : print version and exit"
#  echo "   -nconds     <int>     : number of conditions incl null <autodetect>"
#  echo "   -allvnull             : combine all non-null conditions into one condition"
#  echo "   -synch synchfile      : slice acquisition synchronzation";
  echo ""
  echo "  fMRIA Version $fmrianalver";
  echo "  $SELXAVG_VER"
  echo "  Author: Douglas N. Greve."
  echo "          Massachusetts General Hospital - NMR Center"
  echo "  Comments or questions: analysis-bugs@nmr.mgh.harvard.edu"
  echo ""
  exit 1;
endif

echo ""
echo "  fMRIA Version $fmrianalver";
echo "  selxavg $SELXAVG_VER"
echo "  Comments or questions: analysis-bugs@nmr.mgh.harvard.edu"
echo ""
echo "Current Directory: `$PWDCMD`"

# Set Default Values #
set eresdir   = ();
set signaldir = ();
set nullcondid = 0;
set nconds = -1;
set TR = ();
set TER = ();
set timewindow = 20.0;
set timeoffset =  0.0;
set firstslice = ();
set nslices = ();    # number of slices to process
set nslicesvol = (); # number of slices in the volume
set interleave = 0;
set UseSpatialFilter = 0;
set hanrad = 0;
set baseline = 1;
set detrend  = 0;
set nskip = 0;
set rescale = 0;
set nonwhite = 0;
set nnoise_autocorr = 1;
set basegment = 1; 
set tprestim = 0;
set PSCFile = ();
set PSCDatFile = ();
set PSCDOFFile = ();
set PSCStem = ();
set gammafit = 0;
set delta=2.25 
set tau = 1.25;
set mkeep = 0;
set monly = 0;
set mfile = ();
set synchfile = ();
set mailuser = 0;
set synth = 0;
set seed  = -1;
set allvnull = 0;

set instem  = ();
set parfile = ();
set parname = ();
set outstem = ();
set segstem = ();
set TPExclFile = ();
set cfgfile = ();
set ecvmsnstem = ();
set lambdastem = ();
set ecovmtxstem = ();
set scovmtxstem = ();

set usecfg = `echo $argv | egrep -e "-cfg" | wc -l`;

if($usecfg > 0) then
  goto parse_cfg;
  parse_cfg_return:
endif

goto parse_args;
parse_args_return:

if($#instem == 0) then
  echo "ERROR: no input volumes specified";
  exit 1;
endif

if($#TER == 0) set TER = $TR;
## Autodetect First and Number of Slices ##
if($#firstslice == 0) then
  set firstslice = `getfirstsliceno $instem[1]`;
  if($status) then
    echo "ERROR: detecting slice $firstslice of $instem[1]"
    exit 1;
  endif
endif
if($#nslices == 0) then
  set nslices = `getnslices $instem[1] $firstslice`;
  if($status) then
    echo "ERROR: nslices of $instem[1]"
    exit 1;
  endif
endif

if($#nslicesvol == 0) then
  set fstmp = `getfirstsliceno $instem[1]`;
  set nslicesvol = `getnslices $instem[1] $fstmp`;
  if($status) then
    echo "ERROR: nslices of $instem[1]"
    exit 1;
  endif
endif

goto dump_params;
dump_params_return:

goto check_params;
check_params_return:

set MATLAB = `getmatlab`;
if($status) exit 1;

#### Output Directory #######
set SADir = `dirname $outstem`;
set SABase = `basename $outstem`;
if ( ! -d $SADir ) then
  echo "INFO: Output directory $SADir does not exist, creating."
  mkdir -p $SADir
endif

if($#eresdir   != 0)  mkdir -p $eresdir
if($#signaldir != 0)  mkdir -p $signaldir

## Get path for log-file ##
set LF = $outstem"_sxa.log"
echo "Logfile is $LF"
rm -f $LF;
touch $LF;
echo ------------------------------------------ >> $LF
echo "selxavg $SELXAVG_VER" >> $LF
echo "Comments or questions: analysis-bugs@nmr.mgh.harvard.edu" >> $LF
uname -a >> $LF
hostname >> $LF
date >> $LF
echo $inputargs >> $LF

## Set path for matlab file ##
if(! $monly) then
  set MLF = "/tmp/$SABase"$$"_sxa.m"
else
  set MLF = $mfile;
endif

echo matlab file $MLF
rm -f $MLF;
echo "% Matlab file for selxavg `date`" >> $MLF
echo "% This file may be deleted " >> $MLF

#### Create ParFile Names (same for all Slices) ####
echo ParFiles: | tee -a $LF
set mParList = "strvcat(";
set c = ""
foreach par ($parfile)
  echo $par | tee -a $LF
  if ( ! -r $par ) then
    echo "ERROR: Parfile $par does not exist or is not readable" | tee -a $LF
    $PWDCMD | tee -a $LF
    echo $inputargs | tee -a $LF
    exit 1;
  endif
  set mParList = "$mParList $c '$par'";
  set c = ",";
end
set mParList = "$mParList );";

## Create a list of the exclude files (same for all slices) ####
set mTPExclFiles = " strvcat( ";
set c = "";
foreach exf ($TPExclFile)
  if ( "$exf" != "noexcl" && ! -r "$exf" ) then
    echo "ERROR: Cannot find exclude file $exf ... aborting" |tee -a $LF
    $PWDCMD | tee -a $LF
    echo $inputargs | tee -a $LF
    exit 1;
  endif
  set mTPExclFiles = "$mTPExclFiles $c '$exf'";
  set c = ",";
end
set mTPExclFiles = "$mTPExclFiles )";

#### Create datfile name (same for all Slices) ####
set datFile    = $outstem".dat";

#### Create file to track whether an error has occured ####
set okfile    = $outstem"_tmp.ok";
rm -f $okfile;

echo ------------------------------------------ >> $LF
echo `date`                    >> $LF
echo "instem  = $instem"    >> $LF
echo "outstem = $outstem"    >> $LF
echo "FirstSlice: $firstslice" >> $LF
echo "nSlices: $nslices"       >> $LF
echo "TR: $TR"                 >> $LF
echo "TimeWindow: $timewindow" >> $LF
echo nskip = $nskip             >> $LF
echo hanrad = $hanrad          >> $LF
echo baseline = $baseline         >> $LF
echo detrend = $detrend           >> $LF
echo "eresdir = $eresdir"         >> $LF
echo "signaldir = $signaldir"         >> $LF

############ Go through each slice ##############
@ slice     = $firstslice;
@ slice_max = $firstslice + $nslices;
while( $slice < $slice_max)
  echo -----------------------------------------------------------| tee -a $LF
  echo -- SelXAvg: Slice $slice `date` -------------- | tee -a $LF
  echo -- $outstem -------------- | tee -a $LF
  echo -----------------------------------------------------------| tee -a $LF
  date   | tee -a $LF

  if ($slice < 10) then
     set SliceStr = "00"$slice;
  else
     set SliceStr = "0"$slice;
  endif

  ### Create the hAvg, segment, and hcov names for this slice ###
  set hAvgFile = $outstem"_"$SliceStr".bfloat";
  set dofFile  = $outstem"_"$SliceStr".dof";
#  set hcovFile = $outstem"_hcov_"$SliceStr".bfloat";
  set segFile  = $outstem"-offset_"$SliceStr".bfloat";
  set ReeFile  = $outstem"_ree_"$SliceStr".dat";

  set UsePercent = 0;
  if($#PSCStem > 0) then
    set UsePercent = 1;
    set PSCFile    = $PSCStem"_"$SliceStr".bfloat";
    set PSCDatFile = $PSCStem".dat"
    set PSCDOFFile = $PSCStem"_"$SliceStr".dof";
  endif

  ### Create the mean-slope file for this slice ###
  set VxStatFile = $outstem"_vxst_"$SliceStr".bfloat";

  ### Create a list of the input files for this slice ###
  set mInputFiles = " strvcat( ";
  set c = "";
  foreach i ($instem)
    set infile = $i"_"$SliceStr".bshort";
    if ( ! -r "$infile" ) then
      set infile2 = $i"_"$SliceStr".bfloat";
      if ( ! -r "$infile2" ) then
        echo "ERROR: Cannot find input file $infile or $infile2... aborting" |tee -a $LF;
        $PWDCMD | tee -a $LF
        echo $inputargs | tee -a $LF
        exit 1;
      endif
      set infile = $infile2;
    endif
    set mInputFiles = "$mInputFiles $c '$infile'";
    set c = ",";
  end
  set mInputFiles = "$mInputFiles )";

  ### Create the matlab file ####
  touch $MLF;
  echo "%%% ----------------------------------- %%"    >> $MLF
  echo "% matlab file to run selxavg, Slice $slice"    >> $MLF;
  echo "% $MLF"                          >> $MLF;
  if (! $monly ) then
     echo "global QuitOnError;"             >> $MLF
     echo "QuitOnError = 1;"                >> $MLF
     echo "if (exist('fmri_sxaslice')==0)"        >> $MLF;
     echo "qoe('ERROR: matlab path incorrect');end;" >> $MLF  
  endif
  echo "TimeWindow = $timewindow;"  >> $MLF
  echo "TimeOffset = $timeoffset;"  >> $MLF
  echo "NullCondId = $nullcondid;"       >> $MLF
  echo "Nconds     = $nconds;"       >> $MLF
  echo "TR         = $TR;"          >> $MLF
  echo "TER         = $TER;"          >> $MLF
  echo "nSkip      = $nskip;"       >> $MLF
  echo "RescaleTarget  = $rescale;" >> $MLF
  echo "tPreStim       = $tprestim;"       >> $MLF
  echo "InputFiles     = $mInputFiles;" >> $MLF
  echo "InputStems     = splitstring('$instem');">> $MLF
  echo "HanRadius      = $hanrad;"      >> $MLF
  echo "RemoveBaseline = $baseline;" >> $MLF
  echo "RemoveTrend    = $detrend;"  >> $MLF
  echo "UsePercent     = $UsePercent;"  >> $MLF
  echo "PSCFile        = '$PSCFile';"  >> $MLF
  echo "PSCStem        = '$PSCStem';"  >> $MLF
  echo "PSCDatFile     = '$PSCDatFile';"  >> $MLF
  echo "PSCDOFFile     = '$PSCDOFFile';"  >> $MLF
  echo "NoiseType      = $nonwhite;"  >> $MLF
  echo "nNACorr        = $nnoise_autocorr;" >> $MLF
  echo "BASegment      = $basegment;"  >> $MLF
  echo "GammaFit      = $gammafit;"  >> $MLF
  echo "gfDelta       = $delta;"  >> $MLF
  echo "gfTau         = $tau;"  >> $MLF
  echo "ParFiles   = $mParList;"      >> $MLF
  echo "TPExclFiles   = $mTPExclFiles;"      >> $MLF
  echo "hAvgFile   = '$hAvgFile';"    >> $MLF
  echo "hAvgStem   = '$outstem';"    >> $MLF
  echo "SegStem    = '$segstem';"    >> $MLF
  echo "VxStatFile = '$VxStatFile';"  >> $MLF
  echo "dofFile    = '$dofFile';"     >> $MLF
#  echo "hcovFile    = '$hcovFile';"     >> $MLF
  echo "segFile    = '$segFile';"     >> $MLF
  echo "ReeFile    = '$ReeFile';"     >> $MLF
  echo "datFile    = '$datFile';"     >> $MLF
  echo "SliceNo    = $slice;"     >> $MLF
  echo "nslicesvol = $nslicesvol;"  >> $MLF
  echo "interleave = $interleave;"  >> $MLF
  echo "SynchFile  = '$synchfile';"     >> $MLF
  echo "EResDir    = '$eresdir';"         >> $MLF
  echo "SignalDir  = '$signaldir';"         >> $MLF
  echo "Synth      = $synth;"          >> $MLF
  echo "Seed       = $seed;"          >> $MLF
  echo "AllVNull   = $allvnull;"          >> $MLF
  echo "ecvmsnstem      = '$ecvmsnstem';"          >> $MLF
  echo "lambdastem      = '$lambdastem';"          >> $MLF
  echo "ecovmtxstem = '$ecovmtxstem';"          >> $MLF
  echo "scovmtxstem = '$scovmtxstem';"          >> $MLF
#  echo "fmri_sxavol ;"              >> $MLF
  echo "fmri_sxaslice ;"              >> $MLF
  if (! $monly ) then 
     echo "fprintf(1,'Creating $okfile\\n');" >> $MLF
     echo "fid = fopen('$okfile','w');" >> $MLF
     echo "fclose(fid);" >> $MLF
     echo "fprintf(1,'Done creating $okfile\\n');" >> $MLF
  endif
  if (! $monly ) echo "quit;" >> $MLF

  echo ----- Matlab File ----- >> $LF
  cat $MLF >> $LF
  echo ----------------------- >> $LF

  if (! $monly ) then
    echo  ---- matlab output ----- | tee -a $LF
    echo Computing Selective Average
    cat $MLF | nice $MATLAB  -display iconic | tee -a $LF
    echo  ---- matlab done ----- >> $LF

    if (! $mkeep) rm -f $MLF # clean up

    ## Check for errors during the matlab execution ##
    if ( ! -f $okfile ) then
      echo " "
      echo " "
      echo "--------------------------------------------------------" |tee -a $LF
      echo "ERROR: during matlab execution"       | tee -a $LF
      echo "selxavg aborted at `date`"       | tee -a $LF
      echo "See log file $LF for more detail"
      echo "--------------------------------------------------------" |tee -a $LF
      $PWDCMD | tee -a $LF
      echo $inputargs | tee -a $LF
      exit 1;
    endif
    rm -f $okfile;
  endif

  @ slice = $slice + 1;
end

#----------- for non-white ------------#
if($nonwhite && 0) then
  set lambdastem = $outdir/lambda
  avgcvm -i $ecvmsnstem -norm -o $lambdastem
  if($status) then
    echo "ERROR: avgcvm"
    exit 1;
  endif
endif

echo -----------++++++++++--------------------- | tee -a $LF
echo `date` | tee -a $LF
echo Done   | tee -a $LF
echo -----------++++++++++--------------------- | tee -a $LF

if ( $mailuser ) then
  echo "selxavg done at `date`" | mail -s "selxavg done" $user
endif

exit 0;
############################################################

############--------------##################
parse_args:

set cmdline = "$argv";
while( $#argv != 0 )

  set flag = $argv[1]; shift;
  
  switch($flag)

    case "-i":
      if ( $#argv == 0) goto arg1err;
      set instem = ($instem $argv[1]); shift;
      set TPExclFile = ($TPExclFile noexcl);
      breaksw

    case "-p":
      if ( $#argv == 0) goto arg1err;
      set parfile = ($parfile $argv[1]); shift;
      breaksw

    case "-parname":
      if ( $#argv == 0) goto arg1err;
      set parname = $argv[1]; shift;
      breaksw

    case "-tpexclfile":
    case "-tpx":
      if ( $#instem == 0 ) then
        echo "ERROR: instem must preceed tpxeclfile"
        exit 1
      endif    
      if ( $#argv == 0) goto arg1err;
      set TPExclFile[$#instem] = $argv[1]; shift;
      breaksw

    case "-o":
      if ( $#argv == 0) goto arg1err;
      if ( $#outstem != 0 ) then
        echo ERROR: only one outstem allowed.
        exit 1
      endif
      set outstem = $argv[1]; shift;
      breaksw

    case "-lambda":
      if ( $#argv == 0) goto arg1err;
      set lamdastem = $argv[1]; shift;
      breaksw

    case "-ecvmsn":
      if ( $#argv == 0) goto arg1err;
      set ecvmsnstem = $argv[1]; shift;
      breaksw

    case "-ecovmtx":
      if ( $#argv == 0) goto arg1err;
      set ecovmtxstem = $argv[1]; shift;
      breaksw

    case "-scovmtx":
      if ( $#argv == 0) goto arg1err;
      set scovmtxstem = $argv[1]; shift;
      breaksw

    case "-TR":
      if ( $#argv == 0) goto arg1err;
      set TR = $argv[1]; shift;
      breaksw

    case "-TER":
      if ( $#argv == 0) goto arg1err;
      set TER = $argv[1]; shift;
      breaksw

    case "-nullcondid":
    case "-ncid":
      if ( $#argv == 0) goto arg1err;
      set nullcondid = $argv[1]; shift;
      breaksw

    case "-nconds":
    case "-nbins":
      if ( $#argv == 0) goto arg1err;
      set nconds = $argv[1]; shift;
      breaksw

    case "-timewindow":
    case "-tw":
      if ( $#argv == 0) goto arg1err;
      set timewindow = $argv[1]; shift;
      breaksw

    case "-timeoffset":
    case "-to":
      if ( $#argv == 0) goto arg1err;
      set timeoffset = $argv[1]; shift;
      breaksw

    case "-firstslice":
    case "-fs":
      if ( $#argv == 0) goto arg1err;
      set firstslice = $argv[1]; shift;
      breaksw

    case "-nslices":
    case "-ns":
      if ( $#argv == 0) goto arg1err;
      set nslices = $argv[1]; shift;
      breaksw

    case "-nslicesvol":
      if ( $#argv == 0) goto arg1err;
      set nslicesvol = $argv[1]; shift;
      breaksw

    case "-baseline":
    case "-bl":
      set baseline = 1;
      breaksw

    case "-nobaseline":
      set baseline = 0;
      breaksw

    case "-interleave":
      set interleave = 1;
      breaksw

    case "-nointerleave":
      set interleave = 0;
      breaksw

    case "-detrend":
    case "-dt":
      set detrend = 1; 
      set baseline = 1; 
      breaksw

    case "-nskip":
      if ( $#argv == 0) goto arg1err;
      set nskip = $argv[1]; shift;
      breaksw

    case "-hanrad":
    case "-hr":
      if ( $#argv == 0) goto arg1err;
      set hanrad = $argv[1]; shift;
      breaksw

    case "-prestim":
    case "-ps":
      if ( $#argv == 0) goto arg1err;
      set tprestim = $argv[1]; shift;
      breaksw

    case "-percent":
      if ( $#argv == 0) goto arg1err;
      set PSCStem = $argv[1]; shift;
      breaksw

    case "-rescale":
      if ( $#argv == 0) goto arg1err;
      set rescale = $argv[1]; shift;
      breaksw

    case "-mkeep":
      set mkeep = 1; 
      breaksw

    case "-monly":
      if ( $#argv == 0) goto arg1err;
      set monly = 1; 
      set mkeep = 1; 
      set mfile = $argv[1]; shift;
      breaksw

    case "-cfg":
      if ( $#argv == 0) goto arg1err;
      set cfgfile = $argv[1]; shift;
      if(! -e $cfgfile ) then
        echo "ERROR: $cfgfile does not exist"
        exit 1;
      endif
      breaksw

    case "-eresdir":
      if ( $#argv == 0) goto arg1err;
      set eresdir = $argv[1]; shift;
      breaksw

    case "-signaldir":
      if ( $#argv == 0) goto arg1err;
      set signaldir = $argv[1]; shift;
      breaksw

    case "-synch":
    case "-synchfile":
      if ( $#argv == 0) goto arg1err;
      set synchfile = $argv[1]; shift;
      breaksw

    case "-synth":
      if ( $#argv == 0) goto arg1err;
      set seed  = $argv[1]; shift;
      set synth = 1;
      breaksw

    case "-allvnull":
    case "-avf":
      set allvnull = 1;
      breaksw

    case "-debug":
      set verbose = 1; 
      set echo = 1;
      breaksw

    case "-nonwhite":
      if ( $#argv == 0) goto arg1err;
      set nonwhite = 1; 
      @ nnoise_autocorr = $argv[1];shift;
      if ($nnoise_autocorr < 2) then
        echo "INFO: nonwhite=1 will assume white noise";
        set nonwhite = 0; 
      endif
      breaksw

    case "-basegment":
    case "-baseg":
      set basegment = 1; 
      breaksw

    case "-nobasegment":
    case "-nobaseg":
      set basegment = 0; 
      breaksw

    case "-segstem":
      if ( $#argv == 0) goto arg1err;
      set segstem = $argv[1]; shift;
      breaksw


    case "-gammafit":
    case "-gf":
      if ( $#argv < 2) then
        echo "Flag $flag requires two arguments";
        exit 1;
      endif
      set gammafit = 1;
      set delta = $argv[1];shift;
      set tau   = $argv[1];shift;
      breaksw

    case "-umask":
      if ( $#argv == 0) goto arg1err;
      umask $1; shift;
      breaksw

    case "-mail":
      set mailuser = 1;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized.
      echo $cmdline
      exit 1
      breaksw
  endsw

end
goto parse_args_return;
############--------------##################

############--------------##################
dump_params:
echo ------- selxavg parameters ------------
echo OutputStem: $outstem
echo InputStems: $instem
echo ParFiles:   $parfile
echo ExclFiles:  $TPExclFile
echo nullcondid: $nullcondid
echo TR:         $TR
echo TER:        $TER
echo timewindow: $timewindow
echo timeoffset: $timeoffset
echo firstslice: $firstslice
echo nslices:    $nslices
echo baseline:   $baseline
echo detrend:    $detrend
echo nskip:      $nskip
echo hanrad:     $hanrad
echo prestim:    $tprestim
echo PSCStem:    $PSCStem
echo rescale:    $rescale
echo nonwhite:   $nonwhite
echo nnoise_autocorr: $nnoise_autocorr
echo basegment:  $basegment
echo gammafit:   $gammafit
echo delta:      $delta
echo tau:        $tau
echo ecovmtx:    $ecovmtxstem
echo ecvmsn:     $ecvmsnstem
echo interleave  $interleave  
echo nslicesvol  $nslicesvol  
echo --------------------------------------
goto dump_params_return;
############--------------##################

############--------------##################
check_params:
  if ($#instem == 0) then
     echo "ERROR: must specify at least one input stem";
     exit 1
  endif

  if($rescale > 0) then
    foreach stem ($instem)
      set mvfile = $stem.meanval
      if(! -e $mvfile) then
        echo "ERROR: $stem does not have a .meanval file, run inorm"
        exit 1;
      endif
    end
  endif

  if($#TR == 0) then
    echo "ERROR: must specify TR"
    exit 1;
  endif

  if ($#outstem == 0) then
     echo "ERROR: must specify output stem";
     exit 1
  endif

  set outdir = `dirname $outstem`;
  mkdir -p $outdir;
  pushd $outdir > /dev/null
  set outdir = `$PWDCMD`;
  popd > /dev/null

  if($#parfile != 0 && $#parname != 0) then
    echo "ERROR: cannot use both -p and -parname options"
    exit 1;
  endif

  if($#parname != 0) then
     set parfile = ();
     foreach i ($instem)
       set idir = `dirname $i`;
       set parfile = ($parfile $idir/$parname);
     end
  endif

  if ($#instem != $#parfile) then
     echo "ERROR: Number of input stems ($#instem) does not "
     echo "       match number of parfiles ($#parfile)"
     exit 1
  endif

  if ($#instem != $#TPExclFile) then
     echo "ERROR: Number of input stems ($#instem) does not "
     echo "       match number of tpexcfiles ($#TPExclFile)"
     exit 1
  endif

  if ($#PSCStem && (! $baseline && ! $detrend) ) then
     echo "ERROR: must use -baseline or -detrend must be used with -percent option"
     exit 1
  endif

  if($nonwhite && $#ecvmsnstem == 0 && 0) then
    set ecvmsnstem = $outdir/ecvmsn
    echo "INFO: setting ecvmsn stem to $ecvmsnstem"
  endif


goto check_params_return;
############--------------##################


############--------------##################
arg1err:
  echo "ERROR: flag $flag requires one argument"
  exit 1
############--------------##################

############--------------##################
parse_cfg:
  @ n = 1;
  while($n < $#argv)
    if("$argv[$n]" == "-cfg") then
      @ m = $n + 1;
      set cfgfile = $argv[$m];
      if(! -e $cfgfile ) then
        echo "ERROR: $cfgfile does not exist"
        exit 1;
      endif
    endif
    @ n = $n + 1;
  end

  if($#cfgfile == 0) then
    echo "ERROR: must specify config file with -cfg flag";
    exit 1;
  endif

  echo "--- Parsing Config File: $cfgfile ----"
  set cfgargs = `cat $cfgfile`;
  # echo $cfgargs
  set argv = ($cfgargs $argv);
  
goto parse_cfg_return;
