stardat = { { 7001,   -0.356973,    1.055288, 196,  16},
{ 6705,   -0.189445,    0.842042, 166,  28},
{ 6705,   -0.189445,    0.842042, 168,  28},
{ 6132,    0.138650,    0.668621, 132,  42},
{ 5563,    0.368200,    0.431805, 118,  72},
{ 4301,    1.266475,    0.519088,  68,  94},
{  424,   -0.048869,    0.163723, 132, 106},
{  168,   -1.721590,    0.534734, 192, 150},
{  337,   -1.993223,    0.868234, 216, 190},
{  337,   -1.993223,    0.868234, 216, 192},
{  603,   -2.213898,    0.718355, 188, 196},
{ 1708,    3.079412,    0.594640, 106, 200},
{ 1708,    3.079412,    0.594640, 108, 200},
{ 1708,    3.079412,    0.594640, 106, 202},
{ 1708,    3.079412,    0.594640, 108, 202},
{  921,   -2.532149,    0.746113, 164, 214},
{  921,   -2.532149,    0.746113, 166, 214} }

nstars = Length[ stardat]
ix = Table[ i, {i, nstars}]
azimuths = Part[ stardat, ix, 2]
zenangs = Part[ stardat, ix, 3]
cols = Part[ stardat, ix, 4]
rows = Part[ stardat, ix, 5]

x0 = Cos[ -azimuths] Sin[ zenangs]
y0 = Sin[ -azimuths] Sin[ zenangs]

xp[ca_] := x0 Cos[ -ca] + y0 Sin[ -ca]
yp[ca_] := -x0 Sin[ -ca] + y0 Cos[ -ca]

rho[r_,k_] := r Sin[ k zenangs]
phi[ca_] := +ArcTan[ xp[ca], yp[ca]]

col[c0_,r_,k_,ca_] := c0 + rho[ r, k] Sin[ phi[ ca]]
row[r0_,r_,k_,ca_] := r0 - rho[ r, k] Cos[ phi[ ca]]

colerr[c0_,r_,k_,ca_] := cols - col[ c0, r, k, ca]
rowerr[r0_,r_,k_,ca_] := rows - row[ r0, r, k, ca]

sqerror[c0_,r0_,r_,k_,ca_] := colerr[ c0, r, k, ca]^2 +
			      rowerr[ r0, r, k, ca]^2

totsqerror[c0_,r0_,r_,k_,ca_] := Apply[ Plus,
			                sqerror[ c0, r0, r, k, ca]]

fit = FindMinimum[ totsqerror[c0,r0,r,k,ca], {c0,130.936},{r0,127.054},
                   {r,199.853},{k,0.642907},{ca,0.230475},
                   AccuracyGoal -> 6]

parms = Part[ fit, 2]

fc0 = Part[ parms, 1, 2]
fr0 = Part[ parms, 2, 2]
fr = Part[ parms, 3, 2]
fk = Part[ parms, 4, 2]
fca = Part[ parms, 5, 2]

error = Sqrt[ sqerror[fc0,fr0,fr,fk,fca]]
out=Transpose[ Partition[ Join[ Flatten[ Transpose[ stardat]], error], nstars]]

mse = "mean squared error = " <> ToString[ Part[ fit, 1] / nstars] <>
      " pixel^2"

OutputForm[ "Star  Azimuth  Zenith  Col Row   PixError"] >> results
OutputForm[ TableForm[ out, TableSpacing -> {0, 2}]] >>> results
OutputForm[ mse] >>> results
ColumnForm[ parms] >>> results

!!results
