#!/bin/sh
# setup_subject: R. Poldrack, 1/6/04
# shell script for creating new subject directories and automatically downloading and converting data
# 7/23/08 - removed func-specific information to create release version
# 4/14/08 - added -D command to allow specification of dicom dir
# 3/28/08 - fixed DIRNAME awk command so that the script now works with subdirs within data dirs - dara
# 2/19/08 - made decision to move from debabeler to mricro's dcm2nii, as the debabeler conversion was not playing 
#           nicely with FSL
# 2/11/08 - added avworient command to get data into FSL's preferred orientation
# 1/30/08 - added code to detect FSL version and change avwutils prefix
# 6/20/07 - added diagnostics code, chagned over to nifti debabeler
# 4/19/07 - changed DICOM_USER test from "! -n" to "-z" mds
# 2/15/07 - added SGE access mds
# 3/9/04 - fixed problems with incomplete specification of copy paths
#        - added existence check for debabeler jar file and for file  directories
#        - tested on Mac OS X
#        - added flags for BOLD tag and for skipping debabeler operation
# 7/28/04 - added options to run motion correction and MELODIC
#         - automatically remove DICOM data
#         - automatically remove 3D data files after 4D conversion
# 8/12/04 - added option to run BET in between mcflirt and melodic steps
#         - added requirement to choose either -r or -n for orientation
#         - moved skipping downloading from -n to -e
# 10/3/05 - changed server info due to BMC changes as of 9/17/05
# 10/3/05 - added processing of mp-rage (alignment, exttraction, and bias correction)

# set various paths here

DEBABELER_JAR_NEURO='/space/raid/fmri/java/SiemensToAnalyze-Func_20Jun2007.jar'
DEBABELER_JAR_RADIO='/space/raid/fmri/java/SiemensToAnalyze-Func_LR_20Jun2007.jar'
DEBABELER_JAR_NIFTI='/space/raid/fmri/java/SiemensToNifti-Func_21Jun2007.jar'

DCMNII_CONVERTER='/space/raid/fmri/mricron/mricronlx2/dcm2nii'

SGE_SETTINGS='/space/raid/linux/sge-root/FUNC_Grid/common/settings.sh'
FSLD_RAW_FILE='/space/raid/fmri/fsld/fsld_raw.R'

#R_BIN='R-2.5.0'
R_BIN='R'

FSLVERSION=`which fsl | awk -F - '{print $2}'|awk -F . '{print $1}'`
echo "FSL Version: ${FSLVERSION}"
if [ $FSLVERSION -ge 4 ]
then
    FSLUTILPREFIX='fsl'
else
    FSLUTILPREFIX='avw'
fi

echo "util prefix: ${FSLUTILPREFIX}"

FSL_UTIL_PREFIX=
# server changes as of 10/05
DICOM_SERVER="dns0.bmap.ucla.edu"
BASE_DICOM_DIR="/Volumes/BMC1/dicom"
#BASE_DICOM_DIR="/Volumes/BMC0/BMCusers/poldrack/dicom"
DATE="`date +%d%b%Y`"
TIME="`date +%H-%M`"

MCFLIRT_ARGS="-plots -report"
MELODIC_ARGS="--report"

USAGE="
USAGE: setup_subject_nifti -b <base_dir> -g <group> -s <subject> 
Create Nifti files
Reuired arguments:
  -b base_dir: the project directory in which the subject's 
               dir will be created
               (this MUST be an absolute path, i.e., starting with /)
  -g group:    the name of the group under which the scan was performed 
               (this MUST be in lowercase, and must also match the 
               account name under which the data are stored on DNS0)
  -s subject:  the subject code that was entered when scanning

Optional arguments:
[general flags]:
  -t:          run in test mode - don't execute commands    
[processing operations]:
  -c:          run MCLFIRT motion correction on 4D image
  -m:          run MELODIC ICA on motion-corrected 4D image
  -x:          run BET on the motion-corrected 4D data
  -w:          Preprocess MP-RAGE (align, BET, and bias correction)
  -D:          Run raw data diagnostics
  -z:          name of file specifying definitions for MCFLIRT_ARGS and MELODIC_ARGS
  -h:          unwarp allegra MP-RAGE using MGH code
