#!/bin/bash
#   Copyright (C) 2021 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 6.0 (c) 2018, The University of
#   Oxford (the "Software")
#
#   The Software remains the property of the Oxford University Innovation
#   ("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 Oxford
#   University Innovation ("OUI"), the technology transfer company of the
#   University, to negotiate a licence. Contact details are:
#   fsl@innovation.ox.ac.uk quoting Reference Project 9564, FSL.
export LC_ALL=C
set -e

if [ $# -lt 5 ] ; then
    echo "Usage:  `basename $0` <thresholded_binarised_WMH_map> <ventricles_mask> <minclustersize> <do_stats 0 1 2> <outputdir>"
    echo " This script separates WMH into periventricular and deep WMH, saves two separate binary images (perivent_map and deepwm_map) and calculates volume of total and separate WMHs"
    echo " Criterion = 10mm rule: a lesion within 10 mm (included) from the ventricles is classified as periventricular, otherwise as deep."
    echo "      INPUT 1: <thresholded_binarised_WMH_map>"
    echo " This script was created as postprocessing after WMH segmentation with BIANCA. The input file requested is BIANCA output thresholded at the desired threshold and binarised,  e.g. running:"
    echo "fslmaths BIANCA_output -thr 0.9 -bin BIANCA_out_thr09_bin"
    echo "and using BIANCA_out_thr09_bin as input for this script"
    echo "      INPUT 2: <ventricles_mask>"
    echo " If make_bianca_mask.sh was used to create an exlusion mask for BIANCA output, the ventricle mask to use is the file ventmask.nii.gz"
    echo " If T1 and FLAIR were not in the same space, ventricle mask needs to be registered to FLAIR (and binarised)"
    echo "      INPUT 3: minimum cluster (volume) size (in voxels) to consider"
    echo " Use 0 for no cluster thresholding"
    echo "      INPUT 4: <do_stats 0 1 2>"
    echo "if 0 it will only produce the images and not calculate volumes"
    echo "if 1 it will calculate volumes for total, periventricular and deep WMH and display on the screen"
    echo "if 2 it will calculate volumes and save them in the file WMH_tot_pvent_deep_10mm.txt"
    exit 0
fi

bianca_out_bin=$1
ventricle_mask=$2
minclustersize=$3
do_stats=$4
outdir=$5

outputdir=${outdir}/pwmh_dwmh_output
if [ ! -d $outputdir ]; then
    mkdir $outputdir
fi

# Cluster thresholding if needed
if [ ${minclustersize} -gt 0 ]; then
    # create indexed version of all the lesions in the mask (above minclustersize)
    cluster --in=$bianca_out_bin --thresh=0.05 --oindex=$outputdir/bianca_out_mincluster${minclustersize} --connectivity=6 --no_table --minextent=${minclustersize}
    fslmaths $outputdir/bianca_out_mincluster${minclustersize} -bin $outputdir/bianca_out_mincluster${minclustersize}
    bianca_out_bin=$outputdir/bianca_out_mincluster${minclustersize}
fi

# CRITERION: Distance from ventricles (10 mm)
distancemap -i $ventricle_mask -o $outputdir/deepwm_map_10mm
# If a lesion is within 10 mm (included) from the ventricles is periventricular, if not, it is deep.
# generating deep mask first by taking everything above 10.0001 (fslmaths -thr is inclusive) and generating pvent by subtraction from the original WMH.

fslmaths ${outputdir}/deepwm_map_10mm -mas $bianca_out_bin -thr 10.0001 -bin ${outputdir}/deepwm_map_10mm
fslmaths $bianca_out_bin -sub ${outputdir}/deepwm_map_10mm $outputdir/perivent_map_10mm

# volumes extraction
if [ $do_stats -gt 0 ]  ; then
    tot_vol=`fslstats $bianca_out_bin -V | awk '{print $2}'`
    pvent_vol_10mm=`fslstats $outputdir/perivent_map_10mm -V | awk '{print $2}'`
    deep_vol_10mm=`fslstats $outputdir/deepwm_map_10mm -V | awk '{print $2}'`

    if [ "$do_stats" == "2" ] ; then
	    echo $tot_vol $pvent_vol_10mm $deep_vol_10mm >>  $outputdir/WMH_tot_pvent_deep_10mm.txt
    elif [ "$do_stats" == "1" ] ; then
	    echo "tot_volume= $tot_vol DISTANCE10mm:pvent_vol_10mm= $pvent_vol_10mm deep_vol_10mm= $deep_vol_10mm "
    fi
fi
