stardat = { { 2088,    0.462007,    0.939054,  76,  28},
{ 1708,    0.625600,    0.903839,  62,  40},
{ 4301,   -0.610130,    0.626531, 172,  66},
{ 1017,    1.039128,    0.775751,  44,  82},
{  921,    1.171581,    0.950528,  20,  84},
{ 5054,   -1.174959,    0.660997, 204,  98},
{  424,    0.072931,    0.175706, 122, 106},
{ 5191,   -1.313395,    0.737991, 216, 106},
{  424,    0.072931,    0.175706, 126, 108},
{  603,    1.411056,    0.846265,  24, 112},
{ 5563,   -1.181451,    0.292646, 160, 116},
{ 5563,   -1.181451,    0.292646, 162, 116},
{  168,    1.657630,    0.545496,  58, 136},
{  337,    1.675298,    0.919954,  14, 140},
{  337,    1.675298,    0.919954,  14, 142},
{  337,    1.675298,    0.919954,  16, 142},
{ 8162,    2.642423,    0.319029, 108, 166},
{ 6705,   -2.447526,    0.530372, 170, 182},
{ 8775,    2.273902,    0.963048,  36, 206},
{ 8775,    2.273902,    0.963048,  38, 206},
{ 7001,   -2.703321,    0.734242, 166, 212},
{ 7001,   -2.703321,    0.734242, 166, 214},
{ 7796,    3.036578,    0.695376, 118, 216} }

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
