%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% RUN this script IN SECTIONS

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
%% load data
load('dataAll.mat')

%% plot the full curves wrapped around 0
itp = 35;
allc = nan(36,itp);
alldc = nan(36,itp);
allgn = nan(36,itp);

for i=1:36
    ac = data(i).an{:};
    agn = data(i).agn{:};
    dc = data(i).dc{:};
    FEn = data(i).FEn;
    ace = ac(FEn);
    x = [0:length(ac)-1];
    x = x - FEn;
    acnorm = wrapTo180(ac-ace);
    agnnorm = wrapTo180(agn-ace);
    if FEn-itp<1
        allc(i,end-FEn+1:end)=acnorm(1:FEn);
        allgn(i,end-FEn+1:end)=agnnorm(1:FEn);
        alldc(i,end-FEn+1:end)=dc(1:FEn);
    else
        allc(i,:)=acnorm(FEn-itp+1:FEn);
        allgn(i,:)=agnnorm(FEn-itp+1:FEn);
        alldc(i,:)=dc(FEn-itp+1:FEn);
    end

end

figure(1)
set(gcf,'color','w');
% subplot(1,2,1)
x = -itp+1:0;
x = 10.*x / 60; 
hold on

for i=1:itp
   iok = find(~isnan(allc(:,i)));
   mc(i) = mean(abs(allc(iok,i)));
   mgn(i) = mean(abs(allgn(iok,i)));
   sc(i) = std((allc(iok,i)));
   sgn(i) = std((allgn(iok,i)));
end

shaded_err = shadedErrorBar(x, mc, sc/2, '-b', 1);
shaded_err = shadedErrorBar(x, mgn, sgn/2, '-k', 1);
plot(x,90.*ones(itp,1),'--k')
plot(x,mc,'b','linewidth',3)
plot(x,mgn,'k','linewidth',3)

box on
xlabel('Time (hrs)')
ylabel('Mean angles normalized by ESCAPE direction')
xlim([-itp*10/60 0]);
ylim([0 180]);
set(gca,'FontSize',18,'fontweight','bold')

%% plot the average escape curve
itp = 35;
alldc = nan(36,itp);
alldn = nan(36,itp);

for i=1:36
    dc = data(i).dc{:};
    dn = data(i).dn{:};
    FEn = data(i).FEn;
    x = [0:length(ac)-1];
    x = x - FEn;
    if FEn-itp<1
        alldc(i,end-FEn+1:end)=dc(1:FEn);
        alldn(i,end-FEn+1:end)=dn(1:FEn);
    else
        alldc(i,:)=dc(FEn-itp+1:FEn);
        alldn(i,:)=dn(FEn-itp+1:FEn);
    end

end
for i=1:itp
   iok = find(~isnan(alldc(:,i)));
   mdc(i) = 0.108.*mean(abs(alldc(iok,i)));
   mdn(i) = 0.108.*mean(abs(alldn(iok,i)));
   sdc(i) = 0.108.*std((alldc(iok,i)));
   sdn(i) = 0.108.*std((alldn(iok,i)));
end

figure(2)
set(gcf,'color','w');
hold on
x = -itp+1:0;
x = 10.*x / 60; 

shaded_err = shadedErrorBar(x, mdn, sdn, '-k', 1);
plot(x,20.*ones(itp,1),'--k')
box on
xlabel('Time (hrs)')
ylabel('Distance (µm)')
xlim([-itp*10/60 0]);
ylim([0 25]);
set(gca,'FontSize',17,'fontweight','bold')