[debabeler options]:
  -d:          skip debabeling
  -j:          location of debabeler .jar file
[data input options]:
  -u username  specify a username for dns0 account (defaults to group name)
  -y:          read data from dicom backup (for data collected prior to 9/17/05)
[file output options]:
  -k:          don't automatically delete DICOM data after conversion
  -3:          Keep 3D data after 4D conversion
  -f:          don't fix raw directory names (leave extra numbers)
  -e:          skip downloading of data from dns0 (assumes existing data)
  -a:          tag to denote BOLD directories (defaults to BOLD)
  -q           skip entry of DICOM info into database
  -I	       specify a dicom server directory
[grid options]:
  -G           submit compute tasks to the Grid (default)
  -L           run Locally (do not submit compute tasks to the Grid)
see www.func.ucla.edu for more info

"



if [ $# -eq 0 ]
then
  echo "$USAGE"
  exit
fi

TESTMODE=0
NOSCP=0
NODEBABELER=0
FIXDIRNAMES=1
RUN_MCFLIRT=0
RUN_MELODIC=0
RUN_BET=0
UNWARP_MPRAGE=0
DELETE_DICOM=1
DB_DOWNLOAD=1
DELETE_3D=1
FSLCONVERT=1  # create 4D analyze by default
BOLDTAG='BOLD'
MPRAGE_TAG='MPRAGE'
FSL_OPT_FILE=""
USE_DICOM_BACKUP=0
PROCESS_ANAT=0
SGE_RESUBMIT=-1
R_DIAGNOSTICS=0

DEFAULT_FILETYPE='NIFTI_GZ'
FSLOUTPUTTYPE=$DEFAULT_FILETYPE
echo "using FSL Output Type: ${FSLOUTPUTTYPE}"
IMG_SUFFIX='.nii.gz'
echo "using $IMG_SUFFIX as output file type"

# set up arguments here
while getopts b:g:s:u:a:j:z:I:tqcekhxywmdfi3GLD o 
do  case "$o" in
   b)    BASEDIR="$OPTARG";;
   a)    BOLDTAG="$OPTARG";;
   g)    USERNAME="$OPTARG";;
   s)    SUBCODE="$OPTARG";;
   t)    TESTMODE=1;;
   e)    NOSCP=1;;
   d)    NODEBABELER=1;;
   q)    DB_DOWNLOAD=0;;
   j)    DEBABELER_JAR="$OPTARG";;
   f)    FIXDIRNAMES=0;;
   u)    DICOM_USER="$OPTARG";;
   c)    RUN_MCFLIRT=1;FSLCONVERT=1;;
   x)    RUN_BET=1;FSLCONVERT=1;;
   m)    RUN_MELODIC=1;FSLCONVERT=1;;
   k)    DELETE_DICOM=0;;
   3)    DELETE_3D=0;;
   z)    FSL_OPT_FILE="$OPTARG";;
   w)    PROCESS_ANAT=1;;
   h)    UNWARP_MPRAGE=1;;
   y)    USE_DICOM_BACKUP=1;;
   i)    IMG_SUFFIX="$OPTARG";;
   G)    SGE_RESUBMIT=1;;
   D)    R_DIAGNOSTICS=1;;
   I)    BASE_DICOM_DIR="$OPTARG";;
   L)    unset SGE_RESUBMIT;;
   [?])  print >&2 "$USAGE"
         exit 1;;
 esac
done
#shift $OPTIND-1

echo "FSLCONVERT = $FSLCONVERT"

if [ $SGE_RESUBMIT ]
then
 if [ -r $SGE_SETTINGS ]
 then
   SGE_RESUBMIT=1
 else
  if [ $SGE_RESUBMIT -eq 1 ]
  then
   echo "Grid use requested but not available.  Re-run without -G option."
   exit
  else
   unset SGE_RESUBMIT
  fi
 fi
