%%% Plots gratings efficiency from GFW
fname = 'R2_1000_10deg_200fs';
phistepdeg=0.4;

Radius= 25/2; %mm
Length=230; %mm

fid=fopen(['/oxford/cauchy/' fname '.txt']);
txt=fread(fid);
fclose(fid);

% Component 9 is the sum of components 3-8
% Component 10 is the sliding sum of components 1-8


fnamerep=strrep(fname,'_',' ');
newline=strfind(char(txt'),10);

wavelength_array=zeros(1,180);
efficiencies_array=zeros(180,3,10);
efficiency_phi_weighted=zeros(180,10);
%start_wvl=30;
%end_wvl=170;

inewline=1;
wvl=90;
iwvl=1;
while ((wvl>0)&&(wvl<180))
    for ipol=1:3
        %           (char(txt(newline(inewline):newline(inewline+1))'))
        vals=str2num((char(txt(newline(inewline):newline(inewline+1))')));
        if (~isempty(vals))
            if (ipol==1)
                wavelength_array(iwvl)=vals(1);
                wvl=vals(1);
                efficiencies_array(iwvl,ipol,:)=vals(2:11);
            else
                efficiencies_array(iwvl,ipol,:)=vals(1:10);
               
            end% if
            inewline=inewline+1;
        else
            wvl=-1;
        end
    end %for
    iwvl=iwvl+1;
end %while wvl range

mwvl=iwvl-2;

figure(4)
clf
for ipol=1:3
    %figure(ipol)
    %clf
    subplot(3,1,ipol)
    hold on
    phi_weights=0;
    for ival=1:8
        if (mod(ival,3)==0)
            LineStyle='-';
        elseif (mod(ival,3)==1)
            LineStyle='--';
        else
            LineStyle=':';
        end
        plot(wavelength_array(1:mwvl),efficiencies_array(1:mwvl,ipol,ival),'Color',[0 1-((ival-1)/7) (ival-1)/7],'LineStyle',LineStyle)        
        efficiency_phi_weighted(1:mwvl,ipol)=efficiency_phi_weighted(1:mwvl,ipol)+efficiencies_array(1:mwvl,ipol,ival)*2*sqrt(Radius^2-(Length*sin((ival-1)*phistepdeg*pi/180))^2);
        phi_weights=phi_weights+2*sqrt(Radius^2-(Length*sin((ival-1)*phistepdeg*pi/180))^2);
    end %for ival
    efficiency_phi_weighted=efficiency_phi_weighted./phi_weights;
    plot(wavelength_array(1:mwvl),mean(efficiencies_array(1:mwvl,ipol,1:8),3),'Color',[0 1 0],'LineStyle','-')
    plot(wavelength_array(1:mwvl),efficiency_phi_weighted(1:mwvl,ipol),'Color',[1 0 0],'LineStyle','-')
    
    hold off
    xlabel('theta');
    ylabel('efficiency');
%    if (ipol==1)
    legend('Phi=0','2','3','4','5','6','7','Phi max','Avg','Wght avg','Location','EastOutside')
%    end %if 
    if (ipol==1)
        title(['Total -- ' fnamerep ' -- Phi step (deg)= ' num2str(phistepdeg)])
    elseif (ipol==2)
        title(['P1 -- ' fnamerep ' -- Phi step (deg)= ' num2str(phistepdeg)])
    else
        title(['P2 -- ' fnamerep ' -- Phi step (deg)= ' num2str(phistepdeg)])
    end
end  %for ipol


print('-dpng',['/Users/delerue/travail/svn/sp_upgrade/trunk/data_acquisition/gratings/gratings_efficiency_gfw_' fname '.png']);

