%%%Reads 2D plot from MC Grating for a given polarization

function [littrowWvl,littrowVal]=plot2DscanPol(filename,pitch,order)

%%% Code
fid=fopen(filename)
txt=fread(fid)';
fclose(fid)

end_line=strfind(txt, char(13));

angles_txt=((txt(24:end_line(1))))
char(angles_txt)
angles=str2num(char(angles_txt)) %#ok<ST2NM>

length(end_line)
wavelength=zeros(length(end_line)-1,1);
values=zeros(length(angles),length(wavelength));
for lloop=2:length(end_line)
    line=txt(end_line(lloop-1)+1:end_line(lloop)-1);
%    char(line)
    vals=str2num(char(line))
    wavelength(lloop-1)=vals(1);
 values(:,lloop-1)=vals(2:end);   
end% for

%figure(1)
%plot(wavelength)

%figure(2)
%plot(angles)

figure(3)
imagesc(values)

maxld=20;
ld=zeros(maxld,1);
wvl=zeros(maxld,1);
angleLittrow=zeros(maxld,1);

ld=2*(1:maxld)/(maxld+1)
wvl=ld*pitch
angleLittrow=asin(order*ld/2)*180/pi

figure(4)
plot(wvl,angleLittrow)
grid on

for ldloop=2:maxld-1
    thisWvlIdx=find(wavelength<wvl(ldloop), 1, 'last' );
    thisAngleIdx=find(angles<angleLittrow(ldloop), 1, 'last' );
%    wavelength(thisWvlIdx)
%    thisAngleIdx
    littrowWvl(ldloop)=wavelength(thisWvlIdx)
    littrowAngle(ldloop)=angles(thisAngleIdx)
    littrowVal(ldloop)=values(thisAngleIdx,thisWvlIdx)
end% for

figure(6)
plot(littrowWvl,littrowVal,'-')