fi

if [ $UNWARP_MPRAGE -eq 1 ]
then
  PROCESS_ANAT=1
fi

#BASEDIR=$1
#SUBCODE=$3
#SUBDIR=$1/$3
SUBDIR="${BASEDIR}/$SUBCODE"
DICOMGROUP=`echo "$USERNAME"|sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'`

if [ $USE_DICOM_BACKUP -eq 1 ]
then
  BASE_DICOM_DIR="${BASE_DICOM_DIR}/DICOM_BACKUP_B"
  echo "using backup DICOM dir: ${BASE_DICOM_DIR}"
fi

# read in FSL options from specified file
if [ $FSL_OPT_FILE ]
then
  echo "reading FSL options from $FSL_OPT_FILE..."
  source $FSL_OPT_FILE
fi

# choose appropriate jar file

#if [ -z $RADIOLOGICAL_CONVENTION ]
#then
#  echo "ERROR: You must set orientation with either -r or -n"
#  exit
#fi

#if [ $RADIOLOGICAL_CONVENTION -eq 0 ]
#then
#   DEBABELER_JAR=$DEBABELER_JAR_NEURO
#else
#   DEBABELER_JAR=$DEBABELER_JAR_RADIO
#fi

DEBABELER_JAR=$DEBABELER_JAR_NIFTI

# test for existence of debabeler jar file
if [ ! -f $DEBABELER_JAR ]
then
   echo "Debabeler jar file ($DEBABELER_JAR) does not exist!"
   exit
fi

# set up the log file (unless we are running on the grid)
if [ ! $SGE_TASK_ID ]
then
  LOGFILE="${SUBDIR}/notes/setup_log.${DATE}_${TIME}"
  echo "
  Logging command output to:
  $LOGFILE
"
else
  LOGFILE="/dev/null"
  unset SGE_RESUBMIT
  echo -e "\nexecuting on grid node "`hostname`":" `date` "\n"
fi

if [ -z $DICOM_USER ]
then
  echo "setting dicom user to $USERNAME
"
  DICOM_USER=$USERNAME
fi

echo "Setting up directory structure in $SUBDIR"
echo "Making directories..."

# first check to make sure that it's not root

if [ $SUBDIR == '/' ]
then
  echo "SUBDIR cannot be /! exiting..."
  exit
fi

DIRLIST=""
if [ -d $SUBDIR ]
then
  echo "$SUBDIR already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR"
  mkdir $SUBDIR
fi

if [ -d $SUBDIR/dicom ]
then
  echo "$SUBDIR/dicom already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR/dicom" 
  mkdir $SUBDIR/dicom
fi

if [ -d $SUBDIR/raw ]
then
  echo "$SUBDIR/raw already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR/raw"
  mkdir $SUBDIR/raw
fi

if [ -d $SUBDIR/behav ]
then
  echo "$SUBDIR/behav already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR/behav"
  mkdir $SUBDIR/behav
fi

if [ -d $SUBDIR/analysis ]
then
  echo "$SUBDIR/analysis already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR/analysis"
  mkdir $SUBDIR/analysis
fi

if [ -d $SUBDIR/notes ]
then
  echo "$SUBDIR/notes already exists"
else
  DIRLIST="$DIRLIST
Making $SUBDIR/notes"
  mkdir $SUBDIR/notes
fi

# echo some info to the log file

echo "$0 $*
"  > $LOGFILE
echo "BASEDIR: $BASEDIR" >> $LOGFILE
echo "USERNAME: $USERNAME" >> $LOGFILE
echo "SUBCODE: $SUBCODE" >> $LOGFILE
echo "SUBDIR: $SUBDIR" >> $LOGFILE
echo "DICOMGROUP: $DICOMGROUP" >> $LOGFILE
echo "TESTMODE: $TESTMODE" >> $LOGFILE
echo "NOSCP: $NOSCP" >> $LOGFILE
echo "NODEBABELER: $NODEBABELER" >> $LOGFILE
echo "DICOM_USER: $DICOM_USER" >> $LOGFILE
echo "BOLDTAG: $BOLDTAG" >> $LOGFILE
echo "MPRAGE_TAG: $MPRAGE_TAG" >> $LOGFILE
echo "$DIRLIST
">> $LOGFILE



