#! /bin/csh -f

#
# tkmedit-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2007/12/10 21:16:13 $
#    $Revision: 1.24.2.2 $
#
# Copyright (C) 2002-2007,
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-bugs@nmr.mgh.harvard.edu
#


set VERSION = '$Id: tkmedit-sess,v 1.24.2.2 2007/12/10 21:16:13 greve Exp $';
set inputargs = ($argv);

set PWDCMD = pwd

set analysis      = ();
set anapend       = ();
set sessid        = ();
set isxavgmethod  = ();
set hsurf = ();

set mapanalysis   = ();
set mapsessid     = ();
set mapisxavgmethod  = ();

set contrastlist = ();
set space      = ();
set subject    = ();
set mrivolid   = orig;
set auxvolid   = brainmask.mgz;

set hdrdir = ();
set sessdir = ();

set mapmeanimg = 0;
set map    = ();
set sessanat = 0;
set asd = ();
set ScriptOnly = 0;
set umaskarg = ();
set underlay = ();
set thmin = 2;
set thmax = 7;
set nohdr = 0;
set nosig = 0;
set rawrun = ();
set motioncor = 0;
set mc = "";
set fsd = ();
set fthresh = 2;
set fmax    = 4;
set group = ();
set SessIsGroup = 0;
set spacedir = ();
set segmentation = ();
set segcolor = ();
set segopacity = .3;
set ext = ();
set usestatic = 0;
set hdrtmpdir = ()
set talreg = 0; # show on tal using register.tal
set MGZ = .mgz;
set DoAllContrasts = 0;

set nolog = 0;
set tmpdir = ();
if($?FREESURFER_TMP_DIR) then
  if(-e $FREESURFER_TMP_DIR) set tmpdir = $FREESURFER_TMP_DIR;
endif

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

