#!/bin/csh -f
# mri_autorecon
# Performs the automatic portion of anatomical recontruction. This is
# broken into two stages:
#  Stage 1: 
#    a. Creating the subject's directory structure
#    b. Copying/Converting input data
#    c. Motion Correction
#    d. Creating symbolic link
#    a. Segmentation
#  Stage 2: 
#    b. Fixing
#    c. Morphing
#    d. Making Final Surfaces
#

set VERSION = '$Id: mri_autorecon,v 1.1 2004/01/30 23:22:30 kteich Exp $';

set subjid          = ();
set subjectsdatadir = ();
set subjectslinkdir = ();
set inputlist   = ();
set sessdir     = ();
set sessasd     = (); 
set mailuser    = ();
set submit      = 0;
set submitted   = ();
set LF          = ();
set stage       = 0;  # both 1 and 2 #
set PrintHelp   = 0;

which pawd > /dev/null
if(! $status) then
  set PWDCMD = pawd;
else
  set PWDCMD = pwd;
endif

# If no args, print usage and exit #
if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

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

goto pre_parse_args;
pre_parse_args_return:

if($#submitted != 0) then
  echo "------------------------------------------------------" 
  echo "INFO: this program was submitted by process $submitted" 
  if(! -e $submitpwd ) then
    echo "ERROR: cannot find $submitpwd"
    exit 1;
  endif
  cd $submitpwd 
  echo "------------------------------------------------------" >>  $LF
  echo "INFO: this program was submitted by process $submitted" >>  $LF
  echo "------------------------------------------------------" >>  $LF
  echo "  " >>  $LF
else
  set submitted   = $$;
  set submitpwd   = `$PWDCMD`;
endif

set StartDate = `date`;

##### Create a log file ######
if($#LF == 0) then
  set LF = mri_autrecon-$$.log
  if(-e $LF) mv $LF $LF.old
endif

#### Get full path for logfile ##
set logfilebase = `basename $LF`;
set logfiledir  = `dirname $LF`;
mkdir -p $logfiledir
pushd $logfiledir > /dev/null
set lopfiledir = `$PWDCMD`;
popd  > /dev/null
set LF = $logfiledir/$logfilebase

echo "--------------------------------------------------------------"
echo "mri_auotrecon logfile is $LF"
echo "--------------------------------------------------------------"

echo "mri_autorecon log file" >> $LF
echo $VERSION   >> $LF
echo "$0"     >> $LF
echo "$argv"  >> $LF
$PWDCMD           >> $LF
uname -a      >> $LF
date          >> $LF
which mksubjdirs         >> $LF
which mri_convert        >> $LF
which mri_motion_correct >> $LF

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

if($submit) then
  if(`hostname` != seychelles && `hostname` != seychelles.nmr.mgh.harvard.edu) then
    echo "ERROR: can only submit on seychelles" | tee -a $LF
    exit 1;
  endif
  echo "PBSubmitting process" | tee -a $LF
  set cmd = "mri_autorecon $inputargs -nosubmit"
  set cmd = "$cmd -submitted $$ -logfile $LF -submitpwd $submitpwd"
  echo $cmd | tee -a $LF
  pbsubmit -c "$cmd" | tee -a $LF &
  #$cmd &
  echo " " | tee -a $LF
  echo " " | tee -a $LF
  echo " " | tee -a $LF
  echo "Submitted" | tee -a $LF
  sleep 10
  exit 0;
endif

## Stage 1 Processing ##
if($stage == 0 || $stage == 1) then

  echo "-------------- Stage 1 ---------------------"

  cd $subjectsdatadir
  echo --- subjectsdir  $subjectsdatadir --

  ## Create a new subject directory structure
  set cmd = "mksubjdirs $subjid"
  echo "Creating new subject directory structure" |& tee -a $LF
  $PWDCMD    |& tee -a $LF
  echo $cmd  |& tee -a $LF
  $cmd       |& tee -a $LF
  if($status) then
    echo "ERROR: mksubjdirs failed"
    exit 1;
  endif

  if( ! -e $subjid/mri/orig) then
    echo "ERROR: mksubjdirs failed to create $subjid/mri/orig in $subjectsdatadir"
    exit 1;
  endif

  cd $subjid/mri/orig

  ## Copy/Convert each input to the new directory structure ##
  set inputdirs = ();
  @ ninput = 1;
  foreach i ($inputlist)

    echo "___________________________________________________" |& tee -a $LF
    echo "INFO: $i" |& tee -a $LF
    date |& tee -a $LF

    ## Create a 3-digit directory for the data ##
    set inputdir = `printf %03d $ninput`;
    mkdir -p $inputdir
    set inputdirs = ($inputdirs $inputdir);

    ## Check if it is a COR, then copy it over ##
    set tmp = $i/COR-.info
    if (-e $tmp ) then
      echo "INFO: copying $i to $inputdir" |& tee -a $LF
      cp $i/COR-* $inputdir |& tee -a $LF
      if($status) then
        echo "ERROR: copy failed"  |& tee -a $LF
        exit 1;
      endif
      @ ninput = $ninput + 1;
      continue;
    endif

    ## To get here, it must be a MINC file ##
    set cmd = "mri_convert $i $inputdir" |& tee -a $LF
    echo "INFO: Converting $i to COR" |& tee -a $LF
    $PWDCMD    |& tee -a $LF
    echo $cmd  |& tee -a $LF
    $cmd       |& tee -a $LF
    if($status) then
      echo "ERROR: mri_convert failed"
      exit 1;
    endif
    @ ninput = $ninput + 1;

  end # foreach i ($inputlist)

  #### -----------  Motion Correction --------------------- ###
  echo "_____________________________________________________"|& tee -a $LF
  set cmd = "mri_motion_correct . $inputdirs"
  echo "INFO: Motion Correcting" |& tee -a $LF
  date       |& tee -a $LF
  $PWDCMD        |& tee -a $LF
  echo $cmd  |& tee -a $LF
  $cmd       |& tee -a $LF
  if($status) then
    echo "ERROR: mri_motion_correct failed"
    exit 1;
  endif

  if($subjectsdatadir != $SUBJECTS_DIR) then
    #### -----------  Create Symbolic Link --------------------- ###
    echo "_____________________________________________________"|& tee -a $LF
    set cmd = "ln -s $subjectsdatadir/$subjid $SUBJECTS_DIR/$subjid"
    echo "INFO: Creating symbolic link" |& tee -a $LF
    $PWDCMD  |& tee -a $LF
    $cmd |& tee -a $LF
    if( ! -e $SUBJECTS_DIR/$subjid) then
      echo "ERROR: could not make link "
      echo "  from $subjectsdatadir/$subjid"
      echo "  to    $SUBJECTS_DIR/$subjid"
    endif
  endif

  echo "Segment ------------------------------" |& tee -a $LF
  set cmd = "segment_subject $subjid"
  $PWDCMD |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) then
    echo "ERRRO: $cmd" |& tee -a $LF
    exit 1;
  endif

endif # if($stage == 0 || $stage == 1) then

if($stage == 0 || $stage == 2) then

  echo "------------------ Stage 2 Processing -----------------------"
  if(! -e $SUBJECTS_DIR/$subjid ) then
    echo "ERROR: $SUBJECTS_DIR/$subjid does not exist"
    exit 1;
  endif

  echo "Fix  ------------------------------" |& tee -a $LF
  set cmd = "fix_subject $subjid"
  $PWDCMD |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) then
    echo "ERRRO: $cmd" |& tee -a $LF
    exit 1;
  endif

  echo "Morph  ------------------------------" |& tee -a $LF
  set cmd = "morph_subject $subjid"
  $PWDCMD |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) then
    echo "ERRRO: $cmd" |& tee -a $LF
    exit 1;
  endif

  echo "Make Final Surfaces ------------------------------" |& tee -a $LF
  set cmd = "make_final_surfaces_subject $subjid"
  $PWDCMD |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) then
    echo "ERRRO: $cmd" |& tee -a $LF
    exit 1;
  endif

