#!/bin/sh
#
#  backward fourier transform, with MIRIAD
#  needs $image.rf, $image.if    or    $image.af, $image.pf
#  creates $image.rb.ri, $image.ib.ri or $image.rb.ap $image.ib.ap
#
# $Source: /u/vmcintyr/shellscripts/miriad/backward.sh,v $
# $Date: 2001/09/21 07:04:49 $
#
if [ $# -eq 0 ]; then
  echo "Usage: $0 miriadfile"
  echo "You should have two input files, miriadfile.rf & miriadfile.ri,"
  echo " or miriadfile.af & miriadfile.pf"
  exit 1
fi


image=$1
hasreal=0
hasimag=0
hasampl=0
hasphse=0

if [ -d "${image}.rf" ]; then hasreal=1; echo "Found real part ${image}.rf"; fi
if [ -d "${image}.if" ]; then hasimag=1; echo "Found imaginary part ${image}.rf"; fi
if [ -d "${image}.af" ]; then hasampl=1; echo "Found amplitude image ${image}.af"; fi
if [ -d "${image}.pf" ]; then hasphse=1; echo "Found phase image ${image}.pf"; fi
 
if [ $hasampl -eq 0 -o $hasphse -eq 0 ]; then
  if [ $hasreal -eq 0 -o $hasimag -eq 0 ]; then
    if [ $hasreal -eq 0 ]; then echo "Can't find real part $image"; fi
    if [ $hasimag -eq 0 ]; then echo "Can't find imaginary part $image"; fi
    echo "Giving up"
    exit 1
  else
    echo "Found real part ${image}.rf and imaginary part ${image}.if";
  fi
else
  echo "Found amplitude ${image}.af and phase ${image}.pf";
fi

if [ $hasampl -eq 0 -o $hasphse -eq 0 ]; then
  if [ $hasreal -eq 0 -o $hasimag -eq 0 ]; then
    if [ $hasampl -eq 0 ]; then echo "Can't find amplitude $image"; fi
    if [ $hasphse -eq 0 ]; then echo "Can't find phase part $image"; fi
    echo "Giving up"
    exit 1
  fi
fi

TMPDIR=/tmp/`basename $0`.$$;
LOG="${TMPDIR}/log"
ERR="${TMPDIR}/err"

mkdir $TMPDIR
touch -m $LOG
touch -m $ERR

DIRECTION='-1'
# outputs
realpart="${image}.rb"
imagpart="${image}.ib"
for d in $realpart $imagpart
do
  if [ -d $d ]; then
     echo "image $d exists; removing it."
     /bin/rm -rf $d
  fi
done


if [ $hasampl -gt 0 -a $hasphse -gt 0 ]; then
  echo "Using magnitude and phase"
  #make real & imaginary parts
  if [ $hasreal -gt 0 ]; then 
    echo "removing existing real-part image ${image}.rf"
    /bin/rm -rf ${image}.rf;
  fi
  if [ $hasimag -gt 0 ]; then 
    echo "removing existing imaginary-part image ${image}.if"
    /bin/rm -rf ${image}.if;
  fi
  maths exp="<${image}.af>*cos(<${image}.pf>)" out="${image}.rf" \
 1>> $LOG  2>>$LOG
  maths exp="<${image}.af>*sin(<${image}.pf>)" out="${image}.if" \
 1>> $LOG  2>>$LOG
fi

echo "transforming..."
fft rin="${image}.rf" iin="${image}.if" rout="$realpart" iout="$imagpart" \
    sign="$DIRECTION"  1>> $LOG  2>>$LOG
echo ""

if [ ! -d "$realpart" ]; then
  echo "Failed to create real part $realpart. Exiting.";
  exit 1
fi

if [ ! -d "$imagpart" ]; then
  echo "Failed to create imaginary part $imagpart. Exiting.";
  exit 1
fi

echo "Task complete"
echo "Created: $realpart, $imagpart"

/bin/rm -rf "$TMPDIR"
exit 0
