#!/bin/bash
if [ $# -lt 1 ] ; then
echo 'This algorithm will perform skull stripping and EM-based tissue segmentation on T1/T2 MR brain images in analyze format.'
echo 'It works fine for adult brain images.'
echo 'The input is an analyze image. The output will be a skull-stripped image and a segmented image. (For example, input is Subj.hdr, output will be Subj_mask.hdr and Subj_seg.hdr) '
echo 'Command: SkullStrippingAndTissueSegmentationByEM Subj.hdr tmp_Directory_ForSavingResults ToRemoveOrKeepTmpDir ImageOrientation ThresholdForBET'
echo 'Input:    Subj.hdr               (An image (at analyze format) to be skull-stripped and tissue-segmented)'
echo '          tmp_Directory          (Give a directory name for saving the intermediate results)'
echo '          ToRemoveOrKeepTmpDir   (Default: 0 for keeping the above directory; 1 for removing it)'
echo '          ImageOrientation       (Default: 0 (for RAS, eye on your right hand side);
                                           1 (for RPS, eye on your left hand side))'
echo '          ThresholdForBET        (This is a parameter for fractional threshold in BET skull-stripping algorithm. 
                                    The range is [0,1]. The default one is 0.3. 
                                    The BET algorithm is used to refine the skull-stripping result. 
                                    If this parameter is selected as 0, BET algorithm will not used.'
echo '          n3 correction           (optinal:   default: 0, 1 is do n3)'
echo 'Example: SkullStrippingAndTissueSegmentationByEM AD.hdr Tmp_AD 0 1 0 1
      (The above is an example for ADNI data.)'
echo 'By Feng Shi at 06/16/09, comments and suggestions plz to fengshi@med.unc.edu'
exit
fi
echo 'Welcome to skullstripping'
echo 'Start running...'
# in this version, we use the embeded atlas of spm for adults



# initialize
startTime="$(date +%s)"
c=affine
d=07205st1
Sub="$1"
oldPath=$PWD
imagesize=(256 256 256)
# program path
    program=`echo ${0##*/}`
    # binPath=`echo ${0%*$program}`"bin/"
    binPath=/bricsfw/ideasfw/fSkullStrippingProgram/bin
    echo "bin path is $binPath"
    # recognize the path
    Sub=`echo ${1##*/}`
    if [ $1 == $Sub ] ; then
    newPath=$oldPath
    else
    newPath=${1%*$Sub}
    fi
    cd $newPath

# temparary folder
    if [ "$2". != . ] ; then Tmp="$2" ; else Tmp=tmp_skull ; fi
    if [ "$3". != . ] ; then Clean="$3" ; else Clean=0 ; fi
    if [ "$4". != . ] ; then Ori="$4" ; else Ori=0 ; fi
    if [ "$5". != . ] ; then BetT="$5" ; else BetT=0.3 ; fi
    if [ "$6". != . ] ; then N3="$6" ; else N3=0 ; fi
echo "Tmp=$Tmp, Clean=$Clean, Orientation=$Ori, BetThreshold=$BetT, N3=$N3"
if [ -d $Tmp ] ; then rm -r $Tmp ; fi
mkdir $Tmp ; cd $Tmp
pwd

