#!/bin/bash

###############################################################################

ct="(cos(tau*pi()/180.0))"
st="(sin(tau*pi()/180.0))"
cd="(cos(dec*pi()/180.0))"
sd="(sin(dec*pi()/180.0))"

ct0="(cos(tt*pi()/180.0))"
st0="(sin(tt*pi()/180.0))"
cd0="(cos(dd*pi()/180.0))"
sd0="(sin(dd*pi()/180.0))"

fx="+b0*$sd-c0*$cd*$st+d0*$sd*$st+e0*$sd*$ct-f0*$st"
fy="-a0*$sd+c0*$cd*$ct-d0*$sd*$ct+e0*$sd*$st+f0*$ct"
fz="+a0*$cd*$st-b0*$cd*$ct-e0*$cd"

# $cd*$st, $cd*$ct, $sd

y1="($cd*$st)"
y2="($sd)"
y3="($cd*$ct)"
y4="($cd*$cd*2*$st*$ct)"
y5="($cd*$sd*$st)"
y6="(3*$sd*$sd-1)"
y7="($cd*$sd*$ct)"
y8="($cd*$cd*($ct*$ct-$st*$st))"

fx="$fx+b1*$y1*$sd-c1*$y1*$cd*$st+d1*$y1*$sd*$st+e1*$y1*$sd*$ct-f1*$y1*$st"
fy="$fy-a1*$y1*$sd+c1*$y1*$cd*$ct-d1*$y1*$sd*$ct+e1*$y1*$sd*$st+f1*$y1*$ct"
fz="$fz+a1*$y1*$cd*$st-b1*$y1*$cd*$ct-e1*$y1*$cd"

fx="$fx+b2*$y2*$sd-c2*$y2*$cd*$st+d2*$y2*$sd*$st+e2*$y2*$sd*$ct-0*$y2*$st"
fy="$fy-a2*$y2*$sd+c2*$y2*$cd*$ct-d2*$y2*$sd*$ct+e2*$y2*$sd*$st+0*$y2*$ct"
fz="$fz+a2*$y2*$cd*$st-b2*$y2*$cd*$ct-e2*$y2*$cd"

fx="$fx+b3*$y3*$sd-c3*$y3*$cd*$st+d3*$y3*$sd*$st+e3*$y3*$sd*$ct-f3*$y3*$st"
fy="$fy- 0*$y3*$sd+c3*$y3*$cd*$ct-d3*$y3*$sd*$ct+e3*$y3*$sd*$st+f3*$y3*$ct"
fz="$fz+ 0*$y3*$cd*$st-b3*$y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($cd*$st-$cd0*$st0)"
yz="($sd-$sd0)"

cdef=tau:1,dec:2,tt:3,dd:4

# b8, a8, f7, a7, f6, f5


cat	pointing.txt | \
lfit	-v a0,b0,c0,d0,e0,f0,a1,b1,c1,d1,e1,f1,a2,b2,c2,d2,e2,b3,c3,d3,e3,f3 \
	-v a4,b4,c4,d4,e4,f4,a5,b5,c5,d5,e5 \
	-v a6,b6,c6,d6,e6,b7,c7,d7,e7,c8,d8,e8,f8 \
	-F a0=%9.6f,b0=%9.6f,c0=%9.6f,d0=%9.6f,e0=%9.6f,f0=%9.6f \
	-F a1=%9.6f,b1=%9.6f,c1=%9.6f,d1=%9.6f,e1=%9.6f,f1=%9.6f \
	-F a2=%9.6f,b2=%9.6f,c2=%9.6f,d2=%9.6f,e2=%9.6f \
	-F b3=%9.6f,c3=%9.6f,d3=%9.6f,e3=%9.6f,f3=%9.6f \
	-F a4=%9.6f,b4=%9.6f,c4=%9.6f,d4=%9.6f,e4=%9.6f,f4=%9.6f \
	-F a5=%9.6f,b5=%9.6f,c5=%9.6f,d5=%9.6f,e5=%9.6f \
	-F a6=%9.6f,b6=%9.6f,c6=%9.6f,d6=%9.6f,e6=%9.6f \
	-F b7=%9.6f,c7=%9.6f,d7=%9.6f,e7=%9.6f \
	-F c8=%9.6f,d8=%9.6f,e8=%9.6f,f8=%9.6f \
	-ix - -cx $cdef -fx "$fx" -yx "$yx" -ex 0.000013 \
	-iy - -cy $cdef -fy "$fy" -yy "$yy" -ey 0.000013 \
	-iz - -cz $cdef -fz "$fz" -yz "$yz" -ez 0.000013 \
	--err --residual 


###############################################################################

