#!/bin/sh
#
# Christian Gaser - christian.gaser@uni-jena.de
# Department of Psychiatry
# University of Jena
#
# Copyright Christian Gaser, University of Jena.
# $Id$
#

########################################################
# global parameters
########################################################

measure=thickness
output_dir="."
reg=sphere.reg
template=$FREESURFER_HOME/subjects/fsaverage
fwhm=0
ascii=0
noclobber=0
hemi="lh rh"
gifti=0
label=""

########################################################
# run main
########################################################

main ()
{
  check_tools
  parse_args ${1+"$@"}
  preprocess

  exit 0
}


########################################################
# Resample
########################################################
preprocess ()
{

  if [ ! -d "$output_dir" ]; then
    echo Create directory ${output_dir}.
    mkdir -p $output_dir
  fi
  
  if [ -n "$ARGV_list" ]
  then
    for subject in $ARGV_list
    do

      surfdir=${subject}/surf
      targetdir=${template}/surf
      for name in $surfdir $targetdir; do
        if [ ! -d "$name" ]; then
          echo Directory $name not found.
          break
        fi
      done

      subject_name=`basename $subject`
      tmp_name=/tmp/$$_resample

      for i in $hemi; do
        if [ ! "$fwhm" == 0 ]; then
        
          name=${output_dir}/${fwhm}mm.${measure}.${i}.resample.${subject_name}
          if [ "$ascii" == 1 ]; then
            name=${name}.txt
          fi
        
          if [ -f "${name}" ] && [ "$noclobber" == 1 ]; then
            echo $name will be not overwritten. Do not use -noclobber if you want to overwrite it.
          else
            for files in ${surfdir}/${i}.smoothwm ${surfdir}/${i}.${reg} ${targetdir}/${i}.sphere; do
              if [ ! -f "$files" ]; then
                echo File $files not found.
                break
              fi
            done
            CAT_SurfResampleSpherical ${label} ${surfdir}/${i}.smoothwm ${surfdir}/${i}.${reg} ${targetdir}/${i}.sphere $tmp_name ${surfdir}/${i}.${measure} ${tmp_name}.txt
            CAT_SurfSmooth $tmp_name $name $fwhm ${tmp_name}.txt
            if [ "$gifti" == 1 ]; then
              CAT_AddValuesToSurf $tmp_name $name ${name}.gii
              echo resample and smooth to ${name}.gii          
              rm $name
            else 
              echo resample and smooth to $name 
            fi         
          fi
        
        else
          name=${output_dir}/${measure}.${i}.resample.${subject}
          if [ "$ascii" == 1 ]; then
            name=${name}.txt
          fi
        
          if [ -f "${name}" ] && [ "$noclobber" == 1 ]; then
            echo $name will be not overwritten. Do not use -noclobber if you want to overwrite it.
          else
            for files in ${surfdir}/${i}.smoothwm ${surfdir}/${i}.${reg} ${targetdir}/${i}.sphere; do
              if [ ! -f "$files" ]; then
                echo File $files not found.
                break
              fi
            done
            CAT_SurfResample ${label} ${surfdir}/${i}.smoothwm ${surfdir}/${i}.${reg} ${targetdir}/${i}.sphere $tmp_name ${surfdir}/${i}.${measure} $name
            if [ "$gifti" == 1 ]; then
              CAT_AddValuesToSurf $tmp_name $name ${name}.gii
              echo resample to ${name}.gii          
              rm $name
            else
              echo resample to $name          
            fi
          fi
        
        fi
      done
      if [ -f ${tmp_name}.txt ]; then
        rm ${tmp_name}*
      fi
    done
  else
    echo "No arguments given."
    echo
    usage
    echo "Use the --help option for more information."
    exit 1
  fi

}


########################################################
# check arguments and files
########################################################

