#!/bin/bash -x
if [ $# -lt 1 ] ; then
echo '---------------------------------------------------------------------------'
echo 'This algorithm will perform the brain extraction (skull stripping) on given image.'
echo "Command: $0 Subj.nii [options]"
echo '          -t  Temparary folder name   (optional:   tmp_strip)'
echo '          -c  Temparary folder remove (optional:   default: 0, 1 is to remove)'
echo '          -r  ImageOrientation        (optional:   default: 0 for eye on your right hand side in sigittal view; 1 for left)'
echo '          -p  Adult subject           (optional:   default: 0 for adult T1 images, 1 is for pediatric T1 images, 2 is for neonate T2 images, 3 for unified)'
echo 'Note:    Input image should be nii format.'
echo '         Please setup LABELDIR as the program path in your shell environment ~/.bashrc or ~/.cshrc, as well as in your ~/matlab/startup.m file.'
echo 'Example: for adult, fLABEL  NORMAL01_cbq2.nii -p 0'
echo '         for pediatric, fLABEL  r0301_child.nii -p 1'
echo '         In server using job submission system, qsub -N do_strip_$$ ${LABELDIR}/fLABEL $PWD/subj.hdr'
echo 'Check:   The input image will be firstly aligned to a template and then perform brain extraction. '
echo '         If you got strange results, please check the alignment in temporary folder. '
echo '---------------------------------------------------------------------------'
echo 'by Feng Shi at 2011-2014, comments and suggestions plz send to fengshiunc@gmail.com'
exit
fi
echo 'Welcome to learning based brain extraction'
echo 'Start running...'
# ----------------------------------------------
# functions
function strLength()
{
    count=0
    for t in $* ; do
        count=`expr $count + 1`
    done
    echo $count
}


function exitProgram ()
{   
    echo "exit program is activated"
        # back old dir
        cd $oldPath
        echo $oldPath
        echo "Clean is $Clean, tmp is $Tmp"
        # Clean
        if [ "$Clean" -eq 1 ] ; then rm -r $Tmp; echo "$Tmp folder is removed" ; fi
        # time elapsed
        endTime="$(date +%s)"
        usedTime=`expr $endTime - $startTime`
        echo "Total used $usedTime seconds"
        exit 0
}

# ----------------------------------------------
# initial input parameters
# set up FSL output image type as nii
export FSLOUTPUTTYPE=NIFTI
# if the program path is not defined, define it here.
if [[ ! -z $LABELDir ]] ; then LABELDir=${0/bin\/fLABEL/} ; fi
# record time
startTime="$(date +%s)"
Neo="$1"
# recognize the path
    oldPath=$PWD
    Neo=`echo ${1##*/}`
    if [ $1 == $Neo ] ; then
    newPath=$oldPath
    else
    newPath=${1%*$Neo}
    fi
    cd $newPath
    pwd
# take options
    # predefine
    Tmp=tmp_strip-`echo $Neo|cut -d. -f1` ;Clean=0;Ori=0;Ped=0;
input=$*
input=${input#* }   # remove the $1, input=`removeHeadStr $input`
echo "input is $input, ${#input}"
rm -rf 0
while [ ${#input} > 0 ]
do
    op=`echo $input | cut -d" " -f 1` # ${input%% *} 
    opc=`echo $input | cut -d" " -f 2`
    if   [ $op = '-t' ] ; then Tmp=$opc ;
    elif [ $op = '-c' ] ; then Clean=$opc ;
    elif [ $op = '-r' ] ; then Ori=$opc ;  
    elif [ $op = '-p' ] ; then Ped=$opc ; 
    fi
    input=${input#* }
    input=${input#* }
    flag=`strLength $input`
    if [ $flag -le 1 ] ; then echo "Parameter analyze done" ; break ; fi
done
rm -rf 0
echo `pwd`
echo "Tmp=$Tmp, Clean=$Clean, Oriention=$Ori, PediatricInput=$Ped"

tmpDir=$LABELDIR/templates
if [ $Ped -eq 0 ] ; then
    #tmpImg=label-avgAtlas-subj					# mean image
	tmpImg=atlas90-raw-axialdown-256_256_256    #individual image
    maskImg=label-avgAtlas-subj-mask
elif [ $Ped -eq 1 ] ; then
    tmpImg=label-avgAtlasPed-subj
    maskImg=label-avgAtlasPed-subj-mask
else
    tmpImg=label-avgAtlasNeo-subj
    maskImg=label-avgAtlasNeo-subj-mask
fi
# ----------------------------------------------
# program begin
if [ -d $Tmp ] ; then rm -r $Tmp ; fi
mkdir $Tmp
cd $Tmp
# To get image information for two images
    # image 1
    input_Neo=`echo $Neo | cut -d. -f1`
    cp ../$input_Neo.nii $input_Neo.nii
    if [ ! -s $input_Neo.nii ] ; then echo $PWD ; echo "$input_Neo.nii image not found, exit" ; exitProgram ; fi

# reorient
    m=$input_Neo #-head
    Orient=0;
    # adult atlas is left side, infant atlas is right side.
    if [ $Ori -eq 0 -a $Ped -eq 0 ] ; then Orient=1 ; elif [ $Ori -eq 1 -a $Ped -eq 1 ] ; then Orient=1 ; fi
    if [ $Orient -eq 1 ] ; then
    fslswapdim $m.nii -x -y z $m-reorient.nii
    else
    cp -l $m.nii $m-reorient.nii
    fi

# align
    m=$m-reorient
        flirt -in $m.nii -ref $tmpDir/$tmpImg.nii -out $m-align.nii -omat $m-align.mat -searchrx -30 30  -searchry -30 30 -searchrz -30 30
        # mask
        fslmaths $m-align.nii -mas $tmpDir/$maskImg.nii $m-align-mask.nii

# send to segmentation
    m=$m-align-mask
    echo 'Brain extraction begin ...'
	testname=${PWD}/$m.nii
	flag=$Ped
	matlab -nodesktop -nosplash -r "fLABEL('$testname','$flag','$PWD')"

# reverse the affine registration
    m=$m-strip-mask
        convert_xfm -inverse $input_Neo-reorient-align.mat -omat $input_Neo-reorient-align-reverse.mat
        flirt -in $m.nii -ref $input_Neo-reorient.nii -out $m-alignBack.nii -applyxfm -init $input_Neo-reorient-align-reverse.mat

# reorient back
    m=$m-alignBack
    if [ $Orient -eq 1 ] ; then
        fslswapdim $m.nii -x -y z $m-reorientBack.nii
    else
        cp -l $m.nii $m-reorientBack.nii
    fi

# apply the mask on original image
    fslmaths $input_Neo.nii -mul $m-reorientBack.nii $input_Neo-strip.nii

# copy result up    
    cp $input_Neo-strip.nii ../

# close the program
    exitProgram

# end of program

