#!/bin/bash

# Example single job analysis script. In this example the script runs
# a short freesurfer pre-processing pipeline, but you could include
# any commands that the shell can interpret.

# This example is designed to be called by a multi-job script that passes
# the vaules for the variables SUBID, ANADIR, and OW




# Start by using PBS declarations to define which queue to use, what
# resources to request, etc

#PBS -q compute
#	= use the "compute" queue
#PBS -l walltime=30:00:00
#	= allow upto 30 hours for the job to run


# Configure Freesurfer environment:

export FREESURFER_HOME=/imaging/local/software/freesurfer/latest/`arch`
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${FREESURFER_HOME}/lib_flat
source ${FREESURFER_HOME}/FreeSurferEnv.sh


export FSFAST_HOME=/imaging/local/software/freesurfer/latest/`arch`/fsfast
export FSF_OUTPUT_FORMAT=nii.gz
export MNI_DIR=/imaging/local/software/freesurfer/latest/`arch`/mni
export FSL_DIR=/imaging/local/software/fsl/fsl64/fsl-4.1.8/fsl
export SUBJECTS_DIR=${ANADIR}


# Go to main analysis directory
cd ${ANADIR}


# Set up subject directory
SUBDIR=${ANADIR}/${SUBID}
if [ -d ${SUBDIR} ];then
	if [ ${OW} -eq 1 ];then
		rm -rf ${SUBDIR}
			#mkdir ${SUBDIR}
	else
		echo "Found existing files in in ${SUBDIR}. Exiting."
		exit	
	fi
fi

# Get raw dicom data - we only need the first file for recon-all
SEQ_FILT=MPRAGE
RAW_STRUCT=`ls /mridata/cbu/${SUBID}*/*/*${SEQ_FILT}*/*.dcm | head -1`
# This should cope with the simplest case where the subject has only
# a single session directory and a single MPRAGE. The code could be 
# expanded to cater for cases with multiple session directories, and
# multiple (or missing) MPRAGE series.

# run recon-all
recon-all -i ${RAW_STRUCT} -all -subjid $SUBID

# find fsaverage_sym + copy to SUBDIR
FSAVGSYM=${FREESURFER_HOME}/subjects/fsaverage_sym
FSAVGSYM_CP=${ANADIR}/fsaverage_sym
if [ -d ${FSAVGSYM_CP} ];then
	echo "Directory fsaverage_sym already exists in SUBJECTS_DIR"
	exit
else
	cp -r ${FSAVGSYM}/* ${ANADIR}/
fi

surfreg --s ${SUBID} --t fsaverage_sym --lh
surfreg --s ${SUBID} --t fsaverage_sym --lh --xhemi
