#!/bin/bash
#============================================================================
#
#  Program:     DTI ToolKit (DTI-TK)
#  Module:      $RCSfile: dti_rigid_population,v $
#  Language:    bash
#  Date:        $Date: 2011/07/22 17:22:19 $
#  Version:     $Revision: 1.4 $
#
#  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/>.
#===========================================================================


if [ $# -lt 6 ]
then
echo "Usage: tsa_stats_glm mesh_list_in.txt design_matrix contrast_matrix feature t-threshold  number_of_permutations"
exit 1
fi


# 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

mesh_in=$1
design_mat=$2
contrast_mat=$3
feature=$4
threshold=$5
perm=$6

mesh_glm_exe=`which meshglm`
#export ${PATH}=${PATH}:${mesh_glm_exe%%/meshglm}
jid=tsa_glm_"$$"

for mesh_name in `cat ${mesh_in}`
do
    echo ${mesh_name}
    cmd="${mesh_glm_exe} -m ${mesh_name}.vtk ${mesh_name}.clusters.${feature}_${threshold}.vtk -a ${feature} -g ${design_mat} ${contrast_mat} -s P -t ${threshold} -p ${perm} -e"

	if [ "${DTITK_USE_QSUB}" -eq 1 ]
	then
    jname=${jid}_${mode}
    ${dtitk_qsub} -cwd -e ${mesh_name}.clusters.${feature}_${threshold}.err -o ${mesh_name}.clusters.${feature}_${threshold}.log -b y -N ${jname} $cmd 

    else 
    ${cmd} > ${mesh_name}.clusters.${feature}_${threshold}.log
    fi

done