#!/bin/sh

if [ $# -lt 2 ] ; then 
  echo "Usage: `basename $0` <input_image> <output_image>"
  echo " "
  echo "`basename $0` is a tool for reorienting the image to match the"
  echo "approximate orientation of the standard template images (MNI152)."
  echo "It only applies 0, 90, 180 or 270 degree rotations."
  echo "It is not a registration tool."
  echo "It requires NIfTI images with valid orientation information"
  echo "in them (seen by valid labels in FSLView).  This tool"
  echo "assumes the labels are correct - if not, fix that before using this."
  echo " "
  exit 1
fi

img=`$FSLDIR/bin/remove_ext $1`;
outimg=$2;

if [ `$FSLDIR/bin/imtest $img` = 0 ] ; then
  echo "ERROR: Could not find image $1"
  exit 2
fi

scode=`$FSLDIR/bin/fslorient -getsformcode $img`;
qcode=`$FSLDIR/bin/fslorient -getqformcode $img`;
if [ $scode = 0 -a $qcode = 0 ] ; then
  echo "ERROR: Orientation information not stored in ${1}!"
  echo "Cannot reslice without orientation information (i.e. need valid labels in FSLView)"
  echo "The NIfTI image must contain a non-zero code for either the sform or the qform"
  echo " - check your reconstruction/conversion software to try and fix this"
  exit 3
fi

hand=`$FSLDIR/bin/fslorient -getorient $img`;
if [ $hand = RADIOLOGICAL ] ; then
    $FSLDIR/bin/fslswapdim $img RL PA IS $outimg
else
    $FSLDIR/bin/fslswapdim $img LR PA IS $outimg
fi
