#! /bin/sh

### prf2sess: marty sereno -- conv SamSrf subjdir pRF to also FUNCTIONALS_DIR
# 16/04/28 -- 01a: initial hack

if [ $# -ne 1 ]; then
  echo ""
  echo "use: prf2sess <prf_subject_dir>"
  echo ""
  echo '  --N.B.: first cd into $SUBJECTS_DIR before running prf2sess'
  echo ""
  echo '  --output1: creates "name" file inside subject'
  echo '  --output2: creates csurf "image" subdir inside subject'
  echo '  --output3: converts .label files to .w inside image/prf w/calcvert'
  echo '  --output4: insert r^2 amp to make _x,_y from _r,_i w/calcvert'
  echo ""
  echo "  --csurf can then read this subject dir also as a session dir"
  echo '  --redo OK (only overwrites files in "image" subdir)'
  echo "                                                          version: 01a"
  exit
fi
subj=$1

### only allow run from in current SUBJECTS_DIR
if [ -z "$SUBJECTS_DIR" ]; then
  echo "prf2sess: ### env var SUBJECTS_DIR not set (use export)  ...quitting"
  exit
fi
if [ `pwd` != "$SUBJECTS_DIR" ]; then
  echo "prf2sess: ### not inside current SUBJECTS_DIR  ...quitting"
  exit
fi
if [ ! -d "$subj" ]; then
  echo "prf2sess: ### subject directory $subj not found"
  exit
fi

### make name file
echo ""
echo 'prf2sess: adding "name" file to $subj'
echo $subj > $subj/name

### make standard session dir tree with one scander, "prf"
echo ""
echo 'prf2sess: adding empty "image" directory tree to $subj'
if [ ! -d $subj/image ]; then
  mkdir $subj/image
fi
if [ ! -d $subj/image/scripts ]; then
  mkdir $subj/image/scripts
fi
if [ ! -d $subj/image/rgb ]; then
  mkdir $subj/image/rgb
fi
if [ ! -d $subj/image/mpg ]; then
  mkdir $subj/image/mpg
fi
if [ ! -d $subj/image/prf ]; then
  mkdir $subj/image/prf
fi

### in/out dirs
indir=$subj/prf
outdir=$subj/image/prf

### convert all pRF label files, both hemi's
for hemi in lh rh; do
  list=$indir/${hemi}_pRF_*.label
  echo ""
  echo "prf2sess: (hemi=$hemi) convert ${hemi}_pRF_*.label to wfiles"
  echo "---------------------------------------------------"
  for label in $list; do
    outfile=$outdir/`basename $label .label | cut -b 4-`-${hemi}.w
    calcvert -convert -labelfilein -valfileout $label $outfile
    echo "---------------------------------------------------"
  done
  echo ""
  echo "prf2sess: (hemi=$hemi) ecc/pol: ang from _r,_i w/amp from r^2 => _x,_y"
  echo "---------------------------------------------------"
  for coord in ecc pol; do
    in1=$indir/${hemi}_pRF_sf_${coord}_r.label
    in2=$indir/${hemi}_pRF_sf_${coord}_i.label
    in3=$indir/${hemi}_pRF_sf_r^2.label
    ou1=$outdir/pRF_sf_${coord}_x-${hemi}.w
    ou2=$outdir/pRF_sf_${coord}_y-${hemi}.w
  calcvert -insertamp -labelfilein -valfileout $in1 $in2 $in3 $ou1 $ou2
  echo "---------------------------------------------------"
  done
done