# download data from DNS0
if [ ! -d $SUBDIR/dicom ]
then
  echo "$SUBDIR/dicom does not exist! exiting..."
  exit
fi


if [ $TESTMODE -eq 0 ]
then
  cd $SUBDIR/dicom
fi

if [ $TESTMODE -eq 0 -a $NOSCP -eq 0 ]
then
  echo ""
  echo "copying data from dns0.bmap.ucla.edu using scp..."

# echo "user: ${DICOM_USER}"
# echo "dicomserv: {DICOM_SERVER}"
# echo "base: ${BASE_DICOM_DIR}"
# echo "dicomgroup: ${DICOMGROUP}"
# echo "subcode: $SUBCODE"

  echo "scp -qr ${DICOM_USER}@${DICOM_SERVER}:${BASE_DICOM_DIR}/${DICOMGROUP}GROUP/$SUBCODE $SUBDIR/dicom" >> $LOGFILE
  scp -qr ${DICOM_USER}@${DICOM_SERVER}:${BASE_DICOM_DIR}/${DICOMGROUP}GROUP/$SUBCODE $SUBDIR/dicom
fi

# check here to make sure that something was downloaded
# we only need them if we are going to be debabeling

if [ $TESTMODE -eq 0 -a $NODEBABELER -eq 0 ]
then
  DATALIST=`ls $SUBDIR/dicom`
  if [ -z $DATALIST ]
  then
    echo "error downloading DICOM files from $DICOM_SERVER - aborting!"
    exit 1
  fi
fi

# download data to database

if [ $TESTMODE -eq 0 -a $DB_DOWNLOAD -eq 1 ]
then
    echo "downloading to databse..."
    dicom_to_sql.py  $SUBDIR/dicom
    # for poldracklab data, add to wiki
    if [ $USERNAME == "poldrack" ]
    then
	echo "creating wiki page for subject..."
	echo "create_wiki_page.py $SUBCODE $SUBDIR $LOGFILE" >> $LOGFILE
	create_wiki_page.py $SUBCODE $SUBDIR $LOGFILE >> $LOGFILE
    fi
fi

# from here, resubmit to the SGE
if [ $SGE_RESUBMIT ]
then
  echo "submitting compute tasks to the FUNC Grid"
  echo "submitting compute tasks to the FUNC Grid" >> $LOGFILE
  . $SGE_SETTINGS
  n=`whoami`.`echo $LOGFILE | awk -F / '{print $NF}'`
  c="$0 "$*" -eq"
  qs=`qsub -cwd -j y -o $LOGFILE -N $n -r no -b y sh $c`
  echo -e "$qs\n"`date`"\n" | tee -a $LOGFILE
  echo "watch $LOGFILE for progress"
  jn=`echo $qs | awk '{print $3}'`
  echo $jn `date` $n $c >> /space/raid/linux/sgework/quickrecord
  exit
fi

# use debabeler to convert dicom to $IMG_SUFFIX

if [ ! -d $SUBDIR/raw ]
then
  echo "$SUBDIR/raw does not exist! exiting..."
  exit
fi

if [ $TESTMODE -eq 0 ]
then
  cd $SUBDIR/raw
  echo "debabeling..."
fi

