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

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

outputdir=""
mask=""
reg=sphere.reg
template=$FREESURFER_HOME/subjects/fsaverage
fwhm=0
noclobber=0
gifti=1
DNAME=`dirname $0`
export PATH=$PATH:$DNAME

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

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

  exit 0
}


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

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

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

      surfdir=`dirname $subject`
      hemi=`basename $subject|cut -f1 -d'.'`
      measure=`basename $subject|cut -f2 -d'.'`
      subject_name=`basename $subject|cut -f3 -d'.'`
      central=`basename $subject|sed 's,.'${measure}'.,.central.,g'`
      sphere=`basename $subject|sed 's,.'${measure}'.,.'${reg}'.,g'`
      central=`echo ${central}.gii|sed 's,.gii.gii,.gii,g'`
      sphere=`echo ${sphere}.gii|sed 's,.gii.gii,.gii,g'`
      
      if [ ! "${mask}" == "" ]; then
        if [ ! -f "$mask" ]; then
          echo Masking file $mask not found.
          exit
        fi
      fi

      if [ "${outputdir}" == "" ]; then
        outputdir=$surfdir
      fi

      if [ ! "$hemi" == "lh" ] && [ ! "$hemi" == "rh" ]; then
        echo File $subject should begin with lh or rh.
        exit    
      fi
      
      tmp_name=/tmp/$$_resample

      for i in $hemi; do
      
        if [ ! "$fwhm" == 0 ]; then
          name=${outputdir}/s${fwhm}mm.${i}.${measure}.resampled.${subject_name}
        else
          name=${outputdir}/${i}.${measure}.resampled.${subject_name}
        fi
        
        if [ "$gifti" == 1 ]; then
          output=${name}.gii
        else
          output=${name}
        fi
        
        if [ -f "${output}" ] && [ "$noclobber" == 1 ]; then
          echo $output will be not overwritten. Do not use -noclobber if you want to overwrite it.
        else
          for files in ${surfdir}/${central} ${surfdir}/${sphere} ${targetdir}/${i}.sphere; do
            if [ ! -f "$files" ]; then
              echo File $files not found.
              exit
            fi
          done
            
          CAT_ResampleSurf ${surfdir}/${central} ${surfdir}/${sphere} ${targetdir}/${i}.sphere $tmp_name ${subject} ${tmp_name}.txt
          CAT_BlurSurfHK $tmp_name $name $fwhm ${tmp_name}.txt ${mask}
          if [ "$gifti" == 1 ]; then
            CAT_AddValuesToSurf $tmp_name $name ${output}
            echo resample and smooth to ${output}        
            rm $name
          else 
            echo resample and smooth to $name 
          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
      ;;
    --nogifti* | -nog*)
      gifti=0
      ;;
    --noclobber* | -noc*)
      noclobber=1
      ;;
    --t* | -t*)
      exit_if_empty "$optname" "$optarg"
      template=$optarg
      ;;
    --o* | -o*)
      exit_if_empty "$optname" "$optarg"
      outputdir=$optarg
      ;;
    --m* | -m*)
      exit_if_empty "$optname" "$optarg"
      mask=$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_ResampleSphericalSurf CAT_BlurSurfHK; do
    found=`which ${name}`
    if [ ! -n "$found" ];then
      echo $name not found.
      exit 1
    fi
  done
}

########################################################
# usage
########################################################
usage ()
{
cat <<__EOM__
USAGE: CAT_Resample_ui measure [measure2 .. measureN] [-f=fwhm_in_mm] [-a] [-noclobber] [-nogifti]
                          [-o=outputdirectory] [-r=surfreg] [-t=fsaverage_directory] [-m=mask]                     
    
__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_Resample_ui measure [measure2 .. measureN] [-f=fwhm_in_mm] [-noclobber] [-nogifti]
                          [-o=outputdirectory] [-r=surfreg] [-t=fsaverage_directory] [-m=mask]                    
    
OPTIONS:
  subject    - one or more subject
  -f         - diffusion heat kernel smoothing defined in fwhm in mm [default $fwhm]
  -t         - target surface directory for resampling [default $template]
  -o         - output directory (created if necessary) [default $outputdir]                
  -r         - spherical surface for resampling [default $reg]                 
  -m         - soptional mask to set NaNs in areas where mask=0                 
  -nogifti   - save output not as gifti file
  -noclobber - do not overwrite existing file
    
EXAMPLE:
    CAT_Resample_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_ResampleSurf
    CAT_BlurSurfHK

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

__EOM__
}

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

main ${1+"$@"}
