close all
clear all

time_offset_from_intake = 120;  %delay between intake and delivery to instrument in seconds.

bin_width = 4;

bins = 0:bin_width:40;
bins = bins(1:end-1)+bin_width/2;  %Convert specified bin edges to bin centers for use with hist.

CastDepths = load('DepthRecord');


ProcessedDataPath = '000000_ProcessedData/';
LabProcessedDataPath = '0000_LabProcessedData/';

files = dir([ProcessedDataPath '*_summary_export.csv']);

plot_num = 0;
hists_per_page = 8;
page_num = 0;

for i =  1:length(files)
   
   num_str{i} = files(i).name(1:10);
   
   hr_str{i} = files(i).name(5:6);
   min_str{i} = files(i).name(7:8);
   sec_str{i} = files(i).name(9:10);

   
   summary_data{i} = ReadSummaryExport([ProcessedDataPath files(i).name]);
   
   ParticlesPerml(i) = summary_data{i}.ParticlesPerml 

   
   DateNumStartTime(i) = datenum(summary_data{i}.StartTime)+6/24-time_offset_from_intake/86400;  %Convert to UTC including 1Hr offset of FlowCam clock. (UTC is +7, but clock was one hour fast during April 2nd, 2014 cruise...)
   DateNumTime(i) = datenum(2014,4,2,str2double(hr_str{i}),str2double(min_str{i}),str2double(sec_str{i}))+6/24-time_offset_from_intake/86400; 
   
   SamplingSeconds(i) = summary_data{i}.SamplingSeconds;
   
   
   [data{i}, headertext{i}] = xlsread([ProcessedDataPath num_str{i} '_data_export.csv']);
   
   ESD{i} = data{i}(:,11);
   
   [nelements_ESD{i},centers_ESD{i}] = hist(data{i}(:,11),bins)
     
   n_part_per_ml{i} = [ParticlesPerml(i)*nelements_ESD{i}/sum(nelements_ESD{i})];
   
   plot_num = plot_num+1;
   if(plot_num > hists_per_page) 
       plot_num = 1; 
   end
   if(plot_num == 1) 
     figure('Position', [705 72 1138 1426],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
   end
   subplot(hists_per_page/2,2,plot_num)
   bar(centers_ESD{i},n_part_per_ml{i},1);
   xlabel('Particle Size (ESD - microns)');
   ylabel('Particles per ml');
   title([num2str(SamplingSeconds(i)) ' sec sample starting at ' datestr(DateNumTime(i)) '  Particles per ml = ' num2str(ParticlesPerml(i))]);
   if(plot_num == hists_per_page) 
     page_num = page_num+1;
     print('-dpdf',['04022014_ESD_Histogram_Pg_' num2str(page_num)]);
   end
      
end
   page_num = page_num+1;
   print('-dpdf',['04022014_ESD_Histogram_Pg_' num2str(page_num)]);  %Print leftovers.


jdx = find((ParticlesPerml < 4500) & (SamplingSeconds > 60));
for m = 1:length(jdx)
   stripped_n_part_per_ml{m} = n_part_per_ml{jdx(m)}; 
end

   
figure('Position',[1000 297 1035 1201],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
ah1 = subplot(3,1,1)
set(ah1,'FontSize',14);
plot(CastDepths.all_time,-CastDepths.all_depth,'-x');
datetick('x');
xlabel('time (UTC)');
ylabel('depth (m)');
title('April 2nd, 2014  -  All Casts');
ah2 = subplot(3,1,2)
set(ah2,'FontSize',14);
plot(DateNumTime(jdx),ParticlesPerml(jdx),'x')
datetick('x');
ylabel('Particles Per ml Detected');
xlabel('time (UTC)');

ah3 = subplot(3,1,3)
set(ah3,'FontSize',14);
plot(DateNumTime(jdx),SamplingSeconds(jdx),'x')
datetick('x');
ylabel('Sample Length (seconds)');
xlabel('time (UTC)');

linkaxes([ah1 ah2 ah3],'x');

print('-dpdf','SampleLengthVersusTime');



for i = 1:length(bins)-1
  legend_str{i} = [num2str(bins(i)) ' - ' num2str(bins(i+1)) ' microns (ESD)'];
end
figure('Position',[1000 297 1035 1201],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
ah1 = subplot(2,1,1)
plot(CastDepths.all_time,-CastDepths.all_depth,'-x');
datetick('x');
xlabel('time (UTC)');
ylabel('depth (m)');
title('April 2nd, 2014  -  All Casts');
set(ah1,'FontSize',14);
ah2 = subplot(2,1,2)

plot(DateNumTime(jdx),cell2mat(stripped_n_part_per_ml'),'-x')
xlabel('intake time (UTC)');
datetick('x');
legend(legend_str,'Location','NorthWest');
linkaxes([ah1 ah2],'x');
set(ah2,'FontSize',14);

print('-dpdf','SizeDistributionLinePlotVsTime');




figure('Position',[1000 297 1035 1201],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
ah1 = subplot(2,1,1)
plot(CastDepths.all_time,-CastDepths.all_depth,'-x');
datetick('x');
xlabel('time (UTC)');
ylabel('depth (m)');
title('April 2nd, 2014  -  All Casts');
set(ah1,'FontSize',14);
ah2 = subplot(2,1,2)
bar(DateNumTime(jdx),cell2mat(stripped_n_part_per_ml'),'stacked')
xlabel('intake time (UTC)');
datetick('x');
ylabel('Particles Per ml detected');
legend(legend_str,'Location','NorthWest');
linkaxes([ah1 ah2],'x');
set(ah2,'FontSize',14);
print('-dpdf','SizeDistributionBarPlotVsTime');



%Analyze Casts
DownCast{1} = [735691.6796 735691.6918];  %Start and Stop Times
UpCast{1} = [735691.6951 735691.707];  %Start and Stop Times

DownCast{2} = [735691.742 735691.7507];  %Start and Stop Times
UpCast{2} = [735691.7514 735691.769];  %Start and Stop Times

DownCast{3} = [735691.8047 735691.822];  %Start and Stop Times
UpCast{3} = [735691.8228 735691.8342];  %Start and Stop Times

DownCast{4} = [735691.8552  735691.8698];  %Start and Stop Times
UpCast{4} = [735691.8728 735691.882];  %Start and Stop Times

%Find Results coorepsonding to Upcasts and DownCasts
for i = 1:length(DownCast)
    DownCastDepths_idx{i} = find((CastDepths.all_time > DownCast{i}(1)) & (CastDepths.all_time < DownCast{i}(2)));
    DownCastResults_idx{i} = find((DateNumTime > DownCast{i}(1)) & (DateNumTime < DownCast{i}(2)));
end
for i = 1:length(UpCast)
    UpCastDepths_idx{i} = find((CastDepths.all_time > UpCast{i}(1)) & (CastDepths.all_time < UpCast{i}(2)));
    UpCastResults_idx{i} = find((DateNumTime > UpCast{i}(1)) & (DateNumTime < UpCast{i}(2)));
end

%Estimate depth for midpoint of each sample.
idx = find(~isnan(CastDepths.all_time));
for i = 1:length(DateNumTime)
    SampleDepths(i) = interp1(CastDepths.all_time(idx),CastDepths.all_depth(idx),DateNumTime(i)+(SamplingSeconds(i)/2)/86400);
end

clear legend_str;
figure('Position',[779 88 1225 1417],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
for i = 1:length(DownCast)
    plot(ParticlesPerml(DownCastResults_idx{i}),-SampleDepths(DownCastResults_idx{i}),'-x')
    hold all;
    legend_str{i} = ['Downcast ' num2str(i)]; 
end
legend(legend_str,'Location','SouthEast');
xlabel('Particles Per ml detected');
ylabel('Depth (m)');
title('Total Particle Density for DownCasts');
print('-dpdf','TotalParticleDensityForDownCasts');



for i = 1:length(bins)-1
  legend_str{i} = [num2str(bins(i)) ' - ' num2str(bins(i+1)) ' microns (ESD)'];
end
figure('Position',[779 88 1225 1417],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
for i = 1:length(DownCast)
    ah = subplot(2,2,i) 
    set(ah,'FontSize',14);
    foo = cell2mat(n_part_per_ml');
    plot(foo(DownCastResults_idx{i},:),-SampleDepths(DownCastResults_idx{i}),'-x')
    lh = legend(legend_str,'Location','SouthEast');
    set(lh,'FontSize',10);
    xlabel('Particles Per ml detected');
    ylabel('Depth (m)');  
    title(['DownCast Number ' num2str(i)]);
end
print('-dpdf','DownCastSizeDistributionLinePlot');

    

figure('Position',[779 88 1225 1417],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
for i = 1:length(DownCast)
    ah = subplot(2,2,i) 
    set(ah,'FontSize',14);
    foo = cell2mat(n_part_per_ml');
    if(~isempty(DownCastResults_idx{i}))
      barh(-SampleDepths(DownCastResults_idx{i}),foo(DownCastResults_idx{i},:),'stacked')
      lh = legend(legend_str,'Location','SouthEast');
      set(lh,'FontSize',10);
    end
      xlabel('Particles Per ml detected');
      ylabel('Depth (m)');  
      title(['DownCast Number ' num2str(i)]);
end

print('-dpdf','DownCastSizeDistributionBarPlot');



    
%Analyze Stops
%UpCastStops{1}{1} = [735691.7003 735691.7019];  %Start and Stop times of pauses on first upcast
%UpCastStops{1}{2} = [735691.7028 735691.7036];
%UpCastStops{1}{3} = [735691.7045 735691.7065];

%UpCastStops{2}{1} = [735691.7524 735691.7581];  %Start and Stop times of pauses on second upcast
%UpCastStops{2}{2} = [735691.7587 735691.7633];
%UpCastStops{2}{3} = [735691.7637 735691.7688];
%UpCastStops{2}{4} = [735691.7690 735691.7764];



UpCastStops{1}{1} = [735691.7006];  %Start and Stop times of pauses on first upcast
UpCastStops{1}{2} = [735691.7047];

UpCastStops{2}{1} = [735691.7543];  %Start and Stop times of pauses on second upcast
UpCastStops{2}{2} = [735691.7597];
UpCastStops{2}{3} = [735691.7659];   %7693
UpCastStops{2}{4} = [735691.7732];


%UpCastStops{3}{1} = [];  %Start and Stop times of pauses on third upcast
%UpCastStops{3}{2} = [];
%UpCastStops{3}{3} = [];



for i = 1:2  %Casts
    for j = 1:length(UpCastStops{i})   %Stops
        UpCastStops_idx{i}{j} = find( (DateNumTime <= UpCastStops{i}{j}(end)+10/(24*60*60)) & (DateNumTime >= UpCastStops{i}{j}(1)-10/(24*60*60)));
        %Write out data
        filenm = ['InstrumentIntercomparisons/FlowCam/c' num2str(i) '_s' num2str(j) '.csv'];
        fid = fopen(filenm,'w');
        fprintf(fid,'Part , Num ESD  , Total PartPerml, depth \n');
        for k = 1:length(ESD{UpCastStops_idx{i}{j}})
           fprintf(fid,'%d ,    %f   , %f ,  %f \n',k,ESD{UpCastStops_idx{i}{j}}(k),ParticlesPerml(UpCastStops_idx{i}{j}),SampleDepths(UpCastStops_idx{i}{j}));
        end
        fclose(fid);
    end
end



%Process lab-analyzed samples.
LabProcessedDataPath = '0000_LabProcessedData/';

files = dir([LabProcessedDataPath '*_summary_export.csv']);

plot_num = 0;
hists_per_page = 8;
page_num = 0;

bin_width = 4;

bins = 0:bin_width:100;
bins = bins(1:end-1)+bin_width/2;  %Convert specified bin edges to bin centers for use with hist.

ListFileNames{1} = '093-131708';    Identifier{1} = 'P01-#1';  CastNum{1} = 1;  StopNum{1} = 1;
ListFileNames{2} = '093-134104';    Identifier{2} = 'P01-#4';  CastNum{2} = 1;  StopNum{2} = 4;
ListFileNames{3} = '093-140032';    Identifier{3} = 'P03-B1';  CastNum{3} = 3;  StopNum{3} = 1;
ListFileNames{4} = '093-142251';    Identifier{4} = 'P03-B2';  CastNum{4} = 3;  StopNum{4} = 2;
ListFileNames{5} = '093-144448';    Identifier{5} = 'P03-B3';  CastNum{5} = 3;  StopNum{5} = 3;
ListFileNames{6} = '093-152411';    Identifier{6} = 'P04-B1';  CastNum{6} = 4;  StopNum{6} = 1;
ListFileNames{7} = '093-154321';    Identifier{7} = 'P04-B2';  CastNum{7} = 4;  StopNum{7} = 2;
ListFileNames{8} = '093-160226';    Identifier{8} = 'P04-B3';  CastNum{8} = 4;  StopNum{8} = 3;
ListFileNames{9} = '093-162053';    Identifier{9} = 'P04-B4';  CastNum{9} = 4;  StopNum{9} = 4;
ListFileNames{10} = '093-163906';    Identifier{10} = 'N2-#1';  CastNum{10} = 2;  StopNum{10} = 1;
ListFileNames{11} = '093-165734';    Identifier{11} = 'N2-#4';  CastNum{11} = 2;  StopNum{11} = 2;
ListFileNames{12} = '093-171610';    Identifier{12} = 'N2-#6';  CastNum{12} = 2;  StopNum{12} = 3;
ListFileNames{13} = '093-173455';    Identifier{13} = 'N2-#10';  CastNum{13} = 2;  StopNum{13} = 4;


for i =  1:length(files)
   
   num_str{i} = files(i).name(1:10);
   
   hr_str{i} = files(i).name(5:6);
   min_str{i} = files(i).name(7:8);
   sec_str{i} = files(i).name(9:10);

   
   Lab_summary_data{i} = ReadSummaryExport([LabProcessedDataPath files(i).name]);
   
   Lab_ParticlesPerml(i) = Lab_summary_data{i}.ParticlesPerml 

   
   Lab_DateNumStartTime(i) = datenum(Lab_summary_data{i}.StartTime)+6/24-time_offset_from_intake/86400;  %Convert to UTC including 1Hr offset of FlowCam clock. (UTC is +7, but clock was one hour fast during April 2nd, 2014 cruise...)
   Lab_DateNumTime(i) = datenum(2014,4,3,str2double(hr_str{i}),str2double(min_str{i}),str2double(sec_str{i}))+6/24-time_offset_from_intake/86400; 
   
   Lab_SamplingSeconds(i) =  Lab_summary_data{i}.SamplingSeconds;
   
   
   [data{i}, headertext{i}] = xlsread([LabProcessedDataPath num_str{i} '_data_export.csv']);
   
   Lab_ESD{i} = data{i}(:,11);
   
   [Lab_nelements_ESD{i},Lab_centers_ESD{i}] = hist(Lab_ESD{i},bins)
     
   Lab_n_part_per_ml{i} = [Lab_ParticlesPerml(i)*Lab_nelements_ESD{i}/sum(Lab_nelements_ESD{i})];
   
   plot_num = plot_num+1;
   if(plot_num > hists_per_page) 
       plot_num = 1; 
   end
   if(plot_num == 1) 
     figure('Position', [705 72 1138 1426],'PaperSize',[11 17],'PaperOrientation','portrait','PaperPositionMode','auto','PaperPosition',[.5 .5 10.5 16.5])
   end
   subplot(hists_per_page/2,2,plot_num)
   bar(Lab_centers_ESD{i},Lab_n_part_per_ml{i},1);
   xlabel('Particle Size (ESD - microns)');
   ylabel('Particles per ml');
   title([Identifier{i} '   ' num2str(Lab_SamplingSeconds(i)) ' sec sample   Particles per ml = ' num2str(Lab_ParticlesPerml(i))]); ...
          
   %title([num2str(Lab_SamplingSeconds(i)) ' sec sample starting at ' datestr(Lab_DateNumTime(i)) '  Particles per ml = ' num2str(Lab_ParticlesPerml(i)) ...
   %       '\newline  ' Identifier{i}]);
      
   if(plot_num == hists_per_page) 
     page_num = page_num+1;
     print('-dpdf',['04022014_Lab_ESD_Histogram_Pg_' num2str(page_num)]);
   end
      
end
   page_num = page_num+1;
   print('-dpdf',['04022014_Lab_ESD_Histogram_Pg_' num2str(page_num)]);  %Print leftovers.



