#!/bin/sh

#   match_smoothing - empirical estimation of how much to smooth one image by to match another, in a third space
#
#   Stephen Smith, FMRIB Image Analysis Group
#
#   Copyright (C) 2008 University of Oxford
#
#   Part of FSL - FMRIB's Software Library
#   http://www.fmrib.ox.ac.uk/fsl
#   fsl@fmrib.ox.ac.uk
#   
#   Developed at FMRIB (Oxford Centre for Functional Magnetic Resonance
#   Imaging of the Brain), Department of Clinical Neurology, Oxford
#   University, Oxford, UK
#   
#   
#   LICENCE
#   
#   FMRIB Software Library, Release 5.0 (c) 2012, The University of
#   Oxford (the "Software")
#   
#   The Software remains the property of the University of Oxford ("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 Isis
#   Innovation Limited ("Isis"), the technology transfer company of the
#   University, to negotiate a licence. Contact details are:
#   innovation@isis.ox.ac.uk quoting reference DE/9564.
export LC_NUMERIC=C

res_resample() {
  IN=$1
  SMOOTH=$2
  NEWRES=$3

  # fill input with Gaussian noise and smooth spatially
  ${FSLDIR}/bin/fslmaths $IN -mul 0 -randn -s $SMOOTH $IN -odt float  

  # resample to required resolution
  XDIM=`${FSLDIR}/bin/fslval $IN dim1`
  YDIM=`${FSLDIR}/bin/fslval $IN dim2`
  ZDIM=`${FSLDIR}/bin/fslval $IN dim3`
  XPIXDIM=`${FSLDIR}/bin/fslval $IN pixdim1`
  YPIXDIM=`${FSLDIR}/bin/fslval $IN pixdim2`
  ZPIXDIM=`${FSLDIR}/bin/fslval $IN pixdim3`
  NEWXDIM=`echo "$XDIM 1 - $XPIXDIM * $NEWRES / p" | dc -`
  NEWYDIM=`echo "$YDIM 1 - $YPIXDIM * $NEWRES / p" | dc -`
  NEWZDIM=`echo "$ZDIM 1 - $ZPIXDIM * $NEWRES / p" | dc -`
  ${FSLDIR}/bin/fslcreatehd $NEWXDIM $NEWYDIM $NEWZDIM 1 $NEWRES $NEWRES $NEWRES 1 0 0 0 16 ${IN}_new
  ${FSLDIR}/bin/flirt -in ${IN} -ref ${IN}_new -out ${IN}_new -applyxfm

  # create image mask and run smoothest
  ${FSLDIR}/bin/fslmaths ${IN}_new -mul 0 -add 1 ${IN}_new_mask
  smoothness=`${FSLDIR}/bin/smoothest -z ${IN}_new -m ${IN}_new_mask | tail -n 1 | awk '{print $2}'`
}

Usage() {
    echo "Usage: match_smoothing <example_func> <func_smoothing_FWHM_in_mm> <example_structural> <standard_space_resolution>"
    echo "e.g.,  match_smoothing raw_fmri 5 structural 2"
    echo "The output is smoothing sigma needed to be applied to the structural data in its native space"
    exit 1
}

[ "$4" = "" ] && Usage

FUNC=$1
FUNCSMOOTH=`echo "10 k $2 2.355 / p" | dc -`
STRUC=$3
RES=$4

tmp=`${FSLDIR}/bin/tmpnam`
/bin/rm $tmp  # remove empty tmp file

${FSLDIR}/bin/fslroi $FUNC $tmp 0 1
res_resample $tmp $FUNCSMOOTH $RES
func_smoothness=$smoothness
#echo Functional data: 1 resel = $func_smoothness standard-space voxels

${FSLDIR}/bin/fslroi $STRUC $tmp 0 1
SMOOTH_LOW=0.1
SMOOTH=2
SMOOTH_LAST=1000000
SMOOTH_HIGH=20
while [ `echo "$SMOOTH $SMOOTH_LAST - $SMOOTH $SMOOTH_LAST - * 100 * 1 / p" | dc -` -ne 0 ] ; do
  SMOOTH_LAST=$SMOOTH
  res_resample $tmp $SMOOTH $RES
  #echo Smoothing structural by $SMOOTH gives 1 resel = $smoothness standard-space voxels
  if [ `echo "$smoothness $func_smoothness - 1 / p" | dc -` -le 0 ] ; then
    SMOOTH_LOW=$SMOOTH
    SMOOTH=`echo "2 k $SMOOTH_HIGH $SMOOTH - 2 / $SMOOTH + p" | dc -`
  else
    SMOOTH_HIGH=$SMOOTH
    SMOOTH=`echo "2 k $SMOOTH $SMOOTH_LOW - 2 / $SMOOTH_LOW + p" | dc -`
  fi
done

/bin/rm ${tmp}*

echo $SMOOTH
exit 0

