function outline, mask, n {
  outline = shift(mask, n, 0)
  outline += shift(mask, 0, n)
  outline += shift(mask, -n, 0)
  outline += shift(mask, 0, -n)
  clip outline, 0, 1
  outline -= mask
}

function preparediff, fnames {
med_size_im=1    // ***pixel for median smoothing of Diff image

Diff = readfits(fnames[2])-readfits(fnames[1])
Diff -= median(Diff)

preparediff=boxcar(Diff,med_size_im,/median)
}

function preparemask, MaskIm {
highval=10000
Mask=boxcar(MaskIm,1,/median)

highpos=where(Mask > highval)
Lowpos=where(Mask <= highval)

Mask[highpos]=1
Mask[Lowpos]=0

preparemask = Mask
}

function preparesim, Diff, Mask {
preparesim = Diff + 2 * max(Diff) * Mask
}

function offsets, cent, Diff, MaskIm, luci {
mem
offsets = 1
med_size=3    // ***pixel for median smoothing of mask
gauss_width=4 // ***npix FWHM for gaussian smoothing of mask

//Mim = boxcar(MaskIm,med_size,/median)

//Gim = smooth(Mim, gauss_width)


starcent = maskcent = fits(2, int(naxis2(cent)/2))

j = 1
for (i = 1; i <= naxis2(cent); i += 2) {
  starcent[*,j] = cent[*,i]
  maskcent[*,j] = cent[*,i+1]
  j++
}

//starcent = markpos(Sim)
//starcent=centroids(Diff, starcent, 8) // could also use gausspos
starcent = gausspos(Diff, maxima(Diff, starcent, 8), 5)

//'StarCenters.fits' = starcent
//view Mask,/log,/scale95
//message "Please mark mask positions in the same order"
//maskcent = markpos(Mask)
//maskcent = centroids(Gim, maskcent, 50)
maskcent = centroids(MaskIm, maskcent, 50)

//'MaskCenters.fits' = maskcent

CRpix=[1009.5,1033.4]   // **center of rotation pixel  Luci1

Pixscale1=0.1178     // arcsec per pix Luci1
Pixscale2=0.1190     // arcsec per pix Luci2

Pixscale = Pixscale1

N_stars=naxis2(starcent)

angle_matrix_ref=floatarray(N_stars,N_stars)
angle_matrix_im=floatarray(N_stars,N_stars)

ref=maskcent-1
im=starcent-1      // convert to idl coordinates....not needed due to differnces only count

im_rot=floatarray(2,N_stars)
im_S=floatarray(2,N_stars)



for k=1,N_stars {  
  for L=1,N_stars {
    
  angle_matrix_ref[k,L]=atan((ref[2,k]-ref[2,L]) / (ref[1,k]-ref[1,L]))
  angle_matrix_im[k,L]=atan((im[2,k]-im[2,L]) / (im[1,k]-im[1,L]))  
  
  }
}
  
angle_diff=angle_matrix_ref-angle_matrix_im
angle=avg(angle_diff)

d_angle=angle

// derotate the measured coordinates:
// shift the coordinate system onto center of rotation first:

im_S[1,*]=im[1,*]-CRpix[1]
im_S[2,*]=im[2,*]-CRpix[2]

// rotate
for k=1,N_stars {
  
  im_rot[1,k]=im_S[1,k]*cos(d_angle)-im_S[2,k]*sin(d_angle)
  im_rot[2,k]=im_S[1,k]*sin(d_angle)+im_S[2,k]*cos(d_angle)    
  
}
  
// shift back:
im_S[1,*]=im_rot[1,*]+CRpix[1]
im_S[2,*]=im_rot[2,*]+CRpix[2]  

// X Y shifts
diff_rot=ref-im_S


print "angles "
print angle_diff, /values
print "mean_angle in rad " + angle*(-1)
print "mean_angle in Grad " + rad2deg(angle)*(-1)

print ""
print "single shift values"
print diff_rot, /values

print "mean X shift rot " + avg(diff_rot[1,*])
print "mean Y shift rot " + avg(diff_rot[2,*])

print "median X shift rot " + median(diff_rot[1,*])
print "median Y shift rot " + median(diff_rot[2,*])
print ""

print "DetXY offsets / rotation to apply"
print ""
print "mean_angle in Grad " + rad2deg(angle)*(-1)
print ""
if (luci == 1) {
print "median X shift LUCI1 " + median(diff_rot[1,*])*Pixscale1
print "median Y shift LUCI1 " + median(diff_rot[2,*])*Pixscale1
} else {
print "median X shift LUCI2 " + median(diff_rot[1,*])*Pixscale2
print "median Y shift LUCI2 " + median(diff_rot[2,*])*Pixscale2
Pixscale = Pixscale2
}
print ""
mem
offsets = [median(diff_rot[1,*])*Pixscale, median(diff_rot[2,*])*Pixscale, rad2deg(angle)*(-1), median(diff_rot[1,*]), median(diff_rot[2,*])]
}

