#! /bin/csh -f
# Last edited on 1999-07-28 01:41:19 by stolfi

set usage = "$0 OTDIR RPT XPT YPT ZPT"

# Computes three orthogonal directions in the affine space
# spanned by four given points.
#
# The four points are read from files RPT XPT YPT ZPT;
# Each file has one coordinate per line, in the format
# COORD ITEM, where COORD is a real number and ITEM is any word 
# (ignored).  Copies the point RPT as file OTDIR/O.pos, and
# writes also three orthonormal vectors,
# OTDIR/{X,Y,Z}.dir, in the same format, which are 
# as close as possible to (XPT-RPT), (YPT-RPT), and (ZPT-RPT),
# in that order.

if ( $#argv != 5) then
  echo "usage: ${usage}"; exit 1
endif

set tmp = "/tmp/$$"

echo "Computing orthogonal basis..."

set otdir = "$1"; shift

cp -p $1 ${tmp}-R.pos; shift
cp -p $1 ${tmp}-X.pos; shift
cp -p $1 ${tmp}-Y.pos; shift
cp -p $1 ${tmp}-Z.pos; shift

compute-orthogonal-basis ${tmp}-{R,X,Y,Z}

mv ${tmp}-X.dir ${otdir}/X.dir
mv ${tmp}-Y.dir ${otdir}/Y.dir
mv ${tmp}-Z.dir ${otdir}/Z.dir

rm ${tmp}-*

echo "Tabulating axis coordinates..."

compare-counts \
  -titles 'X Y Z label' \
  -widths '7' \
  ${otdir}/{X,Y,Z}.dir

echo "Checking for orthonormality..."

foreach fg ( X.X X.Y X.Z Y.Y Y.Z Z.Z )
  set f = ${fg:r}
  set g = ${fg:e}
  /usr/ucb/echo -n "$f . $g = "
  join -j1 2 -j2 2 -o1.1,2.1,0 ${otdir}/${f}.dir ${otdir}/${g}.dir \
    | gawk '/./{s+=$1*$2;} END{printf "%+7.5f\n", s;}'
end