# program begin
# To get image information for neo 
    input_Sub=${Sub%*.img}
    input_Sub=${input_Sub%*.hdr}
    # input_Sub=`echo $Sub | cut -d. -f1`
    input_SubHdr=$input_Sub".hdr"
    cp ../$input_Sub.hdr $input_Sub.hdr
    cp ../$input_Sub.img $input_Sub.img
    # Image 2: information
    echo "printavwheader ${input_SubHdr} "
    xdim_SubOri=`printavwheader ${input_SubHdr} | grep --text '^dim\[1\]' | cut -d\< -f2 | cut -d \> -f1`
    ydim_SubOri=`printavwheader ${input_SubHdr} | grep --text '^dim\[2\]' | cut -d\< -f2 | cut -d \> -f1`
    zdim_SubOri=`printavwheader ${input_SubHdr} | grep --text '^dim\[3\]' | cut -d\< -f2 | cut -d \> -f1`
    xres_SubOri=`printavwheader ${input_SubHdr} | grep --text '^pixdim\[1\]' | cut -d\< -f2 | cut -d \> -f1`
    yres_SubOri=`printavwheader ${input_SubHdr} | grep --text '^pixdim\[2\]' | cut -d\< -f2 | cut -d \> -f1`
    zres_SubOri=`printavwheader ${input_SubHdr} | grep --text '^pixdim\[3\]' | cut -d\< -f2 | cut -d \> -f1`
    if [ $xdim_SubOri != ${imagesize[0]} -o $ydim_SubOri != ${imagesize[1]} ] ; then
        echo "$xdim_SubOri $ydim_SubOri $zdim_SubOri not equal to ${imagesize[0]} ${imagesize[1]} ${imagesize[2]}"
        exist
    fi
    if [ ${xres_SubOri:0:1} == "-" ] ; then len=${#xres_SubOri} ; len=`expr $len - 1 ` ; xres_SubOri=${xres_SubOri:1:$len} ; fi
    if [ ${yres_SubOri:0:1} == "-" ] ; then len=${#yres_SubOri} ; len=`expr $len - 1 ` ; yres_SubOri=${yres_SubOri:1:$len} ; fi
    if [ ${zres_SubOri:0:1} == "-" ] ; then len=${#zres_SubOri} ; len=`expr $len - 1 ` ; zres_SubOri=${zres_SubOri:1:$len} ; fi
    makeavwheader ${input_SubHdr} -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -r$xres_SubOri,$yres_SubOri,$zres_SubOri -tSHORT
# # extract head
#     m=$input_Sub
#     usimageInfo $m.img -o $m-byte.img -x$xdim_SubOri -y$ydim_SubOri -z $zdim_SubOri -V$xres_SubOri,$yres_SubOri,$zres_SubOri -h99 -b
#     makeAVWHeader $m-byte.hdr -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -r$xres_SubOri,$yres_SubOri,$zres_SubOri -tCHAR
#     extractHead $m-byte.img $m-byte-head.img -O
#     cp $m-byte.hdr $m-byte-head.hdr
#     fslmaths $m.hdr -mas $m-byte-head.hdr $m-head.hdr

# reorient
    m=$input_Sub #-head
    if [ $Ori -eq 1 ] ; then
        fslswapdim $m.img -x -y z $m-reorient.img
        cp $m.hdr $m-reorient.hdr
    else
        cp -l $m.hdr $m-reorient.hdr
        cp -l $m.img $m-reorient.img
    fi
# n3
    cp $m-reorient.hdr $m-reorient-n3.hdr
    cp $m-reorient.img $m-reorient-n3.img
    if [ $N3 -eq 1 ] ; then
        adjustIntensityOver255ForN3Short $m-reorient-n3.img $m-reorient-n3.img $xdim_SubOri $ydim_SubOri $zdim_SubOri
        n3BiasCorrection.pl -i $m-reorient-n3.img -o $m-reorient-n3.img -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -v$xres_SubOri,$yres_SubOri,$zres_SubOri -g 100 -c1
        n3BiasCorrection.pl -i $m-reorient-n3.img -o $m-reorient-n3.img -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -v$xres_SubOri,$yres_SubOri,$zres_SubOri -g 100 -c1
        n3BiasCorrection.pl -i $m-reorient-n3.img -o $m-reorient-n3.img -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -v$xres_SubOri,$yres_SubOri,$zres_SubOri -g 100 -c1
    fi
# segment
    ln -s -f $m-reorient-n3.hdr 05st1.hdr
    ln -s -f $m-reorient-n3.img 05st1.img
    echo "Segmentation begin ..."
    matlab -nojvm -nosplash < "$binPath/"fspmNewSegmentAdult.m > test.out
    c3d c105st1.nii c105st1.img
    c3d c205st1.nii c205st1.img
    c3d c305st1.nii c305st1.img
    matlab -nojvm -nosplash < "$binPath/"fCombineSegmentImgLinuxBatch.m > test.out
    makeavwheader 05st1_seg.hdr -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -r$xres_SubOri,$yres_SubOri,$zres_SubOri -tCHAR

# remove artifacts
    m=05st1_seg
    "$binPath/"fRemoveArticfactsFindConvexHullV3.csh $m.hdr $input_Sub-reorient.hdr $m-mask_refine.hdr $BetT
    fslmaths $m.hdr -mas $m-mask_refine.hdr $m-seg_refine-first.hdr
    cp -l $m-seg_refine-first.hdr preArtifact.hdr
    cp -l $m-seg_refine-first.img preArtifact.img
    matlab -nojvm -nosplash < "$binPath/"topoCorrectOuterRingSliceBySliceBatch.m > nouse
    cp preArtifact-topo.img $m-seg_refine.img
    cp $m-seg_refine-first.hdr $m-seg_refine.hdr
    rm preArtifact.hdr preArtifact.img preArtifact-topo.img

# reorient back
    if [ $Ori -eq 1 ] ; then
        byte2short $m-seg_refine.img $m-seg_refine-short.img $xdim_SubOri $ydim_SubOri $zdim_SubOri
        makeavwheader $m-seg_refine-short.hdr -d$xdim_SubOri,$ydim_SubOri,$zdim_SubOri -r$xres_SubOri,$yres_SubOri,$zres_SubOri -tSHORT
        fslswapdim $m-seg_refine-short.img -x -y z $m-seg_refine-short-reorientBack.img
        cp $m-seg_refine-short.hdr $m-seg_refine-short-reorientBack.hdr
        short2byte $m-seg_refine-short-reorientBack.img $m-seg_refine-short-reorientBack-byte.img $xdim_SubOri $ydim_SubOri $zdim_SubOri 0
        cp $m-seg_refine.hdr $m-seg_refine-short-reorientBack-byte.hdr
        fslswapdim $m-mask_refine.hdr -x -y z $m-mask_refine-reorientBack.hdr
    else
        cp -l $m-seg_refine.hdr $m-seg_refine-short-reorientBack-byte.hdr
        cp -l $m-seg_refine.img $m-seg_refine-short-reorientBack-byte.img
        cp -l $m-mask_refine.hdr $m-mask_refine-reorientBack.hdr
        cp -l $m-mask_refine.img $m-mask_refine-reorientBack.img
    fi

# copy result up
    cp $m-seg_refine-short-reorientBack-byte.hdr ../${input_Sub}_seg.hdr
    cp $m-seg_refine-short-reorientBack-byte.img ../${input_Sub}_seg.img
    cp $m-mask_refine-reorientBack.hdr ../${input_Sub}_mask.hdr
    cp $m-mask_refine-reorientBack.img ../${input_Sub}_mask.img
# Clean
    cd ..
    if [ "$Clean" -eq 1 ] ; then rm -r $Tmp; echo "$Tmp folder is removed" ; fi
# back old dir
    cd $oldPath

# time elapsed
    endTime="$(date +%s)"
    usedTime=`expr $endTime - $startTime`
    echo "Total used $usedTime seconds"










