#!/bin/bash
#============================================================================
#
#  Program:     DTI ToolKit (DTI-TK)
#  Module:      $RCSfile: dti_template_bootstrap,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/>.
#============================================================================

#
# bootstrap an initial template estimate from a set of DTI volumes
#

# 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 2 ]
then
	echo "Bootstrap an initial template estimate from a set of DTI volumes"
	echo "Usage: `basename $0` existing_template subject_list_file [SMOption]"
	exit 1
fi

template=$1
subjects=$2

# first run rigid alignment to the existing template
dti_rigid_sn $template $subjects EDS

if [ $# -eq 3 ]
then
	SMOption=$3
else
	SMOption=EDS
fi

# next run affine alignment using the rigid alignment output as initialization
dti_affine_sn $template $subjects $SMOption 1

# create the subject list file of the affine aligned subjects
subjects_aff=dti_template_bootstrap_$RANDOM
for file in `cat $subjects`
do
	echo $file | sed -e 's/.nii.gz/_aff.nii.gz/'
done > $subjects_aff

# compute the initial template
TVMean -in $subjects_aff -out mean_initial.nii.gz
echo "Initial bootstrapped template is computed and saved as mean_initial.nii.gz"

# clean up
rm -fr $subjects_aff

