#! /bin/csh -f

#
# sphsmooth-sess - smooths selxavg output that has been resampled
# to the icosahedron.
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:18 $
#    $Revision: 1.4 $
#
# 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: sphsmooth-sess,v 1.4 2007/01/09 22:41:18 nicks Exp $'

set inputargs = ($argv);

set analysis    = ();
set hemi = ();
set insphdir  = sph;
set outsphdir = ();
set smoothsteps = ();
set PrintHelp = 0;
set nolog = 0;

if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

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

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

set SessList = `getsesspath $inputargs`;
if($status || $#SessList == 0) then
  echo "ERROR: finding sessions" 
  echo "       $SessList" 
  exit 1;
endif

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

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

echo "sphsmooth-sess log file" >> $LF
echo $VERSION >> $LF
id            >> $LF
pwd           >> $LF
echo "$0"     >> $LF
echo $inputargs  >> $LF
uname -a      >> $LF
date          >> $LF
which isxavg-fe >> $LF

## Get functional subdirectory from the info file ##
set infofile = $analysis/analysis.info
if(! -e $infofile) then
  echo "ERROR: cannot find $infofile" |& tee -a $LF
  exit 1;
endif
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

#---------------------------------------------------------------------#
foreach hs ($hemi)

  echo "$hemi hemisphere" |& tee -a $LF
  date |& tee -a $LF

  ### Go through each session ###
  @ sessno = 1;
  foreach sess ($SessList)

    set inputdir = $sess/$fsd/$analysis/$insphdir;
    if(! -d $inputdir) then
      echo "ERROR: $sess/$fsd/$analysis/$insphdir does not exist" |& tee -a $LF
      exit 1;
    endif
    set instem = $inputdir/h-$hs
    set inoffsetstem = $instem-offset;
    set indat = $instem.dat

    if(! -e $indat ) then
      echo "ERROR: cannot find $indat" |& tee -a $LF
      exit 1;
    endif
    set i0 = $instem"_000.bfloat";
    if(! -e $i0 ) then
      echo "ERROR: cannot find $i0" |& tee -a $LF
      exit 1;
    endif
    set i0 = $instem"_000.hdr";
    if(! -e $i0 ) then
      echo "ERROR: cannot find $i0" |& tee -a $LF
      exit 1;
    endif

    # Compute the number of vertices #
    set tmp = `getbfvdim $instem`;
    set nvertices = `echo $tmp | awk '{print $1*$2*$3}'`;
    echo "nvertices = $nvertices" |& tee -a $LF

    # Compute the icosahedron order from the number of vertices #
    set icoorder = `geticoorder $nvertices`;
    if($icoorder == -1) then
      echo "ERROR: could not compute ico order" |& tee -a $LF
      exit 1;
    endif
    echo "Ico Order = $icoorder" |& tee -a $LF

    set outputdir = $sess/$fsd/$analysis/$outsphdir;
    set outstem = $outputdir/h-$hs
    set outoffsetstem = $outstem-offset;
    set outdat = $outstem.dat
    mkdir -p $outputdir

    #-- Selxavg Output ----------------------------------------#
    set cmd = (mri_surf2surf);
    set cmd = ($cmd --srcsubject ico --srcsurfval $instem.bhdr);
    set cmd = ($cmd --trgsubject ico --trgsurfval $outstem.bhdr);
    set cmd = ($cmd --trgicoorder $icoorder  --hemi $hs )
    set cmd = ($cmd --nsmooth $smoothsteps);
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      pwd |& tee -a $LF
      exit 1;
    endif

    #-- Mean T2 values -----------------------------------------#
    set cmd = (mri_surf2surf);
    set cmd = ($cmd --srcsubject ico --srcsurfval $inoffsetstem.bhdr);
    set cmd = ($cmd --trgsubject ico --trgsurfval $outoffsetstem.bhdr);
    set cmd = ($cmd --trgicoorder $icoorder  --hemi $hs )
    set cmd = ($cmd --nsmooth $smoothsteps);
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      pwd |& tee -a $LF
      exit 1;
    endif

    #--------------------------------------------------------#
    cp $indat $outdat

    @ sessno = $sessno + 1;
  end # loop over SessList #

end # loop over hemisphere

echo "-----------------------------------------------------"| tee -a $LF

date | tee -a $LF
echo "sphsmooth-sess completed SUCCESSFULLY" | tee -a $LF
echo " "
echo " "

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

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

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

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

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

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

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

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

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

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

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

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

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

    case "-cwd":
      breaksw

    case "-g":
    case "-s":
    case "-sf":
    case "-df":
    case "-d":
      # ignore getsesspath arguments 
      shift;
      breaksw

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

end

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

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

  set errs = 0;

  if($#SessList == 0) then
     echo "ERROR: no sessions specified"
     set errs = 1;
  endif

  if ($#analysis == 0) then
     echo "ERROR: no analysis specified"
     set errs = 1;
  endif

  if ($#insphdir == 0) then
     echo "ERROR: must specify an input sph directory name "
     set errs = 1;
  endif

  if ($#outsphdir == 0) then
     echo "ERROR: must specify an output sph directory name "
     set errs = 1;
  endif

  if($#smoothsteps == 0) then
     echo "ERROR: must specify the amount of smoothing"
     set errs = 1;
  endif

  if($smoothsteps < 1) then
    echo "ERROR: must smoothing steps = $smoothsteps, must be >= 1"
    set errs = 1;
  endif

  if($#hemi == 0) set hemi = (lh rh);
  foreach hs ($hemi)
    if($hs != lh && $hs != rh) then
      echo "ERROR: hemi must be either lh or rh ($hs)";
      set errs = 1;
    endif
  end

  if($errs) exit 1;

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

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

############--------------##################
usage_exit:
  echo "USAGE: sphsmooth-sess"
  echo ""
  echo "Options:";
  echo "   -smoothsteps  n        : number of smoothing steps"
  echo "   -analysis analysisname : session-level functional analysis name"
  echo "   -insphdir  dirname    : input  spherical space directory name <sph>"
  echo "   -outsphdir dirname    : output spherical space directory name"
  echo "   -hemi     hemisphere   : <lh rh>";
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -nolog         : do not create a log file"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -version       : print version and exit"
  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 will smooth an analysis on the surface. The results of
the analysis must have been resampled onto the sphere using
func2sph-sess.  By default, the input directory will be sph (as
created buy func2sph-sess). The user must supply the output
directory. To access the smoothed data in subsequent calls (eg,
isxavg-re-sess or isxavg-fe-sess), add -spacedir followed by the name
given to the output directory.

The amount of smoothing is controlled by the number of smoothing steps
(-smoothsteps). A single smoothing step is when each vertex is
averaged with its neighbors. This will be performed iteratively as
many times as specified. This is ROUGHLY equivalent to a gassian
kernel with StdDev of nsmooth/(pi/2). The FWHM = 2.35*StdDev. The
StdDev and FWHM are in mm. I emphasize that this is a rough
equivalence; the actual StdDev will probably be a little more.





