#!/bin/tcsh -f
# wmedits2surf

set VERSION = 'wmedits2surf 8.2.0';

set subject = ();
set hemilist = (lh rh);
set UseFSA = 1; # target fsaverage, otherwise self
set proj = (--projfrac-max -1 1 .3)
set Overwrite = 0;
set DoSurfs = 1;

set tmpdir = ();
set cleanup = 1;
set LF = ();

set inputargs = ($argv);
set PrintHelp = 0;

if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
endif
set n = `echo $argv | grep -e -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:
goto check_params;
check_params_return:
set StartTime = `date`;
set tSecStart = `date '+%s'`;
set year  = `date +%Y`
set month = `date +%m`
set day   = `date +%d`
set hour   = `date +%H`
set min    = `date +%M`

set outdir = $SUBJECTS_DIR/$subject/surf
if($#tmpdir == 0) then
  set tmpdir = `fs_temp_dir --scratch --base $outdir`
endif
mkdir -p $tmpdir

set sd =  $SUBJECTS_DIR/$subject
set wm = $sd/mri/wm.mgz

# Check whether analysis is needed
if(! $Overwrite) then
  set UpdateNeeded = 0;
  foreach edit (erase fill)
    foreach hemi ($hemilist)
      set fname = $sd/surf/$hemi.wm$edit.mgh
      if($UseFSA) set fname = $sd/surf/$hemi.wm$edit.fsa.mgh
      set UpdateNeeded = `UpdateNeeded $fname $wm`
    end
  end
  if(! $UpdateNeeded) then
    echo "wmedits2surf: update not needed for $subject"
    echo "  run with --overwrite to force reanalysis"
    exit 0;
  endif
endif

# Set up log file
if($#LF == 0) set LF = $outdir/wmedits2surf.log
if($LF != /dev/null) rm -f $LF
echo "Log file for wmedits2surf" >> $LF
date  | tee -a $LF
echo "" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
echo "cd `pwd`"  | tee -a $LF
echo $0 $inputargs | tee -a $LF
echo "" | tee -a $LF
cat $FREESURFER_HOME/build-stamp.txt | tee -a $LF
echo $VERSION | tee -a $LF
uname -a  | tee -a $LF

#========================================================


# Create a binary seg of the erased voxels in the WM
set wmerase = $tmpdir/wm.erase.mgh
set wmecount = $sd/stats/wm.erase.dat
set cmd = (mri_binarize --i $wm --match 1 --o $wmerase --count $wmecount)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) exit 1;

# Map erased voxels to the surface
if($DoSurfs) then
foreach hemi ($hemilist)
  set wmeditsurf = $sd/surf/$hemi.wmerase.mgh
  if($UseFSA) set wmeditsurf = $sd/surf/$hemi.wmerase.fsa.mgh
  set cmd = (mri_vol2surf --regheader $subject --hemi $hemi \
     --mov $wmerase --o $wmeditsurf  --interp nearest $proj)
  if($UseFSA) set cmd = ($cmd --trgsubject fsaverage)
  echo $cmd | tee -a $LF
  $cmd | tee -a $LF
  if($status) exit 1;
  if($UseFSA) then
    # Rebinarize 
    set cmd = (mri_binarize --i $wmeditsurf --min .0001 --o $wmeditsurf)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) exit 1;
  endif
end
endif

# Create a binary seg of the filled voxels in the WM
set wmfill = $tmpdir/wm.fill.mgh
set wmfcount = $sd/stats/wm.fill.dat
set cmd = (mri_binarize --i $wm --match 255 --o $wmfill --count $wmfcount)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) exit 1;

# Map filled voxels to the surface
if($DoSurfs) then
foreach hemi ($hemilist)
  set wmeditsurf = $sd/surf/$hemi.wmfill.mgh
  if($UseFSA) set wmeditsurf = $sd/surf/$hemi.wmfill.fsa.mgh
  set cmd = (mri_vol2surf --regheader $subject --hemi $hemi \
     --mov $wmfill --o $wmeditsurf  --interp nearest $proj)
  if($UseFSA) set cmd = ($cmd --trgsubject fsaverage)
  echo $cmd | tee -a $LF
  $cmd | tee -a $LF
  if($status) exit 1;
  if($UseFSA) then
    # Rebinarize 
    set cmd = (mri_binarize --i $wmeditsurf --min .0001 --o $wmeditsurf)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) exit 1;
  endif
end
endif

#========================================================

# Cleanup
if($cleanup) rm -rf $tmpdir

# Done
echo " " |& tee -a $LF
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %5.2f $tRunHours`
echo "Started at $StartTime " |& tee -a $LF
echo "Ended   at `date`" |& tee -a $LF
echo "Wmedits2surf-Run-Time-Sec $tSecRun" |& tee -a $LF
echo "Wmedits2surf-Run-Time-Hours $tRunHours" |& tee -a $LF
echo " " |& tee -a $LF
echo "wmedits2surf Done" |& tee -a $LF
exit 0

###############################################

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

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

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

    case "--fsaverage":
    case "--fsa":
      set UseFSA = 1;
      breaksw

    case "--self":
    case "--no-fsaverage":
    case "--no-fsa":
      set UseFSA = 0;
      breaksw

    case "--lh":
      set hemilist = (lh)
      breaksw

    case "--rh":
      set hemilist = (rh)
      breaksw

    case "--overwrite":
      set Overwrite = 1;
      breaksw

    case "--no-overwrite":
      set Overwrite = 0;
      breaksw

    case "--no-surfs":
      set DoSurfs = 0;
      breaksw


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

    case "--nolog":
    case "--no-log":
      set LF = /dev/null
      breaksw

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

    case "--nocleanup":
      set cleanup = 0;
      breaksw

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

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

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

end

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

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

if($#subject == 0) then
  echo "ERROR: must spec subject"
  exit 1;
endif
if(! -e $SUBJECTS_DIR/$subject) then
  echo "ERROR: cannot find $subject"
  exit 1;
endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "wmedits2surf --s subject"
  echo " --self : output will be on self instead of fsaverage"
  echo " --overwrite : force overwriting of existing results"
  echo " --tmp tmpdir, --cleanup, --no-cleanup, --debug "
  echo " --lh, --rh : only do one hemi"
  echo " --no-surfs : do not computes surfs, only count stats"
  echo " "
  echo " --help : without it you are helpless"
  echo " "

  if(! $PrintHelp) exit 1;
  echo $VERSION
  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'
exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP

This program computes binary maps of surface locations near where the
wm.mgz has been edited. It creates two files for each hemisphere,
one for each type of edit. These will be

subject/surf/lh.wmerase.fsa.mgh
subject/surf/rh.wmerase.fsa.mgh
subject/surf/lh.wmfill.fsa.mgh
subject/surf/rh.wmfill.fsa.mgh

These are binary masks on fsaverage space. They can be concatenated
together to make maps of the likelyhood that a given spatial location
is affected by a white matter edit.

It will also create 
  subject/stats/wm.erase.dat
  subject/stats/wm.fill.dat
The first number will be the number of voxels cloned/edited

See also bmedits2surf