procedure createxml, luci1dx, luci1dy, luci1dphi, luci2dx, luci2dy, luci2dphi {
output = stringarray(0)

useluci1 = 0
if (luci1dx != 0 || luci1dy!= 0 || luci1dphi != 0) useluci1 = 1
useluci2 = 0
if (luci2dx != 0 || luci2dy!= 0 || luci2dphi != 0) useluci2 = 1

if (useluci1 != 0 || useluci2 != 0) {
output += "<observationItem idItem=\"1\">"
output += "    <!--"
output += "    Label of the observation item. Keep string: ARGOS aquisition to identify a source of item."
output += "    -->"
output += "    <label>ARGOS acquisition</label>"
if (useluci1 != 0 && useluci2 != 0) {
output += "    <itemType>REGULAR</itemType>"
} else {
output += "    <itemType>ACQUISITION_REALTIME</itemType>"
}
output += "    <useBinocularMode>false</useBinocularMode>"
output += "    <synchronizeInstruments>false</synchronizeInstruments>"
output += "    <!--"
output += "    Stop LUCI2 side after this ARGOS correction. Put false if we do not want stop after correction."
output += "    LUCI SW RTD has false for pause."
output += "    If usageType attribute NULL or empty, apply pause for LUCI1 and LUCI2 sides."
output += "    If usageType attribute specified, apply pause just for given side. "
output += "    -->"
output += "    <telescope>"
output += "        <mirrors>"
if (useluci1 != 0) {
output += "            <!--"
output += "            Apply correction for LUCI1 side."
output += "            -->"
output += "            <mirror usageType=\"1\">"
output += "                <!--"
output += "                Here it is relative XY"
output += "                -->"
output += "                <offset absoluteOffset=\"false\" equatorialCoordinate=\"false\">"
output += "                    <coord>" + luci1dx + "</coord>"
output += "                    <coord>" + luci1dy + "</coord>"
output += "                </offset>"
output += "                <rotationAngleOffset absoluteOffset=\"false\">" + luci1dphi + "</rotationAngleOffset>"
output += "                <updatePointingOrigin equatorialCoordinate=\"false\">true</updatePointingOrigin>"
output += "                <guideStarsAuto>false</guideStarsAuto>"
output += "            </mirror>"
}
if (useluci2 != 0) {
output += "            <mirror usageType=\"2\">"
output += "                <!--"
output += "                Here it is relative XY"
output += "                -->"
output += "                <offset absoluteOffset=\"false\" equatorialCoordinate=\"false\">"
output += "                    <coord>" + luci2dx + "</coord>"
output += "                    <coord>" + luci2dy + "</coord>"
output += "                </offset>"
output += "                <rotationAngleOffset absoluteOffset=\"false\">" + luci2dphi + "</rotationAngleOffset>"
output += "                <updatePointingOrigin equatorialCoordinate=\"false\">true</updatePointingOrigin>"
output += "                <guideStarsAuto>false</guideStarsAuto>"
output += "            </mirror>"
}
output += "        </mirrors>"
output += "    </telescope>"
output += "</observationItem>"

export "/tmp/lucioffset.xml", output
exec "/lbt/lucifer/lcsp/bin/commitXML.sh insert /tmp/lucioffset.xml"
}
}
