#!/bin/bash
#============================================================================
#
#  Program:     DTI ToolKit (DTI-TK)
#  Module:      $RCSfile: scalar_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 scalar 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 scalar volumes to a scalar template with iterative template optimization"
	echo "Usage: `basename $0` initial_template subject_list_file SMOption no_of_iterations"
	echo "Available SMOptions:"
	echo "1) SSD: Sum of Squared Differences in intensity"
	echo "2) MI: Mutual Information"
	echo "3) NMI: Normalized Mutual Information"
	exit 1
fi

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

count=1
while [ $count -le $iter ]
do
	echo "scalar_rigid_population iteration" $count
	let oldcount=count-1
	if [ $count -eq 1 ]
	then
		scalar_rigid_sn mean_rigid${oldcount}.nii.gz ${subjects} ${smoption}
	else
		scalar_rigid_sn mean_rigid${oldcount}.nii.gz ${subjects} ${smoption} 1
	fi
	SVMean -in ${subjects_aff} -outMean mean_rigid${count}.nii.gz -outStd meanstd_rigid${count}.nii.gz
	SVtool -in mean_rigid${oldcount}.nii.gz -sm mean_rigid${count}.nii.gz
	let count=count+1
done

