if [ $# -lt 1 ]; then 
echo ' ' 
echo '4DHAMMER_Reg '
echo 'input:  subject_ID          (i.e. file format ${Subj}0${i}_cbq.img)'
echo '        Total years         (optional;             default: 9)' 
echo '        XY_image size       ((optional;            default: 256)'
echo '        Iter                (optional;             default: 50)'
echo '        StepRatio           (optional;             default: 0.070)'
echo '        MatchThreshold      (optional;             default: 0.75)'
echo '        SmoothingTime       (optional;             default: 1)'
echo '        LaplSmooth_spatial  ((0.45~0.6)optional;   default: 0.58)'
echo '        LaplSmooth_temporal ((0.1~0.6) optional;   default: 0.58)'
echo '        -a                  ((optional;            default: no adaptive smoothing strategy)'
echo '        voxel resolution    ((optional;            default: 0.9375 0.9375 1.5)'
echo '        UseLowResolution    ((optional;            default: YYES; use NNO to skip low resolution)'
echo ''
exit
fi

#########################################################
## Register Inter-Brain Frames By 4D Deformation       ##
## File name requirement:                              ##
##    images: ??_cbq.img (name at '??' should be input ##
#########################################################


SubjFile="$1"


# total frame number
 Tyears="9" #total year
   if [ "$2". != . ]; 
   then
       Tyears="$2"
   fi 
 echo 'Total years = '$Tyears''

XY_img="256"
   if [ "$3". != . ]; 
   then
       XY_img="$3"
   fi 
   echo 'XY_img= '${XY_img}''

Iter="50"
 if [ "$4". != . ]; 
 then
 Iter="$4"
 fi 
  Low_Iter=`expr $Iter \* 1` #$Iter \*3
  Mid_Iter=`expr $Iter \* 1` #$Iter \*2
  HGH_Iter=$Iter
 Low_FnlID=`expr $Low_Iter - 1`
 echo 'Low_FnlID= '$Low_FnlID''
 Mid_FnlID=`expr $Mid_Iter - 1`
 echo 'Mid_FnlID= '$Mid_FnlID''
 HGH_FnlID=`expr $HGH_Iter - 1`
 echo 'HGH_FnlID= '$HGH_FnlID''

# Step Ratio
 StepRatio="0.070"
   if [ "$5". != . ]; 
   then
       StepRatio="$5"
   fi 
   echo 'StepRatio= '${StepRatio}''

# Matching Threshold
 MatchThreshold="0.75"
   if [ "$6". != . ]; 
   then
       MatchThreshold="$6"
   fi 
   echo 'MatchThreshold= '${MatchThreshold}''

SmthOption="-E1"
   if [ "$7". != . ]; 
   then
       SmthOption="-E$7"
   fi 
   echo 'SmthOption= '${SmthOption}''

# Laplacian coeff
 laplacianSpatialCoeff="0.58"
   if [ "$8". != . ]; 
   then
       laplacianSpatialCoeff="$8"
   fi 
   echo 'laplacianSpatialCoeff= '${laplacianSpatialCoeff}''

# laplacianTemporalCoeff
 laplacianTemporalCoeff=""
   if [ "$9". != . ]; 
   then
       laplacianTemporalCoeff="-L$9"
   fi 
   echo 'laplacianTemporalCoeff= '${laplacianTemporalCoeff}''

AdaptiveSmth=""
   if [ "${10}". != . ]; 
   then
       AdaptiveSmth="${10}"
   fi 
   echo 'AdaptiveSmth= '${AdaptiveSmth}''

# voxel size
   Vx="0.9375"
   Vy="0.9375"
   Vz="1.5"
   if [ "${11}". != . ]; 
   then
       Vx="${11}"
   fi 
    if [ "${12}". != . ]; 
    then
        Vy="${12}"
    fi 
     if [ "${13}". != . ]; 
     then
         Vz="${13}"
     fi 
   echo 'Voxel size= '${Vx}' '${Vy}' '${Vz}''

#UseLowResolution
  UseLowResolution="YYES"
   if [ "${14}". != . ]; 
   then
       UseLowResolution="${14}"
   fi 
   echo 'UseLowResolution= '${UseLowResolution}''



# brain images: all other year images are transformed to its previous year image
  echo ' ' 
  echo ' ' 
  echo ' ' 
  echo 'Self-transformation on subjects ... '
  echo '. '
  echo '. '
  if [ -f ${SubjFile}0${Tyears}_cbq.img.iso_y1 ]
  then
      echo '*** current subject image already self-aligned  ***'
  else
      # upsample Z-dimension -> .iso
      i="1"
        SubjOrigYY="${SubjFile}0${i}_cbq.img"    
	  SliceNo1st=`getFileSize ${SubjOrigYY}`
          SliceNo1st=`expr ${SliceNo1st} / ${XY_img} / ${XY_img} `
            echo 'org SliceNo1st= '${SliceNo1st}''
          SliceNo1st=`echo ${SliceNo1st} \* ${Vz}|bc -l `
            echo 'iso SliceNo1st= '${SliceNo1st}''
        Resample3dImg ${SubjOrigYY} ${SubjOrigYY}.iso_y1 -d${XY_img},${XY_img} -D${XY_img},${XY_img},${SliceNo1st} -r${Vx},${Vy},${Vz} -R1.0,1.0,1.0 

      negV="-10"
      posV="+10"
      i="2"
      while [ $i -le $Tyears ]
      do 
        echo 'i='$i''
        i_1=`expr $i - 1`	
         SubjOrigY_1="${SubjFile}0${i_1}_cbq.img"
         SubjOrigYY="${SubjFile}0${i}_cbq.img"

          cp ${SubjOrigYY}      AAA.img
	   SliceNo=`getFileSize AAA.img`
           SliceNo=`expr ${SliceNo} / ${XY_img} / ${XY_img} `
           makeaheader AAA.hdr 0 ${XY_img} ${XY_img} $SliceNo $Vx $Vy $Vz
          cp ${SubjOrigY_1}.iso_y1 BBB.img
	   SliceNo=`getFileSize BBB.img`
           SliceNo=`expr ${SliceNo} / ${XY_img} / ${XY_img} `
           makeaheader BBB.hdr 0 ${XY_img} ${XY_img} $SliceNo 1.0 1.0 1.0
          ./flirt -in AAA.hdr -ref BBB.hdr -out AtoB.hdr -omat AtoB.mat -bins 256 -cost leastsq -searchrx ${negV} ${posV} -searchry ${negV} ${posV} -searchrz ${negV} ${posV} -dof 6 -interp nearestneighbour
          FSLmat2Mymat AtoB.mat GlobalTransformation.Affine -r$Vx,$Vy,$Vz -R1.0,1.0,1.0
            \rm AAA.img AAA.hdr BBB.img BBB.hdr AtoB.*
          MakingSubjImgHaveSameSliceNoAsMdl ${SubjOrigYY} ${SubjOrigY_1}.iso_y1 ${XY_img} temp.img 
          Transform3DImg temp.img   ${SubjOrigYY}.iso_y1 -L -I -v${XY_img} 
            \rm temp.img 
          MatchHistogramsOfImgA2ImgB ${SubjOrigYY}.iso_y1 ${SubjOrigY_1}.iso_y1 ${SubjOrigYY}.iso_y1 -a${XY_img},${XY_img} -b${XY_img},${XY_img}

          cp GlobalTransformation.Affine  GlobalTransformation.Affine.Subj${i_1}ToLast
         i=`expr $i + 1`
      done
  fi



#rename file names for the generality of the following algorithm 
 i="1"
 while [ $i -le $Tyears ]
   do 
     echo 'i='$i''     
      cp "${SubjFile}0${i}_cbq.img.iso_y1" "Subj.img${i}"
     i=`expr $i + 1`
   done
SubjFile="Subj.img"


Low_rad="8" #4
Mid_rad="8" #8
HGH_rad="8" #8



#UseLowResolution="YYES" # NNO
if [ "$UseLowResolution" == YYES ] 
then
    echo '*** use low resolution ***'

    #Low resoultion: 4
    echo ' ' 
    echo '*******************************************************************' 
    echo 'Low resoultion:'
    echo '*******************************************************************' 
    echo 'Segmenting '$ImgFile' in low-resolution'
    InterBrainFramesRegistrationBy4DDeformation-HistMatch_V2.5 $SubjFile -R${StepRatio} -i$Low_Iter -r$Low_rad -m${MatchThreshold} -s4 -c0.5 -S${laplacianSpatialCoeff} ${laplacianTemporalCoeff}   -f${Tyears}   $SmthOption  -X${XY_img}  ${AdaptiveSmth} -Y #-Y

    i="0"
    while [ $i -lt $Tyears ]
       do 
         echo 'i='$i''
           mv Res.img.sample4.${Low_FnlID}.t${i}            Warped.org.img.4.t${i}
           splitfile DeformationField.float.img.t$i NoUse 8 Field.4.img.t$i
         i=`expr $i + 1`
       done 
    \rm Res.img.sample4.*


    #Mid resoultion: 2
    echo ' ' 
    echo '*******************************************************************' 
    echo 'Middle resoultion:'
    echo '*******************************************************************' 
    echo 'Segmenting '$ImgFile' in middle-resolution'

    InterBrainFramesRegistrationBy4DDeformation-HistMatch_V2.5 $SubjFile -R${StepRatio} -i$Mid_Iter -r$Mid_rad -m${MatchThreshold} -s2 -c0.5 -S${laplacianSpatialCoeff} ${laplacianTemporalCoeff}   -f${Tyears}   $SmthOption  -X${XY_img}  ${AdaptiveSmth} -Y  -F -C1.0

    i="0"
     while [ $i -lt $Tyears ]
       do 
         echo 'i='$i''
           mv Res.img.sample2.${Mid_FnlID}.t${i}            Warped.org.img.2.t${i}
           splitfile DeformationField.float.img.t$i NoUse 8 Field.2.img.t$i
         i=`expr $i + 1`
       done 
    \rm Res.img.sample2.*

else
    #*****************************************
    echo '*** low resolution is not used  ***'

    #Mid resoultion: 2
    echo ' ' 
    echo '*******************************************************************' 
    echo 'Middle resoultion:'
    echo '*******************************************************************' 
    echo 'Segmenting '$ImgFile' in middle-resolution'

    InterBrainFramesRegistrationBy4DDeformation-HistMatch_V2.5 $SubjFile -R${StepRatio} -i$Mid_Iter -r$Mid_rad -m${MatchThreshold} -s2 -c0.5 -S${laplacianSpatialCoeff} ${laplacianTemporalCoeff}   -f${Tyears}   $SmthOption  -X${XY_img}  ${AdaptiveSmth} -Y

    i="0"
     while [ $i -lt $Tyears ]
       do 
         echo 'i='$i''
           mv Res.img.sample2.${Mid_FnlID}.t${i}            Warped.org.img.2.t${i}
           splitfile DeformationField.float.img.t$i NoUse 8 Field.2.img.t$i
         i=`expr $i + 1`
       done 
    \rm Res.img.sample2.*
fi


    #High resoultion: 1
    echo ' ' 
    echo '*******************************************************************' 
    echo 'High resoultion:'
    echo '*******************************************************************' 
    echo 'Segmenting '$ImgFile' in high-resolution' 

    InterBrainFramesRegistrationBy4DDeformation-HistMatch_V2.5 $SubjFile -R${StepRatio} -i$HGH_Iter -r$HGH_rad -m${MatchThreshold} -s1 -c0.5 -S${laplacianSpatialCoeff} ${laplacianTemporalCoeff}   -f${Tyears}   $SmthOption  -X${XY_img}  ${AdaptiveSmth} -Y  -F -C1.0

     i="0"
     while [ $i -lt $Tyears ]
       do 
         echo 'i='$i''
           splitfile DeformationField.float.img.t$i NoUse 8 Field.1.img.t$i
         i=`expr $i + 1`
       done 
     \rm Res.img.sample1.*


# remove the files that are named in the previous step (resolution 2)
#\rm Warped.org.img.2.t?  Warped.org.img.2.t??
#\rm Field.4.img.t?  Field.2.img.t? Field.4.img.t??  Field.2.img.t??

#rm other files
\rm DeformationField.float.img*
\rm MdlImg_*
\rm ObjImg_*
\rm NoUse
\rm MDL.faces.hi



# Get deformation fields from current frame to next frame 
 i="1"
 while [ $i -lt $Tyears ]
   do
    echo 'i='$i''

     # subject to model 
     iP1=`expr $i + 1`

     mv Field.1.img.t${i}  Field.1.img.1to${iP1}
     PerformDeformationOnImgUsingVectorField Field.1.img.1to${iP1} ${SubjFile}${iP1} Warped.org.${iP1}to1.img -v${XY_img} -s${XY_img}

    i=`expr $i + 1`
   done


# Get reverse one 
 i="2"
 while [ $i -le $Tyears ]
   do
    echo 'i='$i''
      ReverseDeformationField Field.1.img.1to$i Field.1.img.1to${i}.reverse -X${XY_img}
      PerformDeformationOnImgUsingVectorField Field.1.img.1to${i}.reverse ${SubjFile}1 Warped.Mdl.$i -v${XY_img} -s${XY_img} -I
    i=`expr $i + 1`
   done


\rm Subj.img*

