%prof_compact1.m

clear;

fp = '2016Jul07';
path = sprintf( '../%s/parsed/CPF%s.mat',fp,fp);
load(path');

num_prof = size(P,1);
num_dat = size(P,2);


max_depths = 117;
depth = 500;

%     public struct DepthTable
%     {
%         public float depth;
%         public float PV;
%         public byte sampleList;
%         public TimeSpan parkTime;
%         public double T;
%         public double S;
%         public int datnum;
%     }


ascendTable = struct('depth',nan(num_prof,max_depths),...
                     'T',zeros(num_prof,max_depths),...
                     'S',zeros(num_prof,max_depths),...
                     'datnum',zeros(num_prof,max_depths));
for i=1:1:max_depths
    if(depth>20)
        ascendTable.depth(:,i) = depth;
        depth = depth-5;
    else
        ascendTable.depth(:,i) = depth;
        depth = depth-2;
    end
end


for prof=1:1:num_prof
    for dat = 1:1:num_dat;
        
    %bounds checking first
    if( P(prof,dat)<0 || P(prof,dat)>500) P(prof,dat)=0;end
    if( T(prof,dat)<0 || T(prof,dat)> 30) T(prof,dat)=0;end
    if( S(prof,dat)<0 || S(prof,dat)> 37) S(prof,dat)=0;end
    
    
    %find index in ascendTable to start at
    PbinIndex = 1;
    while (PbinIndex < max_depths)
         if (P(prof,dat) > ascendTable.depth(prof,PbinIndex) )
             break
         end
         PbinIndex= PbinIndex+1;
    end

    %load up the T and S
    if (PbinIndex ~= max_depths)

            %found a valid place to put the PTS data
            ascendTable.T(prof,PbinIndex) = ascendTable.T(prof,PbinIndex) + T(prof,dat);
            ascendTable.S(prof,PbinIndex) = ascendTable.S(prof,PbinIndex) + S(prof,dat);
            ascendTable.datnum(prof,PbinIndex) = ascendTable.datnum(prof,PbinIndex)+1; 
    end
    
    end %end for dat
    
    %do the profile average
    fprintf('Profile %d:\n',prof);
    for i=1:1:max_depths
        if( ascendTable.datnum(prof,i)>0 ) %we have data
            ascendTable.T(prof,i) = ascendTable.T(prof,i)/ascendTable.datnum(prof,i);
            ascendTable.S(prof,i) = ascendTable.S(prof,i)/ascendTable.datnum(prof,i);
            fprintf('%d,%f,%f\n',ascendTable.depth(prof,i),ascendTable.T(prof,i),ascendTable.S(prof,i));
        end
    
    end %end doing profile avg
    
end %end for each profile







