%bellows average position summary bellowsavg.m
clear;
fp = 'test';
path = sprintf( '../%s/parsed/CPF%s_ENG.mat',fp,fp);
load(path,'BP','P','DATETIMENUM','BAND','STATE');

numprofiles = size(P,1);
figure;hold on;grid on;

j=1;
k=1;
l=1;
outband = 1;
PID_time = 0;
first_park=0;

for prof = 1:numprofiles
    park = 0;
    j=1;
    k=1;
    clear bp;
    clear bpt;
    clear p;
    clear pt;
    
    for i = 1:1:size(BAND,2)
        if (STATE(prof,i)==16 && first_park==0) %first time in park,start PID
            first_park=1;
            PID_start = DATETIMENUM(prof,i);
            fprintf('PID_start = %f, i=%d\n',PID_start,i);
        end
        if(BAND(prof,i)==1 && STATE(prof,i)==16)
            park = 1;

            if(~isnan(BP(prof,i)))
                bp(j) = BP(prof,i);
                bpt(j) = DATETIMENUM(prof,i);
                j=j+1;
            end
            if(~isnan(P(prof,i)))
                p(k) = P(prof,i);
                pt(k) = DATETIMENUM(prof,i);
                k=k+1;
            end
            if(outband==1) %went in band again, end time
                PID_end = DATETIMENUM(prof,i);
                fprintf('PID_end = %f, i=%d\n',PID_end,i);
                outband = 0;
                PID_time = PID_time + (PID_end-PID_start);
                fprintf('PID_time = %f, i=%d\n',PID_time,i);
            end    
            
        end
        if(BAND(prof,i)>1 && outband==0) %went out of band
            PID_start = DATETIMENUM(prof,i);
            fprintf('PID_start = %f, i=%d\n',PID_start,i);
            outband=1;
            %PID_time = PID_time + (PID_end-PID_start);
        end
    end
    if(park)
        trim = floor( size(bp,2)*.5 );
        bpAvg(l) = mean(bp(trim:size(bp,2)));
        pAvg(l) = mean(p(trim:size(p,2)));
        fprintf('Prof %d, bpAvg = %f, pAvg = %f\n',prof,bpAvg(l),...
            pAvg(l));
        
        subplot(2,1,1);hold on;grid on;
        xlabel('time');
        ylabel('dBar');
        s = plot( pt,p);
        plot([min(pt) max(pt)],...
            [pAvg(l) pAvg(l)],'k--');
        subplot(2,1,2);hold on;grid on;
        xlabel('time');
        ylabel('Bellows Position');
        plot( bpt,bp,'Color',get(s,'Color'))
        plot([min(bpt) max(bpt)],...
            [bpAvg(l) bpAvg(l)],'k--');
        
        l=l+1;
    end
    

    
end
datetick;
subplot(2,1,1);datetick;
figure;hold on;
plot(bpAvg,pAvg,'*');
xlabel('Avg Bellows Position');
ylabel('dBar');
grid on;
