#!/bin/sh
## brainageR software, global wrapper script
## James Cole, King's College London james.cole@kcl.ac.uk
## software version 1.0 09 Aug 2018

usage() {
    cat <<EOF

brainageR software version 1.0 09 Aug 2018

Required arguments: 
	-f: input Nifti file
	-o: output csv filename

Optional arguments:
	-d: debug mode - turns off clean-up
	-h: displays this help message

For example:
brainageR -f subj01_T1.nii -o subj01_brain_predicted.age.csv

Dependencies:
R packages: kernlab, RNifti, stringr
SPM (MATLAB)
FSL (for slicesdir)

EOF
    exit 1
}

############################################################################

while getopts ":f:o:dh:" opt; do
    case "${opt}" in
        f)  	nifti_file=${OPTARG} ;;
        o)		output_filename=${OPTARG} ;;
        d)		debug_mode=1 ;;
        h|*)    usage ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${nifti_file}" ] || [ -z "${output_filename}" ]; then
    usage
fi

## check files are Niftis
if [[ $nifti_file != *.nii ]]; then usage; fi
## configure modules and software directories for your local system
module load R
module load matlab
module load fsl
brainageR_dir=/home/jcole/brain_age/BRAIN_AGE_T1/brainageR/
spm_dir=/apps/matlab_toolboxes/spm12/
## run brainageR analysis
nifti_file=$(find `pwd` -name $nifti_file) 
cmd="matlab -nosplash -nodesktop -r \"addpath(['$brainageR_dir','software/']);spm_preprocess_brainageR('$nifti_file',['$brainageR_dir','software/templates/'], '$spm_dir');exit\""
eval ${cmd}
find `pwd` -name smwc1${nifti_file} > smwc1${nifti_file%.nii}.txt
find `pwd` -name smwc2${nifti_file} > smwc2${nifti_file%.nii}.txt
$brainageR_dir/software/slicesdir.brainageR -n ${nifti_file%.nii} [c,s]*[1,2]*${nifti_file}
Rscript $brainageR_dir/software/predict_new_data_gm_wm.R $brainageR_dir `pwd`/smwc1${nifti_file%.nii}.txt `pwd`/smwc2${nifti_file%.nii}.txt $brainageR_dir/software/GPR_model_gm_wm.RData `pwd`/$output_filename
## clean up
if [ -z $debug_mode  ]; then
for img in c1 c2 c3 rc1 rc2 rc3 u_rc1 smwc1 smwc2; do
	rm ${img}${nifti_file}
done
rm ${nifti_file%.nii}*seg8.mat
rm smwc[1,2]${nifti_file%.nii}.txt
fi
