#!/bin/bash
#   Automated probabilistic tractography plugin for FSL; visualisation script.
#
#   Performs tractography as used in De Groot et al., NeuroImage 2013.
#   2013, Marius de Groot
#
#   LICENCE
#
#   AutoPtx, plugin for FSL, Release 0.1 (c) 2013, Erasmus MC, University
#   Medical Center (the "Software")
#
#   The Software remains the property of the Erasmus MC, University Medical
#   Center ("the University").
#
#   The Software is distributed "AS IS" under this Licence solely for
#   non-commercial use in the hope that it will be useful, but in order
#   that the University as a charitable foundation protects its assets for
#   the benefit of its educational and research purposes, the University
#   makes clear that no condition is made or to be implied, nor is any
#   warranty given or to be implied, as to the accuracy of the Software, or
#   that it will be suitable for any particular purpose or for use under
#   any specific conditions.  Furthermore, the University disclaims all
#   responsibility for the use which is made of the Software.  It further
#   disclaims any liability for the outcomes arising from using the
#   Software.
#
#   The Licensee agrees to indemnify the University and hold the University
#   harmless from and against any and all claims, damages and liabilities
#   asserted by third parties (including claims for negligence) which arise
#   directly or indirectly from the use of the Software or the sale of any
#   products based on the Software.
#
#   No part of the Software may be reproduced, modified, transmitted or
#   transferred in any form or by any means, electronic or mechanical,
#   without the express permission of the University.  The permission of
#   the University is not required if the said reproduction, modification,
#   transmission or transference is done without financial return, the
#   conditions of this Licence are imposed upon the receiver of the
#   product, and all original and amended source code is included in any
#   transmitted product.  You may be held legally responsible for any
#   copyright infringement that is caused or encouraged by your failure to
#   abide by these terms and conditions.
#
#   You are not permitted under this Licence to use this Software
#   commercially.  Use for which any financial return is received shall be
#   defined as commercial use, and includes (1) integration of all or part
#   of the source code or the Software into a product for sale or license
#   by or on behalf of Licensee to third parties or (2) use of the Software
#   or any derivative of it for research with the final aim of developing
#   software products for sale or license to a third party or (3) use of
#   the Software or any derivative of it for research with the final aim of
#   developing non-software products for sale or license to a third party,
#   or (4) use of the Software to provide any service to an external
#   organisation for which payment is received.  If you are interested in
#   using the Software commercially, please contact the technology transfer
#   company of the University to negotiate a licence.  Contact details are:
#   tto@erasmusmc.nl quoting reference SOPHIA #2013-012 and the
#   accompanying paper DOI: 10.1016/j.neuroimage.2013.03.015.
#

Usage() {
cat << EOF

Usage: autoPtx_prepareForDisplay <threshold>

    For all subjects, generates binary masks for each structure, and preares a
    call to display the tracts in FSLView.

    <threshold> is used to binarise the normalised tract density images. As a
    first test try e.g. 0.005.

EOF
    exit 1
}

[ "$1" = "" ] && Usage

thresh=$1

# init
prewd=$PWD
execPath=`dirname $0`
cd $execPath
execPath=$PWD
cd $prewd

tractSrc=tracts
data=preproc
structures=$execPath/structureList
subjects=preproc/subjectList
dest=visualise/th_${thresh}
command=viewAll_${thresh}

mkdir -p $dest

# function based on fsledithd script
setIntentCode() {
    tmpbase=`${FSLDIR}/bin/tmpnam`;
    tmpbase2=`${FSLDIR}/bin/tmpnam`;

    # generate the xml-style header with fslhd
    ${FSLDIR}/bin/fslhd -x $1 | grep -v '/>' | grep -v 'intent_code' | grep -v '_filename' | grep -v '[^t]_name' | grep -v 'nvox' | grep -v 'to_ijk' | grep -v 'form_.*orientation' | grep -v 'qto_' > ${tmpbase}
    # exit if the above didn't generate a decent file
    if [ `cat ${tmpbase} | wc -l` -le 1 ] ; then
    echo "==ERROR== Header not recognized. Exiting..."
    exit 0;
    fi

    # append intent_code to header
    echo "  intent_code = '"$2"'  " >> ${tmpbase}
    # close the xml-style part
    echo "/>" >> ${tmpbase}

    cat ${tmpbase} | grep -v '^[ 	]*#' | grep -v '^[ 	]*$' > ${tmpbase2}
    ${FSLDIR}/bin/fslcreatehd ${tmpbase2} $1

    \rm -f ${tmpbase} ${tmpbase2}
}

# the individual luts for each tract, combined with the intentcode in the nifti
# header allow each tract to be displayed in FSLView with some spatial smoothing
if [ ! -e $dest/luts ]; then
    ln -s $execPath/luts $dest/luts
fi

echo "#!/bin/bash" > $command
chmod +x $command
while read sub; do
    mkdir -p $dest/$sub
    comIt=0
    $FSLDIR/bin/applywarp --in=$data/$sub/dti_FA --out=$dest/$sub/dti_FA --ref=$data/$sub/refVol --premat=$FSLDIR/etc/flirtsch/ident.mat
    $FSLDIR/bin/fslmaths $dest/$sub/dti_FA -mul 1000 -range $dest/$sub/dti_FA
    viewstr=fslview\ $dest/$sub/dti_FA
    while read line; do
        struct=`echo $line | awk '{print $1}'`
        comIt=$(( $comIt + 1 ))
        tracts=$tractSrc/$sub/$struct/tracts/tractsNorm.nii.gz
        tracts_thr=$dest/$sub/${struct}_tract
        $FSLDIR/bin/fslmaths $tracts -thr $thresh -bin -mul $comIt -range $tracts_thr
        setIntentCode $tracts_thr 3
        viewstr=$viewstr\ $tracts_thr\ -b\ 0.1,${comIt}.01\ -l\ $dest/luts/c${comIt}.lut
    done < $structures
    echo $viewstr >> $command
done < $subjects