parse_args ()
{
  local optname optarg

  while [ $# -gt 0 ]
  do
  optname="`echo $1 | sed 's,=.*,,'`"
  optarg="`echo $1 | sed 's,^[^=]*=,,'`"
  case "$1" in
    --f* | -f*)
      optarg=`echo $optarg | sed 's,[^0-9],,g'`
      exit_if_empty "$optname" "$optarg"
      fwhm=$optarg
      ;;
    --a* | -a*)
      ascii=1
      ;;
    --g* | -g*)
      gifti=1
      ascii=0
      ;;
    --noclobber | -noclobber)
      noclobber=1
      ;;
    --lh* | -lh*)
      hemi=lh
      ;;
    --rh* | -rh*)
      hemi=rh
      ;;
    --label | -label)
      label=" -label "
      ;;
    --m* | -m*)
      exit_if_empty "$optname" "$optarg"
      measure=$optarg
      ;;
    --t* | -t*)
      exit_if_empty "$optname" "$optarg"
      template=$optarg
      ;;
    --o* | -o*)
      exit_if_empty "$optname" "$optarg"
      output_dir=$optarg
      ;;
    --r* | -r*)
      exit_if_empty "$optname" "$optarg"
      reg=$optarg
      ;;
    -h | --help | -v | --version | -V)
      help
      exit 1
      ;;
    -*)
      echo "`basename $0`: ERROR: Unrecognized option \"$1\"" >&2
      ;;
    *)
      ARGV_list="$ARGV_list $1"
      ;;
  esac
    shift
  done

}


########################################################
# check arguments
########################################################

exit_if_empty ()
{
  local desc val

  desc="$1"
  shift
  val="$*"

  if [ -z "$val" ]
  then
  echo "ERROR: No argument given with \"$desc\" command line argument!" >&2
  exit 1
  fi
}

########################################################
# check if CAT tools exist
########################################################

check_tools ()
{
  for name in CAT_SurfResampleSpherical CAT_SurfSmooth; do
    found=`which ${name}`
    if [ ! -n "$found" ];then
      echo $name not found.
      exit 1
    fi
  done
}

########################################################
# usage
########################################################
usage ()
{
cat <<__EOM__
USAGE: CAT_ResampleFS_ui subject [subject2 .. subjectN] [-f=fwhm_in_mm] [-a] [-lh|-rh] [-noclobber] [-gifti] [-label]
                          [-o=output_directory] [-m=measure] [-r=surfreg] [-t=target_surface]                      
    
__EOM__
}

########################################################
# help
########################################################

help ()
{
cat <<__EOM__

PURPOSE:
Resample surface values to a parametric tetrahedral sphere. The resampled values can be 
optionally smoothed on the target surface using a diffusion heat kernel.

USAGE:
        CAT_ResampleFS_ui subject [subject2 .. subjectN] [-f=fwhm_in_mm] [-a] [-noclobber] [-lh|-rh] [-gifti] [-label]
                          [-o=output_directory] [-m=measure] [-r=surfreg] [-t=target_surface]                      
    
OPTIONS:
  subject    - one or more subject directories
  -f         - diffusion heat kernel smoothing defined in fwhm in mm [default $fwhm]
  -t         - target surface for resampling [default $template]
  -o         - output directory (created if necessary) [default $output_dir]                
  -m         - surface measure as input [default $measure]                 
  -r         - spherical surface for resampling [default $reg]                 
  -a         - save output as ascii (text) file
  -gifti     - save output as gifti file
  -lh        - resample left hemisphere only
  -rh        - resample right hemisphere only
  -noclobber - do not overwrite existing file
  -label     - use label interpolation (i.e. for labeled atlas data)
    
EXAMPLE:
    CAT_ResampleFS_ui ${SUBJECTS_DIR}/[a-d]* -f=20 -t=fsaverage -o=~/data -m=thickness
    This will resample thickness values of all subject with a beginning a-d in the folder ${SUBJECTS_DIR}
    according to target surface fsaverage.
    The resampled values are smoothed with 20mm and saved in ~/data.

INPUT:
    Freesurfer or MNI-OBJ surface files

OUTPUT:
    Values-files

USED FUNCTIONS:
    CAT_SurfResampleSpherical
    CAT_SurfSmooth

This script was written by Christian Gaser (christian.gaser@uni-jena.de).

__EOM__
}

########################################################
# call main program
########################################################

main ${1+"$@"}
