% resolution_calibrate.m
% returns a calibrated, linearized image and the chack image (marked ROIs)

function [STARCAL,Checkimage] = resoluton_calibrate(STAR,centerx,centery)


warning off MATLAB:polyfit:RepeatedPointsOrRescale

[h,w,d]=size(STAR);
dg=round(0.0733*h);  %width and height of gray patches
bh=round(0.1117*h);  %distance white marker to center of first gray patch
ds=round((7874/8504)*h); %calcuated diameter of star

CheckImage=STAR;

marker(1,1,1)=centerx(1)+ds/2;   % calculate position of marker around star1
marker(1,1,2)=centery(1)-ds/2;

marker(1,2,1)=centerx(1)-ds/2;
marker(1,2,2)=centery(1)-ds/2;

marker(1,3,1)=centerx(1)-ds/2;
marker(1,3,2)=centery(1)+ds/2;

marker(1,4,1)=centerx(1)+ds/2;
marker(1,4,2)=centery(1)+ds/2;


step1=bh;
step2=dg+bh;
x=ones(16);
x(1:4)=marker(1,1,1);  x(3)  =x(3)-step1;   x(4)=x(4)-step2;
x(5:8)=marker(1,2,1);  x(5)  =x(5)+step2;   x(6)=x(6)+step1;
x(9:12)=marker(1,3,1); x(11) =x(11)+step1;  x(12)=x(12)+step2;
x(13:16)=marker(1,4,1) ;x(13)=x(13)-step2;  x(14)=x(14)-step1;

y=ones(16);
y(1:4)  =marker(1,1,2); y(1)=y(1)+step2;   y(2)=y(2)+step1;
y(5:8)  =marker(1,2,2); y(7)=y(7)+step1;   y(8)=y(8)+step2;
y(9:12) =marker(1,3,2); y(9)=y(9)-step2;   y(10)=y(10)-step1;
y(13:16)=marker(1,4,2); y(15)=y(15)-step1; y(16)=y(16)-step2;

halfpatchsize=uint16((0.2*dg));

for i=1:16
    cam(i)=mean(mean(STAR(y(i)-halfpatchsize:y(i)+halfpatchsize,x(i)-halfpatchsize:x(i)+halfpatchsize)));
end

if max(diff(cam))>=0
    warndlg('LUT for calibration not nonotonic decreasing. Check Chart Orientation and gray patches!','Warning');
end

lin=[255 238 221 204 187 170 153 136 119 102 85 68 51 34 17 0];
lin=lin/255*round((max(cam)-min(cam))); %offset

pnorm=polyfit(cam,lin,4); %4th degree polnomial of cam-value
xl=0:255;
LUT=polyval(pnorm,xl); %calcuate LUT

STARCAL=intlut(STAR,uint8(LUT));

Checkimage=STAR;

for i=1:16
    Checkimage(y(i)-halfpatchsize:y(i)+halfpatchsize,x(i)-halfpatchsize:x(i)+halfpatchsize)=round(0.8*(255-cam(i)));
end
