#!/bin/sh
#
#  divide two complex images
#  needs $a.r $a.i and $b.r, $b.i    or    $image.af, $image.pf
#  creates $c.r, $c.i
#
# $Source: /u/vmcintyr/shellscripts/miriad/backward.sh,v $
# $Date: 2001/09/21 07:04:49 $
#
if [ $# -ne 4 ]; then
  echo "Usage: `basename $0` <a_real> <a_imag> <b_real> <b_imag>"
  echo "You should have four input files, in miriad format."
  exit 1
fi

ar=$1; ai=$2; br=$3; bi=$4;
for d in $ar $ai $br $bi
do
   if [ ! -d $d ]; then
     echo "Can't find image $d, exiting";
     exit 1
   fi
done

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

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

# outputs
realpart='quotient.r';
imagpart='quotient.i';
for d in $realpart $imagpart
do
  if [ -d $d ]; then
     echo "image $d exists; removing it."
     /bin/rm -rf $d
  fi
done

#expression is
#  x + yi     (xu + yv) + (yu - xv)i
#  ------  = ------------------------
#  u + vi         u*u + v*v
#http://www.clarku.edu/~djoyce/complex/
#
maths exp="(<${br}>*<${br}>)+(<${bi}>*<${bi}>)" out="${TMPDIR}/bottom"   \
                                                         1>> $LOG 2>> $ERR
maths exp="(<${ar}>*<${br}>)+(<${ai}>*<${bi}>)" out="${TMPDIR}/topreal"\
                                                         1>> $LOG 2>> $ERR
maths exp="(<${ai}>*<${br}>)-(<${ar}>*<${bi}>)" out="${TMPDIR}/topimag"\
                                                         1>> $LOG 2>> $ERR

maths exp="<${TMPDIR}/topreal>/<${TMPDIR}/bottom>" out="${realpart}" \
      mask="<${TMPDIR}/bottom>.gt.0"                     1>> $LOG 2>> $ERR
maths exp="<${TMPDIR}/topimag>/<${TMPDIR}/bottom>" out="${imagpart}" \
      mask="<${TMPDIR}/bottom>.gt.0"                     1>> $LOG 2>> $ERR


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

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