% load ETMX images

clear all
%EY HWS
%cd ./HWS_image_plane_Y
%files = dir('*yaw0*.raw');  %start at HWS location = 0 inches
%files = dir('*yaw2*.raw');  %moved ETMY HWS forward one inch. (+ 1 inch)
%files = dir('*yaw3*.raw');  %move ETMY HWS back 2 inches from current location.b (-1 inch)
%files = dir('*yaw4*.raw');   %moved forward 3 inches (+2 inches)
%files = dir('*yaw5*.raw');  %moved HWS 2 inches forward, to +4inches.
%moved HWS back to origonal location

%EX HWS
cd ./HWS_image_plane_X
%files = dir('*yaw1*.raw');  %start at HWS location = 0 inches
files = dir('*yaw2*.raw');  %moved backwards 2 inches
%from 1 and two expect 2 inches per pixel.
%files = dir('*yaw3*.raw');  %moved last two mirrors 3 inches towards HWS
%moved two mirrors bac to origonal location, left HWS as is.

dpix=12e-6; %pixel diameter micrometers
%close all
xc = [];
arrM = zeros(1024,1024);
M=20; %magnification nominal
Ainj=2e-6; %injection amplitude of 2 microradians
wL= [];
for ii = 1:numel(files)
	   fid = fopen(files(ii).name, 'r');
arr = fread(fid, [1024, 1024], 'uint16')';
fclose(fid);
figure(0704)   
imagesc(arr)
   title(files(ii).name)
   x = 1:1024;
   int1 = mean(arr-50);
   xc = [xc; sum(int1.^2.*x)/sum(int1.^2)];
  % disp(xc(end))
  % pause(0.005)
   
   arrM = arrM + arr;
   

    m1 = mean(arr');
    m2 = m1 - min(m1);
    x = 1:1024;
    xc1 = sum(m2.^2.*x)/sum(m2.^2);
    wx = sqrt(sum(m2.*(x-xc1).^2)/sum(m2));
    wL = [wL; wx];

end

%close all
figure
plot(xc)
%disp(max(xc) - min(xc))
% locate minima and find average minima
a0 = -mean(findpeaks(-xc, 'MINPEAKDISTANCE', 30));
% locate maxima and find average maxima
a1 = mean(findpeaks(xc, 'MINPEAKDISTANCE', 30));
% display the 
disp(['The pk-pk oscillation was ', num2str(a1 - a0), ' pixels'])
disp('')

xpkpk=(a1-a0)*dpix; %peak to peak movement of spot on HWS, [m]
HWS2conj=xpkpk/4/M/Ainj;
ETM2conj=M*xpkpk/4/Ainj;
disp(['The distance from the ETM to the conjugate plane is ' num2str(ETM2conj) ' [m].'])
disp(['The distance from the HWS to the conjugate plane is ' num2str(HWS2conj) ' [m].'])

%close all
figure(1704)
imagesc(arr)
colorbar





