
clearvars
load_Path = 'Iron\ESR Maps\';

%% Input select filename

    [fname,pname] = uigetfile('*.cimg','Load file',load_Path); 
    file=[pname fname];                             

    fname = fname(1:end-5);
    
%% Open file  

    fid=0;                                          
    [fid,message] = fopen(file, 'r');
	if fid == -1
		disp(message)
    end

%% Extract Data    
    
hdr1 = strsplit(fgets(fid));    
hdr2 = strsplit(fgets(fid)); 

datatype = cell2mat(hdr1(2));
endianness = cell2mat(hdr1(3));

dx = str2num(cell2mat(hdr2(1)));
dy = str2num(cell2mat(hdr2(2)));
dv = str2num(cell2mat(hdr2(3)));

countcheck = dx*dy*dv;
[d,count] = fread(fid,'uint16','l');
ESRMatrix = permute(reshape(d,[dx,dy,dv]),[2,1,3]);

h = dy;w = dx;v = dv;

%% Close File 

clear d  %to prevent creation of files too heavy for no reason

fclose(fid);

%% Obtain frequency information

[pes,message] = fopen([pname fname '.pes'], 'r');
A = fscanf(pes,'%s');
[test,Amax]=size(A);

indvmid = findstr(A,'middle');
indvspan = findstr(A,'interval');
indvstep = findstr(A,'step');
indnumpoints = findstr(A,'points');

vmid = str2num(A(indvmid+16:indvspan-14));
vspan = str2num(A(indvspan+9:indvstep-16));
vstep = str2num(A(indvstep+5:indnumpoints-26));

fclose(pes);

v0 = vmid*1000 - vspan/2;

for indaxev = 1:v
    v_MHz (indaxev) = v0 + (indaxev-1)*vstep;
end

%% Plot one ESR spectrum

ix = 100; % in pixels
iy = 100; % in pixels    

spectre = squeeze(ESRMatrix(iy,ix,:))/max(1,mean(squeeze(ESRMatrix(iy,ix,1:10))));
    
fig = figure();

plot(v_MHz,spectre,'Color','Blue')
ax = gca;
%ylim([0.981 1.012])
%ax.YTick=[0.985;0.995;1.005];
xlim([v_MHz(1) v_MHz(v)])
ax.XAxisLocation = 'bottom';
ax.TickDir = 'out';
xlabel('\nu (MHz)');
ylabel('Renormalized Luminescence (au)','VerticalAlignment','bottom','HorizontalAlignment','center');   


