#!bin/bash -eux
SUBJECTS_DIR=/net/synapse/nt/mozzoude/Scripts/freesurfer/scripts
FUNCTIONALS_DIR=/net/synapse/nt/mozzoude/Scripts/freesurfer/scripts

#creating list of session.Always change the subjectID
function find_inputs {
  # return all basenames (do it by length)
  find ${SUBJECTS_DIR} -maxdepth 1 -type d -name "OND01*" -exec bash -c "f='{}' ; echo \${f::-3}" \; | uniq
}


function FreeSurfer_Long {

    local in_dir=$1
    local session=$(basename "${in_dir}")
    
    #stop the execution of this scripts if a command has an error
    set -e 

    # sourcing FREESURFER_HOME
    export FREESURFER_HOME=/opt/freesurfer-6.0.0/freesurfer
    export FS_FREESURFERENV_NO_OUTPUT="1"
    export PS1="0"
    export FS_OVERRIDE="0"
    export FSFAST_HOME=$FREESURFER_HOME/fsfast
    export NO_MINC="0"
    export FSL_DIR="0"
    export FSF_OUTPUT_FORMAT="0"
    export NO_FSFAST="0"
    export VXL_LIB="0"
    export DYLD_LIBRARY_PATH="0"
    source $FREESURFER_HOME/SetUpFreeSurfer.sh
    # source $FREESURFER_HOME/FreeSurferEnv.sh 


    #set subject ID 
    local SubjectID="${session}"

    # #creating SUBJECTS_DIR. where your subjects directory is located 
    export SUBJECTS_DIR=/net/synapse/nt/mozzoude/Scripts/freesurfer/scripts/
    export FUNCTIONALS_DIR=/net/synapse/nt/mozzoude/Scripts/freesurfer/scripts/

    #start scripts
    echo -e "\n START: FreeSurfer_Long"

    # find all directories that have the same basename
    local session_files=($(find ${SUBJECTS_DIR} -maxdepth 1 -type d -name "*${session}*"))
    local tp1=$(basename "${session_files[0]}")
    local tp2=$(basename "${session_files[1]}")

    #create an unbiased template for all time for each subject and process it with recon-all.Remember to change the subjectID. i.e from 001 to 002
    recon-all -base ${session} -tp "${tp1}" -tp "${tp2}" -all -openmp 8 -3T -time 

    # #run the longitudinal processing for all timepoints. the base template needs to be passed to the longitudinal processing of each timpoint of each subject.Remember to change the subjectID. i.e from 001 to 002
    recon-all -long ${tp1} ${session} -all -time -openmp 8 -3T 
    recon-all -long ${tp2} ${session} -all -time -openmp 8 -3T 


}

readonly all_inputs=$(find_inputs)

for in_dir in ${all_inputs}; do
  FreeSurfer_Long "${in_dir}" 
done

