#!/bin/tcsh
# @rotategraddirs
#
# rotate vectors from tensor.1D based on volume registered dataset, r1_vr+orig
#
# Purpose: Uses the matrix vector rotation fields from the header attributes to 
# correct the gradient directions for subject angular motion
#
# Critical Assumptions:
# 1) asssumes 3dAllineate was used, so HEAD rotation fields will be named ALLINEATE_MATVEC_B2S_nnnnnn
# 2) also assumes input gradient vectors textfile contains 
#
# Example: @rotgraddirs TA328DWIREGtoSSanat+orig. DWGradientVectorsAfter12-21-07.txt
# 
# Written by: Daniel Glen SSCC/NIMH/NIH
# Modified by Timothy Ellmore, Ph.D. on 9/23/09 to be compatible 
#  with alignment by 3dAllineate and the Philips 32-direction 
#  overplus gradient directions
#

if ("$1" == '' || "$1" == '-help' || "$1" == '-h') then
goto HELP
endif

if ("$#" < 2) then
echo "Not enough parameters"
goto END
endif

set dset = $1
set tensor1D = $2
set ngrads = `3dnvals $dset`
# must subtract two because we don't want to consider first volume or last volume
@ ngrads = $ngrads - 2
#@ ngrads = $ngrads
echo "Dataset: $dset"
echo "Gradient vectors: $tensor1D"
echo "Num gradients: $ngrads"
echo "Rotating vectors..."
rm -f rotatedgrads.1D

foreach grad ( `count -digits 6 1 $ngrads`)
# put the matrix vector on three rows to be compatible with Vecwarp
( cat_matvec "$dset"'::ALLINEATE_MATVEC_B2S_'${grad} > tempmatvec.1D ) > & /dev/null
# replace the translation vector with 0s
1dcat tempmatvec.1D'[0..2]' '1D:3@0' > tempmatvec0.1D
echo "gradient: $grad"
# if there are no attributes from 3dvolreg in header, try 3dWarpDrive rotations
set check = `wc tempmatvec.1D`
if ($check[1] == 0) then
( cat_matvec "$dset"'::ALLINEATE_MATVEC_B2S_'${grad} > tempmatvec0.1D ) > & /dev/null
set check = `wc tempmatvec0.1D`
if ($check[1] == 0) then
echo "No rotation matrix in header"
goto END
endif
endif

# get the original vector for the current gradient
# (no zero row, so subtract 1)
@ gradrow = $grad - 1
echo "gradrow: $gradrow"
1dcat "$tensor1D{$gradrow}" > tempvector.1D
cat tempvector.1D
cat tempmatvec0.1D
# rotate the vector for the current gradient
Vecwarp -matvec tempmatvec0.1D -backward -input tempvector.1D -force -output temprotgrad.1D > & /dev/null
cat temprotgrad.1D
# |& tee > /dev/null
# append the rotated gradients to a single file
cat temprotgrad.1D >> rotatedgrads.1D
rm temprotgrad.1D
rm tempmatvec*.1D
rm tempvector.1D
end
echo "Output gradient vector file is rotatedgrads.1D"

goto END

HELP:
echo "Usage: `basename $0` volreg_dset gradients.1D"
echo "Rotate DTI gradient vectors based on rotations from volume registration"
echo "Current script assumes 3dvolreg or 3dWarpDrive corrected dataset with"
echo "preference to 3dvolreg rotation parameters"
echo "Output file is rotatedgrads.1D"
echo ""
echo "Daniel Glen SSCC/NIMH/NIH"
echo ""
goto END

END:



