% SMPS-TSI-3082 (version3) data processing from txt files (LRizzo)
% Interpolated to a commom diameter sequence
% Funcoes utilizadas: fsmps_interp, fsmps_param, export_LFA_GoAmazon_jan2015 
%
% Obs para RioBranco: Os dados foram exportados do AIM em um computador com horário UTC-2.
% Ao abrir os dados, o software do AIM mudou os horários originais (que estavam em UTC) para o fuso horário do computador (UTC-2).
% Assim, para reportar os dados em UTC novamente, foram somadas 2 horas ao horário que consta nos arquivos txt.
%
% Para Rio Branco: o código está adaptado só até o Level1. Tem que conferir
% o código para os Levels 2 e 3
%
% Output: alldata(level0) 
% 1 - matdate(utc) 
% 2:7 - Dpg(nm), Mode(nm), GeoStd, TotalConc(cm-3), SurfArea(um2/cm3), Vol(um3/cm3) 
% 8:114 - dN/dlogDp
% 115:121 - SampleTemp(C), SamplePress(kPa), SampleRH(%), SheathFlow(lpm), AerosolFlow(lpm), LowerSize(nm), UpperSize(nm)
%
% Level1: 5-min aerosol concentration must be >50 cm-3 and <100 000 cm-3. 
%         Sheath flow must be > 3 lpm and < 12 lpm. 
%         Sample flow must be > 0.3 lpm and < 2 lpm. 
%         Status flag must be “Normal Scan”. 
%         Multiple charge correction must have been applied.
% Level2: STP correction (1013.25; 293.15).
% Level3: Integrated aerosol number must be within 30% CPC measurement. 
%         Considering an aerosol density of 1.4 g cm-3, integrated mass must be within 50%-120% of TEOM PM2.5.    
%  
% Parametros de entrada:
caminho='C:\A\RioBranco\SMPS_novo\Raw_Data\txt\';
caminho1='C:\A\RioBranco\processados\smps\';
caminho2='C:\A\RioBranco\processados\smps\plots\';
tit='RioBranco-2018';
dens=1.6; % particle density, in g/cm3
ano=2018;
lastday=[31 28 31 30 31 30 31 31 30 31 30 31];
timezone=0;
% diameter sequence to which you want the data to be interpolated (this code does not extrapolate!!)
diam=[9.47 9.82	10.2 10.6 10.9	11.3 11.8 12.2 12.6	13.1 13.6 14.1 14.6	15.1 15.7 16.3 16.8	17.5 18.1 18.8 19.5	20.2	20.9	21.7	22.5	23.3	24.1	25	25.9	26.9	27.9	28.9	30	31.1	32.2	33.4	34.6	35.9	37.2	38.5	40	41.4	42.9	44.5 46.1 47.8	49.6	51.4	53.3	55.2	57.3	59.4	61.5	63.8	66.1	68.5	71	73.7	76.4	79.1	82	85.1	88.2	91.4	94.7	98.2	101.8	105.5	109.4	113.4	117.6	121.9	126.3	131	135.8	140.7	145.9	151.2	156.8	162.5	168.5	174.7	181.1	187.7	194.6	201.7	209.1	216.7	224.7	232.9	241.4	250.3	259.5	269	278.8	289	299.6	310.6	322	333.8	346	358.7	371.8	385.4	399.5	414.2	429.4];
filtmanut=false; % logical para filtrar dados em períodos de manutenção ou com problemas
lev1=false;
lev2=false;
%
% inicio e termino de periodos de manutencao (horario em utc): removidos das analises
% if(filtmanut)
%     C1=xlsread('C:\A\Diadema2016\logbook_trailer_Diadema2016.xlsx','todos','A4:M135');
%     manut(:,1)=datenum(C1(:,1:6));
%     manut(:,2)=datenum(C1(:,7:12));
%     manut(:,3)=C1(:,13);
% end
%
files=dir(caminho);
if(size(files,1)==0)
    disp('Error: raw data files path might be wrong')
    stop
end
tempo=zeros(1,1);param=zeros(1,7);totconc=zeros(1,4);sizedist=zeros(1,length(diam));
disp('-----Reading raw data files')
for ifile=3:size(files,1)
    nome=getfield(files, {ifile,1}, 'name');
    disp(nome)
    fid=fopen(strcat(caminho,nome));
    config=textscan(fid,'%s',74,'Delimiter',',');
    if(strcmp(config{1,1}(57),'FALSE'))
        disp('Warning: no multiple charge correction!!!')
    end
    % verifica se chegou no início dos diâmetros
    if~(strcmp(config{1,1}(74),'Diameter Midpoint (nm)'))
        disp('Did not find diameter start in raw data file.')
        stop
    end
    aux=textscan(fid,'%f',1,'Delimiter',',');
    idiam=1;
    diam_=nan(1,100);
    while(cell2mat(aux)>0)
        diam_(idiam)=cell2mat(aux);
        idiam=idiam+1;
        aux=textscan(fid,'%f',1,'Delimiter',',');
    end
    aux=textscan(fid,'%s',29,'Delimiter',',');
    % verifica se chegou no final do cabeçalho
    if~(strcmp(aux{1,1}(29),'Comment'))
        disp('Did not find end of header.')
        stop
    end
    %
    f1='%*f%s%s%f%f%f%*f%*f%*s';
    f3='%*f%*f%*f%*f %f%f %*f%*f%*f %f%f %*f%*f%*f%*f%*f%*f %f%f%f%f %*s%*s%*s%*s%*s%*s%*s%*s';
    f2='';
    for i=1:length(diam_)
        f2=strcat(f2,'%f');
    end
    format=strcat(f1,f2,f3);
    C=textscan(fid,format,'Delimiter',',');
    fclose(fid);
    %
    % Retrieve normalized size distribution
    sizedist_=zeros(size(C{1,1},1),length(diam_));        
    for j=6:length(diam_)+5  
        sizedist_(:,j-5)=C{1,j};
    end
    % Retrieve control parameters [1-SampleTemp(C), 2-SamplePress(kPa), 3-SampleRH(%), ...
    ... 4-SheathFlow(lpm), 5-AerosolFlow(lpm), 6-LowerSize(nm), 7-UpperSize(nm)]
    param_=zeros(size(C{1,1},1),7);
    for j=1:3
        param_(:,j)=C{1,j+2};
    end
    jj=4;
    for j=length(diam_)+6:size(C,2)-4
        param_(:,jj)=C{1,j};
        jj=jj+1;
    end
    % Retrieve [Geo.Mean(nm) Mode(nm) Geo.Std.Dev. TotalConc.(cm-3)]
    totconc_=zeros(size(C{1,1},1),4);
    for j=size(C,2)-3:size(C,2)
        totconc_(:,j-size(C,2)+4)=C{1,j};
    end
    disp('Convertendo data e hora para matriz de tempo')
    aux1=strcat((C{1,1}(:,1)),(C{1,2}(:,1)));
    tempo_=datenum(aux1,'mm/dd/yyyyHH:MM:SS'); % matlab date 
    %
    interp=false;
    if(length(diam_)==length(diam))          
        if(sum(diam_==diam)~=length(diam))
            interp=true;
        end
    else
        interp=true;
    end    
    if(interp) % Interpolate to match a diameter sequence defined by the user, if necessary 
        disp('Interpolating to a commom diameter sequence')
        [newsizedist]=fsmps_interp(diam,diam_,sizedist_,tempo_);
        sizedist_=newsizedist(:,2:size(newsizedist,2));        
    end
    %
    tempo=cat(1,tempo,tempo_);
    param=cat(1,param,param_);
    totconc=cat(1,totconc,totconc_);
    sizedist=cat(1,sizedist,sizedist_);
    %
    clear C aux aux1 aux2 param_ totconc_ diam_ tempo_ sizedist_
end
%
% Calculate size dist parameters
[maisparam]=fsmps_param(diam,9,sizedist,false); % (N(cm-3), Dpg(nm), sg, SurfaceArea(um2/cm3), Volume(um3/cm3), SMD(nm), VMD(nm))
%
alldata=cat(2,tempo,totconc,maisparam(:,4:5),sizedist,param);
alldata=sortrows(alldata,1); % sort data based on day of year
alldata(1,8:length(diam)+7)=diam;
alldata(2:length(alldata),1)=alldata(2:length(alldata),1)+datenum(0,0,0,2,0,0); % corrigindo para hora UTC, conforme explicação no cabeçalho do programa
save(strcat(caminho1,tit,'_smps_level0.mat'),'alldata','-mat')
csvwrite(strcat(caminho1,tit,'_smps_level0.csv'),[alldata,datevec(alldata(:,1))])
%
% Remove maintanance periods from dataset
if(filtmanut)
    for i=1:size(manut,1)
        aux=find(alldata(:,1)>=manut(i,1) & alldata(:,1)<=manut(i,2));
        alldata(aux,:)=[];
    end
    clear aux
    save(strcat(caminho1,tit,'_smps_clean.mat'),'alldata','-mat')
    %csvwrite(strcat(caminho1,tit,'_smps_clean.csv'),[alldata,datevec(alldata(:,1))])
end
%
% Basic plots
% 1 - matdate(utc) 
% 2:7 - Dpg(nm), Mode(nm), GeoStd, TotalConc(cm-3), SurfArea(um2/cm3), Vol(um3/cm3) 
% 8:114 - dN/dlogDp
% 115:121 - SampleTemp(C), SamplePress(kPa), SampleRH(%), SheathFlow(lpm), AerosolFlow(lpm), LowerSize(nm), UpperSize(nm)
colsdist=8:length(diam)+7;
lin=2:size(alldata,1);
figure
subplot(3,1,1),plot(alldata(lin,1),alldata(lin,length(diam)+10),'c*'),grid on
set(gca,'YLim',[20 60]),ylabel('SampleRH(%)')
title(tit)
dynamicDateTicks
subplot(3,1,2),plot(alldata(lin,1),alldata(lin,length(diam)+11),'m*'),grid on
set(gca,'YLim',[5 10]),ylabel('SheathFlow(lpm)')
dynamicDateTicks
subplot(3,1,3),plot(alldata(lin,1),alldata(lin,length(diam)+12),'g*'),grid on
set(gca,'YLim',[0.5 1.7]),ylabel('AerosolFlow(lpm)')
dynamicDateTicks
saveas(gcf,[caminho2,tit,'_smps_diag'],'jpg')
%
figure
subplot(3,1,1),plot(alldata(lin,1),alldata(lin,5),'b*'),grid on
ylabel('Total Conc (cm^-^3)')
title(tit)
dynamicDateTicks
subplot(3,1,2),plot(alldata(lin,1),alldata(lin,2),'r*'),grid on
ylabel('Dpg(nm)')
dynamicDateTicks
subplot(3,1,3),plot(alldata(lin,1),alldata(lin,4),'g*'),grid on
ylabel('GeoStd')
dynamicDateTicks
saveas(gcf,[caminho2,tit,'_smps_param'],'jpg')
%
disp('Calculations for contourplots')
aux=find(diff(alldata(:,1))>=0.5);
alldata2(1,:)=alldata(1,:);
for i=2:length(aux) % insere linhas em branco em períodos com mais de 12h sem dados
    alldata2=cat(1,alldata2,alldata(aux(i-1)+1:aux(i),:),nan(1,size(alldata,2)));
end
alldata2=cat(1,alldata2,alldata(aux(length(aux))+1:size(alldata,1),:));
aux=find(isnan(alldata2(:,1)));
alldata2(aux,1)=alldata2(aux-1,1)+0.4;
timesec=alldata2(lin,1);
Z=alldata2(lin,colsdist);
[r,c]=find(Z<0);  % replace negative values per 0
for k=1:length(r)
    Z(r(k),c(k))=0;
end
clear r c
Znorm=Z;
for ii=1:size(Z,1)
    Znorm(ii,:)=Z(ii,:)./max(Z(ii,:));
end
figure,subplot(2,1,1)
contourf(timesec,diam,Znorm','LineStyle','none'),grid on
set(gca,'YScale','log')
set(gca,'YTick',[20 50 100 200 400])
% imagesc(timesec,log10(diam),Znorm')
% set(gca,'YDir','normal')
% set(gca,'YTick',[1.0 log10(30) log10(50) 2.0 log10(200) log10(400)])
% set(gca,'YTickLabel',[10 30 50 100 200 400],'FontSize',12)
legend('normalized')%,colorbar 
title(tit,'FontSize',15),xlabel('UTC Time','FontSize',12),ylabel('Diameter (nm)','FontSize',12)
set(gca,'XLim',[datenum(2018,9,24) floor(alldata(size(alldata,1),1))])
set(gca,'XTick',datenum(2018,9,24):7:floor(alldata(size(alldata,1),1)))
set(gca,'XTickLabel', datestr(datenum(2018,9,24):7:floor(alldata(size(alldata,1),1)),'mm/dd/yy'),'FontSize',12)
subplot(2,1,2),plot(alldata(lin,1),alldata(lin,5),'ko'),grid on,hold on
%addaxis(alldata(lin,1),alldata(lin,7)*dens,'b.')
set(gca,'XLim',[datenum(2018,9,24) floor(alldata(size(alldata,1),1))])
set(gca,'XTick',datenum(2018,9,24):7:floor(alldata(size(alldata,1),1)))
set(gca,'XTickLabel', datestr(datenum(2018,9,24):7:floor(alldata(size(alldata,1),1)),'mm/dd/yy'),'FontSize',12)
xlabel('UTC Time','FontSize',12)
ylabel('Total Conc (cm^-^3)');
%addaxislabel(1,'Total Conc (cm^-^3)');
%addaxislabel(2,'Mass (ug/m^-^3)');
saveas(gcf,strcat(caminho2,tit,'_contour_tseries'),'jpg')
%
mediana=zeros(3,length(colsdist));    
for ii=8:colsdist(length(colsdist))
    mediana(1,ii-7)=prctile(alldata(:,ii),25);
    mediana(2,ii-7)=prctile(alldata(:,ii),50);
    mediana(3,ii-7)=prctile(alldata(:,ii),75);
end
figure
errorbar(diam,mediana(2,1:length(diam)),mediana(1,1:length(diam)),mediana(3,1:length(diam)),'-b.')
title(strcat(tit,'Median Size Distribution'),'FontSize',12,'fontweight','b'),xlabel('Dp (nm)','FontSize',12,'fontweight','b'),ylabel('dN/dlogDp (cm^-^3)','FontSize',12,'fontweight','b')
set(gca,'XScale','log'), grid on
set(gca,'XTick',[20 50 100 200 400],'FontSize',12,'fontweight','b')
set(gca,'XLim',[10 500])
saveas(gcf,strcat(caminho2,'\median_sizedist'),'jpg')
%
% ------------ Level 1 ------------------------------------------------
% Level1: 1-min aerosol concentration must be >50 cm-3 and <100 000 cm-3. 
%         Sheath flow must be > 3 lpm and < 12 lpm. 
%         Sample flow must be > 0.3 lpm and < 2 lpm. 
%         dN must be >0 in the middle of the accumulation mode (Dp~200nm)
%         Dpg must be <200 nm  
%         sg must be >1.5 
%         Status flag must be “Normal Scan”. 
%         Multiple charge correction must have been applied.
% alldata:
% 1 - matdate(utc) 
% 2:7 - Dpg(nm), Mode(nm), GeoStd, TotalConc(cm-3), SurfArea(um2/cm3), Vol(um3/cm3) 
% 8:112 - dN/dlogDp
% 113:119 - SampleTemp(C), SamplePress(kPa), SampleRH(%), SheathFlow(lpm), AerosolFlow(lpm), LowerSize(nm), UpperSize(nm)
%
if(lev1)       
    %C=load('C:\A\RioBranco\processados\smps\RioBranco-2018_smps_level0.mat');
    %alldata=C.alldata;    
    %diam=C.alldata(1,colsdist);
    %tit='RioBranco-2018';
    %
    origsize=size(alldata,1);
    orig=alldata;
    alldata(alldata(:,5)<50,:)=[]; % remove lines with totconc<50cm-3
    alldata(alldata(:,5)>10^5,:)=[]; % remove lines with totconc>10^5cm-3
    alldata(alldata(:,length(diam)+11)<3,:)=[]; % remove lines with sheath<3 lpm
    alldata(alldata(:,length(diam)+11)>12,:)=[]; % remove lines with sheath>12 lpm
    alldata(alldata(:,length(diam)+12)<0.3,:)=[]; % remove lines with sampleflow<0.3 lpm
    alldata(alldata(:,length(diam)+12)>2,:)=[]; % remove lines with sampleflow>2 lpm
    j=find(diam>=200 & diam<=250);
    alldata(alldata(:,j(1)+8)<=0,:)=[]; % remove lines with dN(200nm)<=0
    alldata(alldata(:,2)>200,:)=[]; % remove lines with Dpg>200nm
    alldata(alldata(:,4)<1.5,:)=[]; % remove lines with sg<1.5
    %
    lin=2:length(alldata);
    figure
    subplot(3,1,1),plot(orig(lin,1),orig(lin,5),'r.'),grid on, hold on
    plot(alldata(lin,1),alldata(lin,5),'k.')
    ylabel('Total Conc (cm^-^3)')
    title(tit)
    dynamicDateTicks
    subplot(3,1,2),plot(orig(lin,1),orig(lin,2),'r.'),grid on, hold on
    plot(alldata(lin,1),alldata(lin,2),'k.')
    ylabel('Dpg(nm)')
    dynamicDateTicks
    subplot(3,1,3),plot(orig(lin,1),orig(lin,4),'r.'),grid on, hold on
    plot(alldata(lin,1),alldata(lin,4),'k.')
    ylabel('GeoStd')
    dynamicDateTicks
    legend('level0','level1')
    saveas(gcf,strcat(caminho2,'\level0_level1'),'jpg')
    %   
    % Save Level 1 data 
    Instrument='SMPS_TSI';
    Model='3082';
    serial_num='3082001629001';
    Site=tit;
    Val_level='1';
    Proc_vers='1.0';
    labels{1}='Total concentration';
    labels{2}='Total volume';
    labels{3}='Mean diameter';
    units{1}='(cm-3)';
    units{2}='(um3.cm-3)';
    units{3}='(nm)';
    export_LFA_GoAmazon_jan2015(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,origsize,alldata(lin,1),[alldata(lin,5) alldata(lin,7) alldata(lin,2)],diam,alldata(lin,colsdist));    
end
%
% ------------ Level 2 ------------------------------------------------
% Level2: STP correction (1013.25; 293.15).
if(lev2)        
    % Lê os arquivos Level 1 que ja salvou
    aux=importdata('C:\A\RioBranco\processados\LFA_standard\RioBranco-2018_SMPS_TSI_3082_Level1_5min.csv');
    diam=zeros(1,107);
    for j=24:130
        diam(j-23)=str2num(char(aux.textdata(2,j)));
    end
    level1_5min=[aux.data(:,1:2) aux.data(:,9) aux.data(:,16) aux.data(:,23:129)];        
    clear aux
    level1_5min(:,1)=level1_5min(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    origsize=sum(~isnan(level1_5min(:,2)));
    tit='RioBranco-2018';
    %
    % Lê dados de meteorologia e calcula fator stp
    C=importdata('');
    met(:,1)=datenum(C.textdata(3:length(C.textdata)),'dd-mmm-yyyy HH:MM:SS ');
    met(:,2:3)=C.data;
    met(:,1)=met(:,1)+3/24; % local time to utc time
    met(:,3)=met(:,3)+273.15; % oC to K
    met(met(:,1)<level1_5min(1,1),:)=[];
    met(met(:,1)>level1_5min(length(level1_5min),1),:)=[];
    if(length(met)~=length(level1_5min))
        disp('check length of meteorological data file')
        stop
    end
    %
    pref=1013.25; tref=293.15;
    stp=(pref*met(:,3))./(tref*met(:,2));
    for j=2:size(level1_5min,2)
        if(j~=4) % skip Dpg                 
            level1_5min(:,j)=level1_5min(:,j).*stp;
        end
    end
    %   
    % Save Level 2 data 
    Instrument='SMPS_TSI';
    Model='3082';
    serial_num='3082001629001';
    Site=tit;
    Val_level='2';
    Proc_vers='1.0';
    labels{1}='Total concentration';
    labels{2}='Total volume';
    labels{3}='Mean diameter';
    units{1}='(cm-3)';
    units{2}='(um3.cm-3)';
    units{3}='(nm)';
    export_LFA_GoAmazon_jan2015(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,origsize,level1_5min(:,1),level1_5min(:,2:4),diam,level1_5min(:,5:109));    
end
%
%
% ------------ Level 3 ------------------------------------------------
% Level3: Integrated aerosol number must be within 30% CPC measurement. 
%         Considering an aerosol density of 1.4 g cm-3, integrated mass must be within 50%-120% of TEOM PM2.5.    
%         Obs:
%         Testes em laboratório com esferas de PSL em 2017 indicaram que o 
%         sizing deste SMPS está correto, mas a contagem está ~50% subestimada.
%         As distribuições dN/logDp foram divididas pelo fator constante de XXX
%         (slope SMPSxCPC). Porém, mesmo após essa correção, as concentrações
%         do SMPS devem ser interpretadas apenas qualitativamente.
%
if(lev3)        
    dens=1.6; %g/cm3
    % Lê os arquivos Level 2 que ja salvou
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_SMPS_TSI_3082_Level2_30min.csv');
    diam=aux.data(1,:);
    aux.data(length(aux.data)+1:length(aux.textdata)-1,:)=NaN;
    sdist=aux.data(2:length(aux.data),:);  
    param=str2double(aux.textdata(3:length(aux.textdata),2:5)); % TotConc(cm-3); TotVol(cm3); Dpg(nm)
    param(:,1)=param(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    origsize=sum(~isnan(param(:,2)));
    tit='RioBranco-2018';
    %
    aux=load('C:\A\Diadema2016\processados\smps\Diadema-2016_smps_clean.mat');
    level0=[aux.alldata(:,1) aux.alldata(:,113:117)]; %SampleTemp(C), SamplePress(kPa), SampleRH(%), SheathFlow(lpm), AerosolFlow(lpm)
    level0(1,:)=[];
    %
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_CPC_3772_Level2_30min.csv');
    cpc=aux.data;
    cpc(:,1)=cpc(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    %
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_ACSM_dados preliminares_Level1_30min.csv');
    acsm=aux.data; % {'Org','SO4','NO3','NH4','Chl','OOA','HOA','BBOA'}
    acsm(:,1)=acsm(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    %
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_MAAP_5012_Level2_30min.csv');
    maap=aux.data(:,1:2); % BC
    maap(:,1)=maap(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    %
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_OPS_TSI_3330_Level2_30min.csv');
    aux.data(length(aux.data)+1:length(aux.textdata)-1,:)=NaN;
    dops=aux.data(1,:)*1000; % nm
    ops(:,2:17)=aux.data(2:length(aux.data),:);
    for i=3:length(aux.textdata)
        ops(i-2,1)=str2double(char(aux.textdata{i,2}))/(24*60*60)+datenum(1970,1,1); % unix time to matlab time;
    end       
    clear aux
    %    
    msdist=param(:,3)*dens; % ug/m3
    macsmmaap=sum(acsm(:,2:6),2)+maap(:,2); % ug/m3    
    %
    rem=[datenum(2017,2,8,9,0,0) datenum(2017,2,15,19,0,0)]; 
    aux=find(param(:,1)>=rem(1,1) & param(:,1)<=rem(1,2));
    %
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(level0(:,1),level0(:,2),'r.'),grid on,dynamicDateTicks
    ylabel('SampleTemp(C)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(level0(:,1),level0(:,3),'g.'),grid on,dynamicDateTicks
    ylabel('SamplePress(kPa)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(level0(:,1),level0(:,4),'c.'),grid on,dynamicDateTicks
    ylabel('SampleRH(%)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(level0(:,1),level0(:,5),'c.'),grid on,dynamicDateTicks
    ylabel('SheathFlow(lpm)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    set(gca,'YLim',[5 7])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(level0(:,1),level0(:,6),'b.'),grid on,dynamicDateTicks
    ylabel('AerosolFlow(lpm)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(param(:,1),param(:,4),'c.'),grid on,dynamicDateTicks
    hold on,  plot(param(aux,1),param(aux,4),'rx')
    ylabel('Dpg(nm)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    subplot(2,1,1),plot(param(:,1),cpc(:,2)./param(:,2),'b.'),grid on,hold on,dynamicDateTicks
    ylabel('Ratio','FontSize',12),title(tit,'FontSize',12)
    plot(param(:,1),macsmmaap./msdist,'r.')
    legend('CPC/SMPS','ACSM+MAAP/SMPS')
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(param(:,1),ops(:,3)./sdist(:,101),'k.'),grid on,dynamicDateTicks
    hold on,  plot(param(aux,1),ops(aux,3)./sdist(aux,101),'rx')
    ylabel('OPS/SMPS @370nm ','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    %
    paramorig=param;
    param(param(:,1)>=rem(1,1) & param(:,1)<=rem(1,2),2:4)=NaN;
    msdist(param(:,1)>=rem(1,1) & param(:,1)<=rem(1,2))=NaN;
    param(:,2:3)=param(:,2:3)/0.58; % correção utilizando o slope com o cpc
    msdist=param(:,3)*dens; % ug/m3
    figure
    subplot(1,2,1),plot(cpc(:,2),param(:,2),'b.'),grid on,hold on
    [a,b,rsquare]=flinreg(cpc(:,2),param(:,2));
    x=[min(cpc(:,2)) max(cpc(:,2))];
    plot(x,a*x+b,'-r')
    legend('data (dens 1.6 g/cm3)',[num2str(a,'%1.2f'),'*x+',num2str(b,'%3.0f'),' R^2=',num2str(rsquare,'%1.2f')])
    ylabel('ConcSMPS (cm^-^3)','FontSize',12),xlabel('CPC (cm^-^3)','FontSize',12)
    title(tit,'FontSize',12)
    subplot(1,2,2),plot(macsmmaap,msdist,'c.'),grid on,hold on
    [a,b,rsquare]=flinreg(macsmmaap,msdist);
    x=[min(macsmmaap) max(macsmmaap)];
    plot(x,a*x+b,'-r')
    legend('data',[num2str(a,'%1.2f'),'*x+',num2str(b,'%3.0f'),' R^2=',num2str(rsquare,'%1.2f')])
    ylabel('ConcSMPS (cm^-^3)','FontSize',12),xlabel('ACSM+BC (ug/m^3)','FontSize',12)
    %
    % Lê os arquivos Level 2 5min para corrigir e salvar o Level3
    aux=importdata('C:\A\Diadema2016\processados\LFA_standard\Diadema-2016_SMPS_TSI_3082_Level2_5min.csv');
    diam=aux.data(1,:);
    aux.data(length(aux.data)+1:length(aux.textdata)-1,:)=NaN;
    sdist=aux.data(2:length(aux.data),:);  
    param=str2double(aux.textdata(3:length(aux.textdata),2:5)); % TotConc(cm-3); TotVol(cm3); Dpg(nm)
    param(:,1)=param(:,1)/(24*60*60)+datenum(1970,1,1); % unix time to matlab time
    origsize=sum(~isnan(param(:,2)));
    tit='RioBranco-2018';
    rem=[datenum(2017,2,8,9,0,0) datenum(2017,2,15,19,0,0)];
    param(param(:,1)>=rem(1,1) & param(:,1)<=rem(1,2),2:4)=NaN;
    sdist(param(:,1)>=rem(1,1) & param(:,1)<=rem(1,2),:)=NaN;
    param(:,2:3)=param(:,2:3)/0.58; % correção utilizando o slope com o cpc
    sdist=sdist/0.58;
    figure
    subplot(2,1,1),plot(param(:,1),param(:,2),'-b.'),grid on,dynamicDateTicks
    ylabel('SMPS Conc','FontSize',12),title([tit,'Após correção'],'FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    subplot(2,1,2),plot(param(:,1),param(:,4),'-c.'),grid on,dynamicDateTicks
    ylabel('Dpg(nm)','FontSize',12)
    set(gca,'XLim',[datenum(2016,12,1) datenum(2017,3,16)])
    figure
    cor='brgkcmbrgkcmbrgkcm';
    delta=10;
    for i=31969:delta:length(sdist)
        if(sum(isnan(sdist(i:i+9,5)))<10)
            for ii=1:delta
                semilogx(diam,sdist(i+ii-1,:),['-',cor(ii),'.']),grid on,hold on
                set(gca,'XLim',[10 500])
                title(datestr(param(i,1)))
            end
            pause%(0.5)
        end
        hold off
    end
    %
    % Save Level 3 data 
    Instrument='SMPS_TSI';
    Model='3082';
    serial_num='3082001629001 - Sizing quantitative, Concentration qualitative';
    Site=tit;
    Val_level='3';
    Proc_vers='1.0';
    labels{1}='Total concentration';
    labels{2}='Total volume';
    labels{3}='Mean diameter';
    units{1}='(cm-3)';
    units{2}='(um3.cm-3)';
    units{3}='(nm)';
    export_LFA_GoAmazon_jan2015(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,origsize,param(:,1),param(:,2:4),diam,sdist);    
    %
end
% -------------------------------------------------------------------------
%     
% % Contourplots - daily
% year=alldata(2,2);month=alldata(2,3);iday=alldata(2,4); % Start date
% day=iday-1;
% clear tempo 
% tempo=alldata(2:size(alldata,1),1); 
% sizedist(:,1)=[];
% nday=tempo-mod(tempo,1);
% figure
% for i=nday(1):nday(length(nday))
%     aux=find(nday==i);
%     if (isempty(aux))
%         day=day+1;
%         continue
%     end
%     timesec=tempo(aux);
%     Z=sizedist(aux,:)';
%     [r,c]=find(Z<0);  % replace negative values per 0
%     for k=1:length(r)
%         Z(r(k),c(k))=0;
%     end
%     clear r c
%     %
%     day=day+1;
%     if(day>lastday(month))
%         day=day-lastday(month);
%         month=month+1;
%     end
%     %
%     % figure
%     contourf(mod(timesec,1),diam,Z),shading flat
%     colorbar
%     title(strcat(tit,num2str(year),num2str(month,'%02d'),num2str(day,'%02d')),'FontSize',12),xlabel('UTC Time','FontSize',12),ylabel('Dp (um)','FontSize',12)
%     set(gca,'YScale','log'),grid on
%     set(gca,'YTick',[20 50 100 200 400])
%     set(gca,'XLim',[0 1])
%     set(gca,'XTick',[0.125 0.25 0.375 0.5 0.625 0.75 0.875 1.0])
%     set(gca,'XTickLabel',{'3:00';'6:00';'9:00';'12:00';'15:00';'18:00';'21:00';'0:00'},'FontSize',12)    
%     saveas(gcf,strcat(caminho2,'\',num2str(year),num2str(month,'%02d'),num2str(day,'%02d'),'_contour'),'jpg')
%     %
%     % figure
% %     contourf(mod(timesec,1),diam,log10(Z)),shading flat
% %     colorbar, legend('log10')
% %     title(strcat(num2str(year),num2str(month,'%02d'),num2str(day,'%02d'),tit),'FontSize',12),xlabel('UTC Time','FontSize',12),ylabel('Dp(um)','FontSize',12)
% %     set(gca,'YScale','log')
% %     set(gca,'YTick',[20 50 100 200 400])
% %     set(gca,'XTick',[0.125 0.25 0.375 0.5 0.625 0.75 0.875 1.0])
% %     set(gca,'XTickLabel',{'3:00';'6:00';'9:00';'12:00';'15:00';'18:00';'21:00';'0:00'},'FontSize',12)
% %     saveas(gcf,strcat(caminho2,'\',num2str(year),num2str(month,'%02d'),num2str(day,'%02d'),'_log'),'jpg')
%     %
%     Znorm=Z;
%     for j=1:size(Z,2)
%         Znorm(:,j)=Z(:,j)./max(Z(:,j));
%     end
%     %  figure
%     contourf(mod(timesec,1),diam,Znorm),shading flat
%     colorbar, legend('normalized')
%     title(strcat(tit,num2str(year),num2str(month,'%02d'),num2str(day,'%02d')),'FontSize',12),xlabel('UTC Time','FontSize',12),ylabel('Dp (um)','FontSize',12)
%     set(gca,'YScale','log'), grid on
%     set(gca,'YTick',[20 50 100 200 400])
%     set(gca,'XLim',[0 1])
%     set(gca,'XTick',[0.125 0.25 0.375 0.5 0.625 0.75 0.875 1.0])
%     set(gca,'XTickLabel',{'3:00';'6:00';'9:00';'12:00';'15:00';'18:00';'21:00';'0:00'},'FontSize',12)
%     saveas(gcf,strcat(caminho2,'\',num2str(year),num2str(month,'%02d'),num2str(day,'%02d'),'_norm'),'jpg')
% end