if($#argv == 0) goto usage_exit;

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

##### Create a log file ######
if(! $nolog) then
  set logdir = `$PWDCMD`/log;
  mkdir -p $logdir
  if(! -e $logdir || ! -w $logdir) then
    echo "WARNING: could not create $logdir"
    set LF = /dev/null
  else
    set LF = $logdir/tkmedit-sess.log
    if(-e $LF) mv $LF $LF.old
  endif
else
  set LF = /dev/null
endif

echo "--------------------------------------------------------------"
echo "tkmedit-sess logfile is $LF"
echo "--------------------------------------------------------------"

echo "tkmedit-sess log file" >> $LF
echo $VERSION   >> $LF
id            >> $LF
echo "$0"     >> $LF
echo "$argv"  >> $LF
$PWDCMD           >> $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR"  | tee -a $LF
uname -a      >> $LF
date          >> $LF
which tkmedit >> $LF

set StudyDir = `pwd`;

## Get functional subdirectory from the info file ##
if($#analysis != 0) then
  if(! -e $analysis ) then
    echo "ERROR: $analysis does not exist. Try running mkanalysis-sess" |& tee -a $LF
    exit 1;
  endif
  set infofile = $analysis/analysis.info
  set fsd = `cat $infofile | awk '{if($1 == "fsd") print $2}'`;
  set designtype = `cat $infofile | awk '{if($1 == "designtype") print $2}'`;
  if($#designtype == 0) then
    set designtype = `cat $infofile | awk '{if($1 == "avgtype") print $2}'`;
  endif
else
  if($#fsd == 0) set fsd = bold;
  set nohdr = 1;
  set nosig = 1;
endif

if("$designtype" != "event-related") set nohdr = 1;

## Get map functional subdirectory from the info file ##
if($#mapanalysis != 0) then
  if(! -e $mapanalysis ) then
    echo "ERROR: $mapanalysis does not exist. Try running mkanalysis-sess" |& tee -a $LF
    exit 1;
  endif
  set mapfsd = `cat $mapanalysis/analysis.info | awk '{if($1 == "fsd") print $2}'`;
else
  if($#mapfsd == 0) set mapfsd = bold;
  set nohdr = 1;
  set nosig = 1;
endif

if($#isxavgmethod == 0) then
  if($space == native) then
    set spacesubdir = ();
  else
    set spacesubdir = $spacedir
  endif
else
  if($isxavgmethod == fixed) then
    set spacesubdir = $spacedir-ffx
  else
    set spacesubdir = $spacedir-rfx
  endif
endif

set hdrdir = $sess/$fsd/$analysis$anapend/$spacesubdir
if($#ext == 0) then
  set hstem = $hdrdir/h-offset
  set ext = `fast_getext $hstem`
  if($status) then
    echo $ext
    exit 1;
  endif
endif

#----------------------------------------------------#
if(! $nohdr) then

  if(! -e $hdrdir) then
    echo "ERROR: cannot find $hdrdir"
    exit 1;
  endif
  set hdrstem = $hdrdir/h

  if($space == native) then
    if(! $talreg) then
      #set regfile = $StudyDir/$sess/$fsd/register.dat;
      set regfile = $sess/$fsd/register.dat;
    else
      #set regfile = $StudyDir/$sess/$fsd/register.tal;
      set regfile = $sess/$fsd/register.tal;
    endif
  else
    set regfile = $hdrdir/register.dat;
  endif

  if(! -e $regfile ) then
    echo "ERROR: cannot find $regfile"
    exit 1;
  endif

  # get the full path the regfile
  set d = `dirname $regfile`;
  pushd $d > /dev/null
  set d = `pwd`;
  popd > /dev/null
  set regfile = $d/`basename $regfile`;

  #cp $regfile $hdrdir
  set hdrregfile = $regfile

endif

#----------------------------------------------------#
set mapconcatfile = ();
if(! $nosig) then

  if($#mapisxavgmethod == 0) then
    if($space == native) then
      set spacesubdir = ();
    else
      set spacesubdir = $spacedir
    endif
  else
    if($mapisxavgmethod == fixed) then
      set spacesubdir = $spacedir-ffx
    else
      set spacesubdir = $spacedir-rfx
    endif
  endif

  set maphdrdir = $mapsess/$mapfsd/$mapanalysis$anapend/$spacesubdir

  set maplist = ()
  foreach contrast ($contrastlist)
    set condir = $maphdrdir/$contrast
    if(! -e $condir) then
      echo "ERROR: cannot find $condir"
      exit 1;
    endif
    set mapstem = $condir/$map
    set mapfile = `stem2fname $mapstem`
    if($status) then
      echo "$mapfile"
      exit 1;
    endif
    set maplist = ($maplist $mapfile)
  end
  set mapconcatfile = $mapsess/$mapfsd/$mapanalysis$anapend/tkmconcat.nii
  set cmd = (mri_concat $maplist --o $mapconcatfile);
  echo $cmd
  $cmd
  if($status) exit 1;

  if($space == native) then
    if(! $talreg) then
      #set regfile = $StudyDir/$sess/$fsd/register.dat;
      set regfile = $sess/$fsd/register.dat;
    else
      #set regfile = $StudyDir/$sess/$fsd/register.tal;
      set regfile = $sess/$fsd/register.tal;
    endif
  else
    set regfile = $maphdrdir/register.dat;
  endif
  if(! -e $regfile ) then
    echo "ERROR: cannot find $regfile"
    exit 1;
  endif

  set d = `dirname $regfile`;
  pushd $d > /dev/null
  set d = `pwd`;
  popd > /dev/null
  set regfile = $d/`basename $regfile`;

  set mapregfile = $regfile

  set mapoption = (-overlay $mapconcatfile)
  set mapoption = ($mapoption -overlay-reg $mapregfile)
  
endif

if($#subject == 0) set subject = `cat $regfile | head -n 1`;
echo "INFO: subject is $subject"

if($subject != talairach && $space == tal) set mrivolid = talairach

set tmp = $SUBJECTS_DIR/$subject/mri/$mrivolid.mgz
if(-e $tmp) then
  echo "Cannot find $tmp, assuming COR"
  set MGZ = ".mgz";
else
  set MGZ = ();
endif

if($#auxvolid) then
  if(! -e $SUBJECTS_DIR/$subject/mri/$auxvolid) then
    echo "ERROR: $auxvolid does not exist for subject $subject"
    exit 1;
  endif
else
  set auxvolid = brain$MGZ;
  if(! -e $SUBJECTS_DIR/$subject/mri/$auxvolid) set auxvolid = ();
endif

set hdroption  = ""
set offsetoption = ""

## Get the full path to the hdr dir ##
pushd $hdrdir > /dev/null
set hdrdir = `$PWDCMD`;
popd  > /dev/null

if(! $nohdr ) then
  ## make sure that dat file exists
  set hdrdat = $analysis$anapend/h.dat
  if(! -e $hdrdat ) then
    echo "ERROR: could not find $hdrdat" |& tee -a $LF
    pwd
    exit 1;
  endif

  ## Check whether an IRF was used ##
  set tmp = `grep Nh $hdrdat`;
  @ Nh = $tmp[2];
  if($Nh != 1 && ! $nohdr) then
    set hdroption  = (-timecourse $hdrdir/h.$ext )
    set hdroption  = ($hdroption -timecourse-reg $hdrregfile)
    set offsetoption = (-timecourse-offset $hdrdir/h-offset.$ext)
  endif
endif

## Get the directory for the anatomicals ##
if(! $sessanat ) then
  if($subject != talairach || $SessIsGroup) then
    echo "INFO: subject is $subject" |& tee -a $LF
    if(! -e $SUBJECTS_DIR/$subject ) then
      echo "ERROR: subject $subject does not exist in data base" |& tee -a $LF
      echo "SUBJECTS_DIR: $SUBJECTS_DIR" |& tee -a $LF
      exit 1;
    endif
    set anatoption = "$subject $mrivolid$MGZ";
    echo "mrivolid $mrivolid$MGZ "
  else
    set tmpreg = $sess/$fsd/register.dat
    set tmpsubject = `head -n 1 $tmpreg`;
    set anatdir = $SUBJECTS_DIR/$tmpsubject/mri/talairach
    if(-e $anatdir) then
      set subject    = $tmpsubject;
      set anatoption = "$subject talairach";
    else
      set anatdir = $SUBJECTS_DIR/$subject/mri/$mrivolid
      set anatoption = "$subject $mrivolid$MGZ";
    endif
  endif
else
  set tmp = `ls -d $sess/$asd/???`;
  if($#tmp == 0) then
    echo "ERROR: cannot find a run in $sess/$asd" |& tee -a $LF
    exit 1;
  endif
  set anatdir = $tmp[1];
  set anatoption = "-f $anatdir";
endif

#--------- Prep the segmentation ---------------------------#
if($#segmentation != 0) then

  if(-e $segmentation) then
     set segdir = $segmentation
  else
    set segdir = $SUBJECTS_DIR/$subject/mri/$segmentation$MGZ
    if(! -e $segdir ) then
      echo "ERROR: cannot find either $segmentation or $segdir"
      exit 1;
    endif
  endif

  if(! -e $segcolor) then
    set tmp = $segdir/$segcolor
    if(-e $tmp) then
      set segcolor = $tmp;
    else
      echo "ERROR: cannot find either $tmp or $segcolor"
      exit 1;
    endif
  endif
  set segoption = (-segmentation $segdir $segcolor )
  set segoption = ($segoption -segmentation-opacity $segopacity)
else
  set segoption = ();
endif

#------- Create and run the cmd line -----------------------#
set TKMEDIT = tkmedit
if($usestatic) set TKMEDIT = $TKMEDIT.static
set cmd = ($TKMEDIT $anatoption $hsurf $mapoption $hdroption $offsetoption)
set cmd = ($cmd -fthresh $fthresh -fmax $fmax)
set cmd = ($cmd $segoption);
if($#auxvolid) set cmd = ($cmd -aux $auxvolid);
if($subject == talairach || $subject == fsaverage) then
  set set cmd = ($cmd -bc-main .65 11);
endif
echo "------------------------"|& tee -a $LF
echo "SUBJECTS_DIR $SUBJECTS_DIR"|& tee -a $LF
$PWDCMD|& tee -a $LF
echo $cmd|& tee -a $LF
echo "------------------------"|& tee -a $LF

@ nth = 0;
foreach c ($contrastlist)
  echo $nth $c
  @ nth = $nth + 1;
end

$cmd|& tee -a $LF
if($status) then
  echo "tkmedit failed"|& tee -a $LF
  exit 1;
endif

if($#mapconcatfile) rm -f $mapconcatfile
if($#hdrtmpdir) rm -f $hdrtmpdir/*

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

############--------------##################
parse_args:
set cmdline = ($argv);
while( $#argv != 0 )

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

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

    case "-call":
      set DoAllContrasts = 1;
      breaksw

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

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

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

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

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

    case "-no-aux":
      set auxvolid = ();
      breaksw

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

    case "-map":
      if ( $#argv == 0) goto arg1err;
      set map = $argv[1]; shift;
      if($map != sig && $map != minsig && $map != iminsig && $map != t) then
        #echo "ERROR: map must be either sig, minsig, iminsig, or t"
        # exit 1;
      endif
      breaksw

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

    case "-sf":
      if ( $#argv == 0) goto arg1err;
      set sessfile = $argv[1]; shift;            
      if( ! -e $sessfile ) then
        echo "ERROR: $sessfile does not exist"
        exit 1;
      endif
      set tmp = `cat $sessfile`;
      if($#tmp == 0) then
        echo "ERROR: $sessfile is empty"
        exit 1;
      endif
      set sessid = $tmp[1];
      if($#tmp > 1) then
        echo "WARNING: $sessfile has more than one session, using $sessid"
      endif
      breaksw

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

    case "-df":
      if ( $#argv == 0) goto arg1err;
      set df = $argv[1]; shift;
      if(! -e $df) then
        echo "ERROR: cannot find $df"
        exit 1;
      endif
      set sessdir = ($sessdir `cat $df`);
      breaksw

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

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

    case "-isxavg":
      if ( $#argv == 0) goto arg1err;
      set isxavgmethod = $argv[1]; shift;
      if($isxavgmethod != "fixed" && $isxavgmethod != "random") then
        echo "ERROR: -isxavg must be either fixed or random" 
        exit 1;
      endif
      breaksw

    case "-mapgroup":
    case "-group":
      echo "ERROR: $flag flag is no longer valid. Specify the group "
      echo "       using the  -s or -sf flag."
      exit 1;
      breaksw

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

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

    case "-mapisxavg":
      if ( $#argv == 0) goto arg1err;
      set mapisxavgmethod = $argv[1]; shift;
      if($mapisxavgmethod != "fixed" && $mapisxavgmethod != "random") then
        echo "ERROR: -mapisxavg must be either fixed or random"  
        exit 1;
      endif
      breaksw

    case "-subjdir":
      if ( $#argv == 0) goto arg1err;
      set subjdir = $argv[1]; shift;
      if(! -e $subjdir) then
        echo "ERROR: $subjdir does not exist"
        exit 1;
      endif
      pushd $subjdir > /dev/null
      set subjdir = `$PWDCMD`;
      popd > /dev/null
      setenv SUBJECTS_DIR $subjdir
      echo "INFO: setting SUBJECTS_DIR to $SUBJECTS_DIR"
      breaksw

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

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

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

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

    case "-thmask":
      set fthresh = .5;
      set fmax    =  1;
      breaksw

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

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

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

    case "-seg":
      if ( $#argv < 2) then
        echo "ERROR: -seg needs to arguments"
        exit 1;
      endif
      set segmentation = $argv[1]; shift;
      set segcolor = $argv[1]; shift;
      breaksw

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

    case "-aseg":
      set segmentation = aseg;
      set segcolor = $FREESURFER_HOME/tkmeditColorsCMA
      breaksw

    case "-aparc+aseg":
      set segmentation = aparc+aseg;
      set segcolor = $FREESURFER_HOME/FreeSurferColorLUT.txt
      breaksw

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

    case "-sessanat":
    case "-samesess":
      set sessanat = 1;
      breaksw

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

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

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

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

    case "-motioncor":
      set motioncor = 1;
      set mc = "mc";
      breaksw

    case "-mgz":
      set MGZ = ".mgz";
      breaksw

    case "-cor":
      set MGZ = "";
      breaksw

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

    case "-static":
      set usestatic = 1;
      breaksw

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

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

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

    case "-scriptonly":
      set ScriptOnly = 1;
      breaksw

    case "-cwd":
      set cwd = `$PWDCMD`;
      set sessdir = `dirname $cwd`;
      set sessid  = `basename $cwd`;
      breaksw

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

end

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

############--------------##################
check_params:

  if($#analysis == 0) then
    echo "ERROR: no analysis specified" 
    exit 1;
  endif
  if(! -e $analysis) then
    echo "ERROR: $analysis does not exist"
    exit 1;
  endif
  if($#mapsessid == 0)   set mapsessid   = $sessid;
  if($#mapanalysis == 0) set mapanalysis = $analysis;
  if(! -e $mapanalysis) then
    echo "ERROR: $mapanalysis does not exist"
    exit 1;
  endif
  if($DoAllContrasts) then
    set matlist = (`ls $mapanalysis/*.mat`);
    if($status) then
      echo "ERROR: cannot find any contrasts in $analysis"
      exit 1;
    endif
    foreach m ($matlist)
      set c = `basename $m .mat`;
      set contrastlist = ($contrastlist $c);
    end
  endif
  if($#contrastlist == 0) then
    echo "ERROR: no contrast specified" 
    exit 1;
  endif
  if($#contrastlist == 0)  set nosig = 1;
  if($#analysis == 0)  set nohdr = 1;
  if($#contrastlist != 0 && $#analysis == 0 ) then
     echo "ERROR: must specify an analysis with contrast" 
     exit 1
  endif

  if($#sessid == 0) then
    echo "ERROR: no sessions specified" 
    exit 1;
  endif

  if($mapmeanimg == 1 && $#contrastlist != 0) then
    echo "ERROR: cannot map mean image and contrast" 
    exit 1;
  endif

  # Make sure that everything has a value # 
  if($#space == 0) set space = native;
  if($#asd == 0)   set asd   = 3danat;
  if($#map == 0) then
    set map = sig;
    if($#contrastlist == 1) then
      if($contrastlist == omnibus) set map = fsig;
    endif
  endif


  if($mapmeanimg == 1) then
    set map = h-offset;
    set thmin =  500
    set thmax = 1000
  endif

  if($mapmeanimg == 1 && $#analysis == 0) then
    echo "ERROR: must specify analysis when mapping mean image" 
    exit 1;
  endif

  if($space != "native" && $space != "tal") then
    echo "ERROR: space must be either native or tal " 
    exit 1;
  endif

  #--------------------------------------------------------------------#
  if($#sessdir == 0) set sessdir = ".";
  set sess = ();
  foreach d ($sessdir)
    set tmp = "$d/$sessid"
    if(-e $tmp) then
      set sess = ($sess $tmp);
      echo "INFO: Found session in: $sess" 
    endif
  end
  if($#sess == 0) then
    echo "ERROR: could not find $sessid" 
    exit 1;
  endif
  if($#sess > 1) then
    echo "ERROR: found multiple sessions for $sessid" 
    exit 1;
  endif

  set sessinfo = $sess/session.info
  if(-e $sessinfo) then
    set SessIsGroup = `grep GroupAverage $sessinfo | wc -l`;
    if($SessIsGroup) then
      echo "INFO: $sessid is a group average"  
      if($space != tal) then
        echo "ERROR: no support for tkmedit of $space space for group" 
        exit 1;
      endif
      if($#isxavgmethod == 0) then
        echo "ERROR: must specify -isxavg with group" 
        exit 1;
      endif
      if($isxavgmethod == random) set nohdr = 1;
    endif
  endif

  #--------------------------------------------------------------------#
  set mapsess = ();
  foreach d ($sessdir)
    set tmp = $d/$mapsessid
    if(-e $tmp) then
      set mapsess = ($mapsess $tmp);
      echo "INFO: Found session in: $mapsess" 
    endif
  end
  if($#mapsess == 0) then
    echo "ERROR: could not find $mapsessid" 
    exit 1;
  endif
  if($#mapsess > 1) then
    echo "ERROR: found multiple sessions for $mapsessid" 
    exit 1;
  endif

  set sessinfo = $mapsess/session.info
  set MapSessIsGroup = `grep GroupAverage $sessinfo | wc -l`;
  if($MapSessIsGroup) then
    echo "INFO: $sessid is a group average"  
    if($#mapisxavgmethod == 0) set mapisxavgmethod = $isxavgmethod;
    if($space != tal) then
      echo "ERROR: no support for tkmedit of $space space for group" 
      exit 1;
    endif
    if($#mapisxavgmethod == 0) then
      echo "ERROR: must specify -mapisxavg with group" 
      exit 1;
    endif
  endif

  if($#rawrun != 0 && $space != native ) then
    echo "ERROR: cannot view raw with space $space" 
    exit 1;
  endif

  if($space != native && $sessanat ) then
    echo "ERROR: cannot use -sessanat with space $space" 
    exit 1;
  endif

  if($#spacedir == 0) set spacedir = $space;

  if($talreg && $space != native) then
    echo "ERROR: space must be native with -talreg. Rerun without -space."
    exit 1
  endif


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

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

############--------------##################
usage_exit:
  echo "USAGE: tkmedit-sess"
  echo "Options:";
  echo "   -volid  FSVolId : name of volume under subject/mri"
  echo "   -mgz            : assume anatomicals are in mgz format"
  echo "   -analysis  analysisname : name of session-level functional analysis";
  echo "   -s         sessid   (only one allowed)"
  echo "   -isxavg    method (fixed or random)"
  echo "   -contrast  contrastname : contrast name"
  echo "   -call      : do all contrasts"
  echo "   -map       mapname      : <sig>, minsig, iminsig, t"
  echo "   -mapanalysis analysisname : name of session-level functional analysis";
  echo "   -mapsess     sessid from which to get the map";
  echo "   -mapisxavg   method "

  echo "   -space       spacename : <native> or tal"
  echo "   -d           sessdir     ..."

  echo "   -sessanat      : use session 3d anatomical instead of recon"
  echo "   -fsd dir       : functional subdirectory (bold)"
  echo "   -asd dir       : anatomical subdirectory (3danat)"
  echo "   -seg segvol segcolor : segmentation vol and color"
  echo "   -aseg : show automatic segmentation (must alreay exist)"
  echo "   -aparc+aseg : show aparc+aseg segmentation (must alreay exist)"
  echo "   -segopacity opacity : between 0 and 1 (def .3)"
  echo "   -hsurf hemi.surf : load hemi.surf with volume"
  echo "   -fthresh fthresh : threshold for color overlay"
  echo "   -fmax    fmax    : saturation threshold for color overlay"
  echo ""
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -version       : print version and exit"
  echo "   -fthresh thresh : minimum threshold for display ($thmin)"
  echo "   -fsat    thresh : saturation threshold for display "
  echo "   -static : use statically linked version"
  echo "   -oldread : for use with old version of tkmedit"
#  echo "   -thmax     thresh : maximum threshold for display ($thmax)"
#  echo "   -nohdr            : do not load/show hemodynamic response"
#  echo "   -nosig            : do not load/show significance map"
#  echo "   -raw       run    : display raw MR from run"
#  echo "   -motioncor        : display motion corrected raw data (with -raw)"
  echo ""
exit 1;
