#! /bin/sh

### fsavgannot2subj: marty sereno -- samp/conv annot to single sub 3D ROIs
# 17/03/17 -- 01a: initial hack

if [ $# -ne 2 ] && [ $# -ne 3 ]; then
  echo ""
  echo "use: fsavgannot2subj <annotinfix> <subj> [-f]"
  echo ""
  echo "  --sphere.reg resamp fsaverage annot to single subj w/mri_surf2surf"
  echo "  --append -f to force overwrite already existing"
  echo "  --example: fsavgannot2subj HCP-MMP1 marser-qT1"
  echo "                                                          version: 01a"
  exit
fi
annotinfix=$1
subj=$2
if [ $# -eq 3 ] && [ "$3" = "-f" ]; then force=1; else force=0; fi

### check binaries/inputs exist
if [ "`which mri_surf2surf`" == "" ]; then
  echo 'fsavgannot2subj: ### mri_surf2surf not on $path   ...quitting'
  exit
fi
if [ -z "$SUBJECTS_DIR" ]; then
  echo "fsavgannot2subj: ### no SUBJECTS_DIR env var (use export)  ...quitting"
  exit
fi
if [ ! -d "$SUBJECTS_DIR/$subj" ]; then
  echo "fsavgannot2subj: ### subject directory: $subj not found"
  exit
fi
for hemi in lh rh; do
  chkfile="$SUBJECTS_DIR/fsaverage/label/$hemi.$annotinfix.annot"
  if [ ! -f $chkfile ]; then
    echo "fsavgannot2subj: ### infile not found:"
    echo "fsavgannot2subj: ### $chkfile"
    exit
  fi
done

### check outputs don't exist
found=0
for hemi in lh rh; do
  chkfile=$SUBJECTS_DIR/$subj/label/$hemi.$annotinfix.annot
  if [ -f $chkfile ]; then
    if [ $found -eq 0 ]; then
      echo "fsavgannot2subj: ### outfile(s) already exist:"
    fi
    echo "fsavgannot2subj: ###  $chkfile"
    found=1
  fi
done
if [ $found -eq 1 ]; then
  if [ $force -eq 1 ]; then
    echo "fsavgannot2subj: (-f) overwriting..."
  else
    echo "fsavgannot2subj: ### move aside and try again (or use -f)"
    exit
  fi
fi

### go
echo "fsavgannot2subj: resample fsaverage {rh,lh}.$annotinfix.annot to $subj"
for hemi in lh rh; do
  cmd="mri_surf2surf \
    --srcsubject fsaverage \
    --trgsubject $subj \
    --hemi $hemi \
    --mapmethod nnf \
    --sval-annot $SUBJECTS_DIR/fsaverage/label/$hemi.$annotinfix.annot \
    --tval $SUBJECTS_DIR/$subj/label/$hemi.$annotinfix.annot"
  echo ""
  echo "####################################################################"
  echo $cmd
  echo "####################################################################"
  $cmd
done