endif # if($stage == 0 || $stage == 2) then

set EndDate = `date`;

echo ""
echo "_____________________________________________________"|& tee -a $LF
echo "Started at $StartDate" |& tee -a $LF
echo "Ended   at $EndDate"   |& tee -a $LF
echo ""
echo "mri_autorecon completed SUCCESSFULLY" 
echo ""

exit 0;

########---------------------------------####
## PreParse: before there is a log file    ##
pre_parse_args:

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

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

    case "-help"
    case "--help"
      set PrintHelp = 1;
      goto usage_exit;
      breaksw

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

    case "-submitted"
      if ( $#cmdline == 0) goto arg1err;
      set submitted = $cmdline[1]; shift cmdline;
      breaksw

    case "-submitpwd"
      if ( $#cmdline == 0) goto arg1err;
      set submitpwd = $cmdline[1]; shift cmdline;
      breaksw

    case "-submit"
      set submit = 1;
      breaksw

    case "-nosubmit"
      set submit = 0;
      breaksw

    default:
      set inputargs = ($inputargs $flag);
      #shift cmdline;
      breaksw
  endsw

end
goto pre_parse_args_return;
############--------------##################

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

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

    case "-help"
    case "--help"
      set PrintHelp = 1;
      goto usage_exit;
      breaksw

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

    case "-subjectslinkdir"
      if ( $#argv == 0) goto arg1err;
      set subjectslinkdir = $argv[1]; shift;
      setenv SUBJECTS_DIR $subjectsdir
      breaksw

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

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

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

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

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

    # this should have been handeled above, but needed here
    # so that it does not fall to default
    case "-logfile": 
      if ( $#argv == 0) goto arg1err;
      shift;
      breaksw

    case "-stage": 
      if ( $#argv == 0) goto arg1err;
      set stage = $argv[1]; shift;
      if($stage != 0 && $stage != 1 && $stage != 2) then
        echo "ERROR: stage=$stage, must be either 0, 1, or 2" |& tee -a $LF
        exit 1;
      endif
      breaksw

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

    case "-nosubmit":
      set submit = 0;
      breaksw

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

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

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

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

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

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

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

end

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

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

  if ( $#subjid == 0 ) then
     echo "ERROR: no subject id specified"|& tee -a $LF 
     exit 1
  endif

  if($stage == 0 || $stage == 1) then

    if($user != "inverse") then
      echo "ERROR: must be logged in as user inverse in order to run"
      echo "       stage 0 or 1"
      exit 1;
    endif

    if( $#subjectsdatadir == 0 ) then
       echo "ERROR: no subjects data directory specified"|& tee -a $LF 
       exit 1
    endif

    if( $#inputlist == 0 && $#sessdir == 0) then
      echo "ERROR: no inputs specified"|& tee -a $LF 
      exit 1;
    endif

    if( $#inputlist != 0 && $#sessdir != 0) then
      echo "ERROR: cannot specify both -i and -sessdir " |& tee -a $LF 
      exit 1;
    endif

    if( $#inputlist != 0 && $#sessasd != 0) then
      echo "WARNING: -sessasd ignored " |& tee -a $LF 
      exit 1;
    endif

    if( ! -e $subjectsdatadir ) then
      echo "ERROR: $subjectsdatadir does not exist" |& tee -a $LF 
      exit 1;
    endif
    pushd $subjectsdatadir > /dev/null
    set subjectsdatadir = `$PWDCMD`;
    popd > /dev/null

    if( ! -w $subjectsdatadir ) then
      echo "ERROR: $subjectsdir is not writable" |& tee -a $LF 
      exit 1;
    endif

    if( ! -w $SUBJECTS_DIR ) then
      echo "ERROR: $SUBJECTS_DIR is not writable" |& tee -a $LF 
      exit 1;
    endif

    # If the session dir has been specified, go get the input list #
    if($#sessdir != 0 ) then

      # Make sure the session directory exists and is readable #
      if( ! -e $sessdir ) then
        echo "ERROR: $sessdir does not exist" |& tee -a $LF 
        exit 1;
      endif
      if( ! -r $sessdir ) then
        echo "ERROR: $sessdir is not readable" |& tee -a $LF 
        exit 1;
      endif

      # Assign default session anatomical subdir #
      if( $#sessasd == 0 ) set sessasd = 3danat;

      # Make sure the session anatomical dir exists #
      set anatdir = $sessdir/$sessasd
      if( ! -e $anatdir ) then
        echo "ERROR: cannot find $anatdir";
        exit 1;
      endif

      ## Get a list of possible run sub directories ###
      set tmplist = `ls -d $anatdir/???`;
      if( $#tmplist == 0 ) then
        echo "ERROR: cannot find any runs in $anatdir"
        exit 1;
      endif

      ## Go thru each potential run subdir and add to list if OK ##
      set inputlist = ();
      foreach tmp ($tmplist)

        # Check whether it is numeric (eg, 002, not abc) #
        set runstring = `basename $tmp`;
        printf %03d $runstring >& /dev/null
        if($status) continue;
        pushd $tmp > /dev/null

        # Check if there are COR files #
        if( -e COR-.info ) then
          set inputlist = ($inputlist `$PWDCMD`);
          popd > /dev/null
          continue;
        endif

        # Check if there are MINC files #
        mncfile = `ls *.mnc *.mnc.gz`;

        # make sure there are not more than one #
        if( $#mncfile > 1 ) then
          echo "ERROR: mutliple MNC files found in $tmp"
          echo $mncfile
          exit 1;
        endif

        # Check if there are any, and add to list #
        if( $#mncfile != 0 ) then
          set inputlist = ($inputlist `$PWDCMD`/$mncfile);
          popd > /dev/null
          continue;
        endif

        popd > /dev/null

      end  # foreach tmp ($tmplist)

      if( $#inputlist == 0 ) then
        echo "ERROR: could not find any runs in $anatdir"
        exit 1;
      endif

    endif # if($#sessdir != 0 ) then

    # Check that the items in the input list exist #
    foreach i ($inputlist)
      if( ! -e $i ) then
        echo "ERROR: item $i does not exist"
        exit 1;
      endif
    end

    ## Check whether a link already exists in the database #
    if( -e $SUBJECTS_DIR/$subjid ) then
      echo "ERROR: $subjid already exists in $SUBJECTS_DIR" |& tee -a $LF 
      exit 1;
    endif

    ## Check whether hard location for data exists ##
    set SubjectDir = $subjectsdatadir/$subjid
    if( -e $SubjectDir ) then
      echo "ERROR: $subjid already exists in $subjectsdatadir" |& tee -a $LF 
      exit 1;
    endif

  endif  # if($stage != 2) then

  if( $#subjectslinkdir == 0 ) then
    set subjectslinkdir = $SUBJECTS_DIR;
  endif

  ## Check how much disk space is available at this location ##
  set AvailSpace = `df -k $subjectsdatadir | grep % | tail -n 1 | awk '{print $3}'`;
  set NeededSpace = `echo "($#inputlist + 1) * 256 * 256 *256/1024" | bc `;
  echo "Available Space = $AvailSpace"
  echo "Needed Space    = $NeededSpace"
  if($AvailSpace < $NeededSpace) then
    echo "ERROR: not enough space in $subjectsdatadir"
    df -k $subjectsdatadir 
    exit 1;
  endif

  ## Check how much disk space is available in /tmp ##
  set AvailSpace = `df -k /tmp | grep % | tail -n 1 | awk '{print $3}'`;
  set NeededSpace = `echo "2 * 256 * 256 *256/1024" | bc `;
  echo "/tmp: Available Space = $AvailSpace"
  echo "/tmp: Needed Space    = $NeededSpace"
  if($AvailSpace < $NeededSpace) then
    echo "ERROR: not enough space in /tmp"
    df -k /tmp
    exit 1;
  endif

  # This must be done makesubjdirs
  #mkdir -p $SubjectDir
  #if(! -e $SubjectDir ) then
  #  echo "ERROR: could not create $SubjectDir" |& tee -a $LF 
  #  exit 1;
  #endif


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

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

############--------------##################
usage_exit:
  echo "USAGE: mri_autorecon"
  echo "Options:";
  echo "   -stage  stage        : 1, 2 (or 0 for both)"
  echo "   -submit              : submit job to PBS (must be on seychelles)"
  echo "   -subjid subjidstring : subject identifier string"
  echo "   -subjectsdatadir dir : subjects' data directory"
  echo "   -subjectslinkdir dir : subjects' link directory"
  echo "   -i input <-i input>"
  echo "   -sessdir sessiondir"
  echo "   -sessasd anatsubdir"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -version       : print version and exit"
  echo "   -help          : print help and exit"

  if(! $PrintHelp) exit 1;

  echo " "
  echo "$VERSION"
  echo " "
  echo "This script performs the automatic portion of anatomical recontruction."
  echo "This is broken into two stages:"
  echo " Stage 1: "
  echo "   a. Creating the subject's directory structure"
  echo "   b. Copying/Converting input data"
  echo "   c. Motion Correction"
  echo "   d. Creating symbolic link"
  echo " Stage 2: "
  echo "   a. Segmentation"
  echo "   b. Fixing"
  echo "   c. Morphing"
  echo "   d. Making Final Surfaces"

  echo " "
  echo "subjectdatadir: parent directory where actual data will reside"
  echo "subjectlinkdir: parent directory where link to actual data will reside"
  echo "                this will be set to SUBJECTS_DIR by default"
  echo " "
  echo "This script will create subjectdatadir/subjidstring and"
  echo "create a link to that from subjectlinkdir/subjidstring."
  echo " "
  echo "The input(s) can be specified in one of two ways:"
  echo "   a. -i input <-i input2>  where 'input' is either an input"
  echo "      MINC file or COR directory. Use multiple -i for multiple inputs"
  echo "   b. -sessdir sessiondir where sessiondir is the name of the session"
  echo "      directory as unpacked by brose-sessions"
  echo " "

exit 1;