if [ $TESTMODE -eq 0 -a $NODEBABELER -eq 0 ]
then
  echo ""
  echo "Converting DICOM to analyze using dcm2nii..."

  #  use dcm2nii to convert entire dicom dir into raw


  # NB: This is probably a fairly fragile method for finding the dicom directories.  
  # it assumes that the depth of the dicom directory tree structure will never change

  DICOMDIRS=`find $SUBDIR/dicom -mindepth 5 -type d`
  #echo "DICOMDIRS: $DICOMDIRS"

  for i in $DICOMDIRS
  do
 
      #DIRNAME=`echo $i | awk -F'/' '{print $13}'`
      DIRNAME=`echo $i | awk -F'/' '{print $NF}'` # sets DIRNAME to the last work in the path (accounts for subdirs within data dirs)
      mkdir $SUBDIR/raw/$DIRNAME
      echo "processing dicom files in $i into $SUBDIR/raw/$DIRNAME"
      echo "Using command:"
      echo " $DCMNII_CONVERTER -d N -o $SUBDIR/raw/$DIRNAME $i"
      $DCMNII_CONVERTER -d N -o $SUBDIR/raw/$DIRNAME $i 
      # rename files
      cd $SUBDIR/raw/$DIRNAME
      FILELIST=`ls | grep $IMG_SUFFIX`
      for f in $FILELIST
      do
	  echo "renaming $f to ${DIRNAME}${IMG_SUFFIX}"
	  mv $f ${DIRNAME}${IMG_SUFFIX}
      done
  done
  echo "DICOM conversion finished: `date`"
  
fi

