%plotConcat2.m

clear;

raw = '2016Aug23';
path =    sprintf('../%s/raw',raw);
matfile = sprintf('../%s/parsed/CPF%s_ENG.mat',raw,raw);


MAXi=50000;
load (matfile,'DATETIMENUM','STATE','P','SEDHOME','SEDNEXT');
numprof = size(STATE,1);

maxP=1;
figure(2);  hold on;
state_legend;
emerg_index=1;

for prof=1:1:numprof
        p(1)=NaN;
        t(1)=NaN;
        emerg_p(1)=NaN;
        emerg_t(1)=NaN;
        
        prev_state=0;
        j=1;

        while(~isnan(STATE(prof,j)))
            state(j)=STATE(prof,j);
            j=j+1;
        end
        numpoints=j-1;
        k=2;
        for j=1:1:numpoints
            if(state(j)==3 || state(j) ==17)
                emerg_p(emerg_index)=P(prof,j);
                emerg_t(emerg_index)=DATETIMENUM(prof,j);
                emerg_index=emerg_index+1;
            end
            if(state(j)==prev_state )
                if(~isnan(P(prof,j)))
                    p(k)=P(prof,j);
                    if(P(prof,j)<maxP)maxP=P(prof,j);end
                else
                    p(k)=p(k-1);
                end
                t(k)=DATETIMENUM(prof,j);
                format longg,t;
                k=k+1;
            else %state change
                %fprintf('STATE change from %d to %d\n',prev_state,state(j)); 
                
                if(state(j)==17)
                    plot([t(size(t,2)) t(size(t,2))],[-500 10],'Color',[1 0.8 0.8],'LineWidth',5);
                end
                plot(t,p,'Color',state_color(prev_state));hold on;
                

                
                prev_state = state(j);
                %pause;
                clear('p','t');
                p(1)=NaN;
                t(1)=NaN;
                k=2;
            end
        end
        
        clear('j');    
end

plot(t,p,'Color',state_color(prev_state));hold on; %get the last one
scatter(emerg_t,emerg_p,30,'red','filled');



axis([DATETIMENUM(1,1) t(size(t,2)) maxP 2]);
datetick('keeplimits');
ylabel('dbar');
xlabel('hour');
title(raw);
grid on;    
logsave=sprintf('%s.png',raw);
saveas(gcf,logsave);


% for i=1:1:numprof
% 
%   for (j = 1:1:size(DATETIMENUM,2))
%       clr(j,:) = state_color(STATE(i,j));
%       
%       if(STATE(i,j)==3 || STATE(i,j) ==17)
%           dat_size(i,j) = 50;
%           
%       else
%           dat_size(i,j) = 10;
%           %clr(j,:) = [1 1 1];
%       end
%       
%   end
%   
%   for( j = 2:1:size(DATETIMENUM,2))
%       if ( isnan(P(i,j)) )
%           P(i,j)=P(i,j-1);
%       end
%   end
%           
%   
%   %plot(DATETIMENUM(i,:),STATE(i,:));
%   scatter(DATETIMENUM(i,:),P(i,:),dat_size(i,:),clr,'filled');
% 
% end