#!/bin/sh

# Print usage if no argument is given
if [ -z "$1" ]; then
cat <<EOU
Batch convert surface and DPV (curvature) files from a given 
subject to ASCII format. FreeSurfer must be correctly
configured in the memory, with both \${FREESURFER_HOME}
and \${SUBJECTS_DIR} variables set.

Usage:
subj2ascii <subj_id>

_____________________________________
Anderson M. Winkler
Yale University / Institute of Living
Jan/2011 (original version)
Jul/2013 (this version)
http://brainder.org
EOU
exit
fi

# Subject ID
SUBJ=$1

# Hemispheres
HEMI="lh rh"

# Surfaces (up to v5.3.0; increase the list as needed for future versions)
SURF="inflated inflated.nofix orig orig.nofix pial qsphere.nofix smoothwm smoothwm.nofix sphere sphere.reg white"

# Curvatures (up to v5.3.0; increase the list as needed for future versions)
CURV="area area.mid area.pial avg_curv curv curv.pial inflated.H inflated.K jacobian_white smoothwm.BE.crv smoothwm.C.crv smoothwm.FI.crv smoothwm.H.crv smoothwm.K1.crv smoothwm.K2.crv smoothwm.K.crv smoothwm.S.crv sulc thickness volume w-g.pct.mgh"

# "Nofix" curvatures (up to v5.3.0; increase the list as needed for future versions)
CURV_NOFIX="defect_borders defect_chull defect_labels"

# Simplify a bit with a shorter variable
SDIR=${SUBJECTS_DIR}/${SUBJ}

# Where to store the outputs
mkdir -p ${SDIR}/ascii

# For each hemisphere
for h in ${HEMI} ; do

   # For each surface file
   for s in ${SURF} ; do
      if [ -e ${SDIR}/surf/${h}.${s} ] ; then
         echo "${SDIR}/surf/${h}.${s} -> ${SDIR}/ascii/${h}.${s}.srf"
         ${FREESURFER_HOME}/bin/mris_convert ${SDIR}/surf/${h}.${s} ${SDIR}/ascii/${h}.${s}.asc
         mv ${SDIR}/ascii/${h}.${s}.asc ${SDIR}/ascii/${h}.${s}.srf
      fi
   done

   # For each curvature file
   for c in ${CURV} ; do
      if [ -e ${SDIR}/surf/${h}.${c} ] ; then
         echo "${SDIR}/surf/${h}.${c} -> ${SDIR}/ascii/${h}.${c}.dpv"
         ${FREESURFER_HOME}/bin/mris_convert -c ${SDIR}/surf/${h}.${c} ${SDIR}/surf/${h}.white ${SDIR}/ascii/${h}.${c}.asc
         mv ${SDIR}/ascii/${h}.${c}.asc ${SDIR}/ascii/${h}.${c}.dpv
      fi
   done
   
   # For each "nofix" curvature file
   for c in ${CURV_NOFIX} ; do
      if [ -e ${SDIR}/surf/${h}.${c} ] ; then
         echo "${SDIR}/surf/${h}.${c} -> ${SDIR}/ascii/${h}.${c}.dpv"
         ${FREESURFER_HOME}/bin/mris_convert -c ${SDIR}/surf/${h}.${c} ${SDIR}/surf/${h}.orig.nofix ${SDIR}/ascii/${h}.${c}.asc
         mv ${SDIR}/ascii/${h}.${c}.asc ${SDIR}/ascii/${h}.${c}.dpv
      fi
   done
done
