#!/bin/bash
#============================================================================
#
#  Program:     DTI ToolKit (DTI-TK)
#  Module:      $RCSfile: dti_rigid_population,v $
#  Language:    bash
#  Date:        $Date: 2011/12/21 20:39:22 $
#  Version:     $Revision: 1.1.1.1 $
#
#  Copyright (c) Gary Hui Zhang (garyhuizhang@gmail.com).
#  All rights reserverd.
#
#  DTI-TK is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  DTI-TK is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with DTI-TK.  If not, see <http://www.gnu.org/licenses/>.
#============================================================================

#
# rigid alignment of a set of DTI volumes to some template with iterative
# template optimization
#

# check DTITK_ROOT variable
if [ -z "${DTITK_ROOT}" ]
then
	echo "Environment variable DTITK_ROOT is not defined"
	exit 1
fi

# source dtitk_common.sh
. ${DTITK_ROOT}/scripts/dtitk_common.sh

if [ $# -lt 4 ]
then
	echo "Rigid aligment of a set of DTI volumes to a DTI template with iterative template optimization"
	echo "Usage: `basename $0` initial_template subject_list_file SMOption no_of_iterations"
	exit 1
fi

log=dti_rigid_population.log
echo "command: " $* | tee ${log}
date | tee -a ${log}

template=$1
subjects=$2
smoption=$3
iter=$4

cp $template mean_rigid0.nii.gz
subjects_aff=`echo $subjects | sed -e 's/.txt/_aff.txt/'`
rm -fr ${subjects_aff}
for subj in `cat ${subjects}`
do
	pref=`getTVPrefix ${subj}`
	echo ${pref}_aff.nii.gz >> ${subjects_aff}
done

jid=drp_"$$"
count=1
while [ $count -le $iter ]
do
	echo "dti_rigid_population iteration" $count | tee -a ${log}
	let oldcount=count-1
	if [ $count -eq 1 ]
	then
		dti_rigid_sn mean_rigid${oldcount}.nii.gz ${subjects} ${smoption}
	else
		dti_rigid_sn mean_rigid${oldcount}.nii.gz ${subjects} ${smoption} 1
	fi
	if [ "${DTITK_USE_QSUB}" -eq 1 ]
	then
		${dtitk_qsub} -cwd -o /dev/null -e /dev/null -b y -N ${jid} ${DTITK_ROOT}/bin/TVMean -in ${subjects_aff} -out mean_rigid${count}.nii.gz
		${dtitk_qsub} -sync y -hold_jid ${jid} -o /dev/null -e /dev/null -b y echo "done" > /dev/null
	else
		TVMean -in ${subjects_aff} -out mean_rigid${count}.nii.gz
	fi
	TVtool -in mean_rigid${oldcount}.nii.gz -sm mean_rigid${count}.nii.gz -SMOption  $smoption | grep Similarity | tee -a ${log}
	let count=count+1
done