# move MP-RAGE dicom to raw so they don't get deleted
if [ $TESTMODE -eq 0 ]
then
    DICOMDIR="$SUBDIR/dicom"
    MPRAGE_DICOMDIR=`find $DICOMDIR -name "MPRAGE*"`

    MPRAGE_RAWDIRS=`find ${SUBDIR}/raw -maxdepth 1 -name "MPRage*"`
    for m in $MPRAGE_RAWDIRS
    do
        if [ -d $m ]
        then
	    s=`echo $m | awk -F"MPRage" '{print $2}' | awk -F"_" '{print $3}' | sed 's/0//g'`
	    cd $m
	    dcmdir=`find ${SUBDIR}/dicom -name "MPRAGE*$s"`
	    echo "copying MP-Rage DICOM files for series $s from $dcmdir to $m"
	    mkdir dicom
	    cp $dcmdir/* dicom
        fi
    done

fi


# delete DICOM data after conversion

if [ $TESTMODE -eq 0 -a $DELETE_DICOM -eq 1  -a $NODEBABELER -eq 0 ]
then
    DICOMDIR="$SUBDIR/dicom"
    if [ $DICOMDIR -a -d $DICOMDIR -a ! $DICOMDIR == '/' ]
    then
	echo "deleting DICOM files in $DICOMDIR..."
	rm -rf $DICOMDIR
    fi
fi

# fix raw directory names
# don't need this anymore

if [ 0 -eq 1 -a $FIXDIRNAMES -eq 1 -a $TESTMODE -eq 0 -a $NODEBABELER -eq 0 ]
then
  echo "fixing dir names..."
  cd $SUBDIR/raw
  BOLDDIRS=`ls -1 | grep $BOLDTAG`

  for i in $BOLDDIRS
  do
    NEWDIRNAME=`echo "$i" | awk -F"__" '{ print $1 "_" $2 }'`
    if [ -d "$SUBDIR/raw/$i" -a ! -d "$SUBDIR/raw/$NEWDIRNAME" ]
    then
       mv $SUBDIR/raw/$i $SUBDIR/raw/$NEWDIRNAME
       echo "mv $SUBDIR/raw/$i $SUBDIR/raw/$NEWDIRNAME" >> $LOGFILE
    fi
  done
fi

# create 4D analyze files
# don't need to do this anymore
if [ 1 -eq 0 -a $FSLCONVERT -eq 1  -a $TESTMODE -eq 0 -a $NODEBABELER -eq 0 ]
then
  cd $SUBDIR/raw
  BOLDDIRS=`ls -1 | grep $BOLDTAG`
  echo "making 4D $IMG_SUFFIX files..."

  for i in $BOLDDIRS
  do
    cd $SUBDIR/raw/$i
    BOLDSERIES=`ls S*_I0001.nii|awk -F"_" '{ print $1 }'`
    NEWFILENAME="${BOLDSERIES}_4D"
    ${FSLUTILPREFIX}merge -t $NEWFILENAME ${BOLDSERIES}_*.nii
    echo "${FSLUTILPREFIX}merge -t $NEWFILENAME ${BOLDSERIES}_*.nii" >> $LOGFILE

    # I don't like doing this, but we have to use fslswapdim/fslorient to get the nifti
    # images to have the same orientation as the canonical FSL space (R-L, P-A, I-S)
    # since the nifti debabeler gives them a different orientation and Scott Neu didn't want
    # to muck with it

 #   ${FSLUTILPREFIX}swapdim $NEWFILENAME -x -y z $NEWFILENAME
 #   echo "${FSLUTILITIES}swapdim x -y z $NEWFILENAME" >> $LOGFILE
 #   ${FSLUTILPREFIX}orient -swaporient $NEWFILENAME
 #   echo "${FSLUTILITIES}orient -swaporient $NEWFILENAME" >> $LOGFILE

    if [ $DELETE_3D -eq 1 ]
    then
        echo "deleting 3D $IMG_SUFFIX files for series $BOLDSERIES..."
	rm ${BOLDSERIES}_I[0-9]*
    fi
  done
fi


# run mcflirt
if [ $FSLCONVERT -eq 1 -a $RUN_MCFLIRT -eq 1  -a $TESTMODE -eq 0 ]
then
  echo "running mcflirt on bold dirs..."
  cd $SUBDIR/raw
  BOLDDIRS=`ls -1 | grep $BOLDTAG`
  for i in $BOLDDIRS
  do
    cd $SUBDIR/raw/$i
    FOUR_D_FILENAME=`ls ${BOLDTAG}*$IMG_SUFFIX`
    mcflirt -in $FOUR_D_FILENAME $MCFLIRT_ARGS
    echo "mcflirt -in $FOUR_D_FILENAME $MCFLIRT_ARGS" >> $LOGFILE

  done
fi

# run betfunc2 - this version creates additional diagnostic files
if [ $FSLCONVERT -eq 1 -a $RUN_BET -eq 1  -a $TESTMODE -eq 0 ]
then
  echo "running BET on bold dirs..."
  cd $SUBDIR/raw
  BOLDDIRS=`ls -1 | grep $BOLDTAG`
  for i in $BOLDDIRS
  do
    cd $SUBDIR/raw/$i
    MCF_FILENAME=`ls ${BOLDTAG}*_mcf$IMG_SUFFIX`
    if [ ! -s $MCF_FILENAME ]
    then
      echo "$MCF_FILENAME does not exist, trying original file"
      MCF_FILENAME=`ls $BOLDTAG}*$IMG_SUFFIX`
    fi
    # remove file extension since BET wants stems only
    MCF_FILENAME=`echo "${MCF_FILENAME}" | sed " s/$IMG_SUFFIX// "`    
    BET_FILENAME="${MCF_FILENAME}_brain"
    betfunc2 $MCF_FILENAME  
    echo "betfunc2 $BET_ARGS  $MCF_FILENAME  $BET_FILENAME" >> $LOGFILE
  done
fi



if [ $FSLCONVERT -eq 1 -a $RUN_MELODIC -eq 1  -a $TESTMODE -eq 0 ]
then
  echo "running MELODIC on bold dirs..."
  for i in $BOLDDIRS
  do
    cd $SUBDIR/raw/$i
    MCF_FILENAME=`ls ${BOLDTAG}*_mcf_brain$IMG_SUFFIX`
    if [ ! -s $MCF_FILENAME ]
    then
      echo "$MCF_FILENAME does not exist, trying mcf file"
      MCF_FILENAME=`ls ${BOLDTAG}*_mcf$IMG_SUFFIX`
    fi
    if [ ! -s $MCF_FILENAME ]
    then
      echo "$MCF_FILENAME does not exist, trying original 4D file"
      MCF_FILENAME=`ls ${BOLDTAG}*$IMG_SUFFIX`
    fi
    melodic $MELODIC_ARGS  -i $MCF_FILENAME
    echo "melodic  $MELODIC_ARGS  -i $MCF_FILENAME" >> $LOGFILE
  done
fi

if [ $R_DIAGNOSTICS -eq 1 -a  $TESTMODE -eq 0 ]
then
  echo "running R diagnostics ..."
   cd $SUBDIR/raw
   BOLDDIRS=`ls -1 | grep $BOLDTAG`
  for i in $BOLDDIRS
  do
    cd $SUBDIR/raw/$i
    MCF_FILENAME=`ls ${BOLDTAG}*_mcf.nii.gz`
 
    if [ ! -s $MCF_FILENAME ]
    then
      echo "$MCF_FILENAME does not exist, skipping this run"
      continue
    fi

    echo "source('${FSLD_RAW_FILE}');fsld_raw('${MCF_FILENAME}')" | $R_BIN --no-save
    echo "source('${FSLD_RAW_FILE}');fsld_raw('${MCF_FILENAME}')" >> $LOGFILE
    gzip *nii
  done
  

fi

# fix orientation on MP-RAGE

if [ $TESTMODE -eq 0 ]
then
  echo "changing orientation on MP-RAGE..."
  cd $SUBDIR/raw
  ANATDIRS=`ls -1 | grep $MPRAGE_TAG`
  for i in $ANATDIRS
  do
    echo "processing $i"
    cd $SUBDIR/raw/$i
    MPRAGE_FILE=`ls -1 | grep MPRAGE`
    echo "fslswapdim $MPRAGE_FILE -z -x y mprage"
    fslswapdim $MPRAGE_FILE -z -x y mprage
    echo "NOTE: orientation was swapped on mprage.nii.gz using:" > README.orientation
    echo "fslswapdim $MPRAGE_FILE -z -x y mprage">>README.orientation
  done
fi


if [ $PROCESS_ANAT -eq 1 -a $TESTMODE -eq 0 ]
then
  echo "processing MP-RAGE..."
  cd $SUBDIR/raw
  ANATDIRS=`ls -1 | grep $MPRAGE_TAG`

  # RP - deal with case where freesurfer environment has not been set up
  if [ ! $FREESURFER_HOME ]
  then
    FREESURFER_HOME=/space/raid/fmri/freesurfer
    source $FREESURFER_HOME/FreeSurferEnv.sh
  fi

  for i in $ANATDIRS
  do
    echo "processing $i"

    cd $SUBDIR/raw/$i    
    
    if [ $UNWARP_MPRAGE -eq 1 ]
    then
       dcmdir=$SUBDIR/raw/$i/dicom
       if [ -d $dcmdir ]
       then
	  SERIESNUM=`dcmdump $dcmdir/1 | grep SeriesNumber | awk '{print $3}' | sed 's/\]//' | sed 's/\[//'` 
	  echo "unwarping MP-RAGE (series ${SERIESNUM}) in $dcmdir"
	  unwarp_allegra -i $dcmdir -s $SERIESNUM -o mprage_unwarped > unwarp_output
       fi
       ANATVOL=$SUBDIR/raw/$i/mprage_unwarped
       # go ahead and rename original mprage
       anatimg=`ls 0*.img`
       mv $anatimg mprage.img
       anatimg=`ls 0*.hdr`
       mv $anatimg mprage.hdr
    else
       anatimg=`ls 0*.img`
       mv $anatimg mprage.img
       anatimg=`ls 0*.hdr`
       mv $anatimg mprage.hdr
       ANATVOL=$SUBDIR/raw/$i/mprage
    fi
 
    # run BET
    COMMAND="bet $ANATVOL ${ANATVOL}_bet -f 0.5 -g 0"   
    echo $COMMAND
    echo $COMMAND >> $LOGFILE
    $COMMAND
    
   done
fi

# note completion time
echo -e "\ncommand complete:" `date` | tee -a $LOGFILE

#fi
