% getCPFdata10.m

% Extract science data from all engineering files from a deployment
% directory

% 10/10/16 fixed cp data parsing problem - only pars lines w 3 csv's
tic
% ************************************************************************
% SET DIRS AND PATHS AND BUILD FILE LIST
deploy_dir = '2017Jan24-27';
%deploy_dir = '2017Mar09-13';

data_dir    = '\\atlas\ProjectLibrary\CPF\Data\CPF-P2\Paragon Tests\';
deploy_path = [data_dir, deploy_dir, '\LogFiles\'];

file_list = ls([deploy_path,'*.eng']);

% ************************************************************************
% SET SWITCHES, DEFINE SOME LISTS
% ************************************************************************
fig_switch =[0 0 1 1 0]; % 1 to display figure

% Define columns to keep in engineering file. These columns may then have
% the desired data to parse
keep_vars = {'Date', 'Time', 'State', 'Comment', 'Pressure', ...
    'CTD Sal', 'FLBB', 'Topt','NO3','pH','GPS'};

% Define the states to look for data in
states = {'Surface Ops' 'Anchor' 'Ascend' 'Dump CP Data'};

% ***********************************************************************
% SET SOME FORMAT STRINGS & CALIBRATIONS
% ***********************************************************************
FLBB_format = '99/99/99,99:99:99,%*f,%f,%*f,%f,%f';
% FLBB CALIBRATION MATRIX (COUNTS)
% [ID CHL_DC CHL_Scale BSCAT_DC BSCAT_SCALE]
FLBB =3310;
FLBB_cal = [3310, 46, 0.0073, 45, 1.671E-06]; % For instrument 3310

gps_format    = '%*s %*s %*s %f %s %f %s';

O2_format     = ['%*s%*s%*s%*s%f%*s%f%*s%f%*s%f%*s%f%*s%f%*s%*f', ...
    '%*s%*f%*s%*f%*s%*f'];

% ***********************************************************************
% ***********************************************************************
% BUILD FORMAT STRING TO DO FIRST ROUND OF PARSING BASED ON HEADER LINE
% AND DESIRED COLUMNS DETERMINED FROM "keep_vars"
%
% $	   Date	  Time	State	Comment	Pressure	Bel Pos	Batt Volt
% CTD Temp	CTD Sal	 LPS331 Press	LPS311 Temp	  SHT21 Humid	 SHT21 Temp
% FLBB	Topt	Tphase	Rphase	NO3	pH	LPF PVel
% Diff PVel 	LPF PAcc	Press Avg	Press Var	PID SP	PID PV
% PID Y1	PID Y2	PID I	PID v	PID u	PID uCPS
% Batt Amps	 12V Amps	3.3V Amps	Debug	GPS	Irid Modem
% ***********************************************************************
surface_out   = [];
anchor_out = [];
ascend_out = [];

for prof_ct = 1: size(file_list,1)
    fname     = strtrim(file_list(prof_ct,:));
    %fname     = strtrim(file_list(12,:));
    fid       = fopen([deploy_path,fname]);
    
    tline     = fgetl(fid); % 1st line of data is always header line
    hdr_vars  = textscan(tline,'%s','Delimiter','\t');
    hdr_vars  = hdr_vars{1,1};
    
    ct = 0;
    txt_format = '';
    for i = 1:length(hdr_vars) % Finish building format string
        hdr_test = strcmp(hdr_vars{i,1},keep_vars);
        if sum(hdr_test) == 0
            txt_format = [txt_format,' %*s']; % Un-wanted column heade
        else
            txt_format = [txt_format,' %s'];  % desired column header
            ct = ct+1;
            txt_hdr(1,ct) = hdr_vars(i,1); %Header for discovered var
        end
    end
    
    % *************************************************************************
    % GET INDICES FROM  "saved_vars" IF THEY EXIST
    % *************************************************************************
    Date_col  = find(strcmp('Date',txt_hdr));
    Time_col  = find(strcmp('Time',txt_hdr));
    state_col = find(strcmp('State',txt_hdr));
    comnt_col = find(strcmp('Comment',txt_hdr));
    pres_col  = find(strcmp('Pressure',txt_hdr));
    CTD_col   = find(strcmp('CTD Sal',txt_hdr));
    FLBB_col  = find(strcmp('FLBB',txt_hdr));
    Topt_col  = find(strcmp('Topt',txt_hdr));
    NO3_col   = find(strcmp('NO3',txt_hdr));
    pH_col    = find(strcmp('pH',txt_hdr));
    GPS_col   = find(strcmp('GPS',txt_hdr));
    
    % *************************************************************************
    % BRING DATA TXT STRINGS INTO CELL ARRAY
    % *************************************************************************
    txt_data = textscan(fid, txt_format, 'Delimiter','\t');
    fclose(fid);
    clear ct tline hdr_test i fid
    
    % *************************************************************************
    % *************************************************************************
    %                         NOW CONVERT TEXT TO NUMBERS
    % *************************************************************************
    % *************************************************************************
    [rows,~] = size(txt_data{1,2}); % Will be sdn and decimal seconds
    time_stamp  = ones(rows,2)*NaN; %predimmension
    
    % *************************************************************************
    % PARSE TIME STAMP
    % *************************************************************************
    time_stamp(:,1) =  datenum(txt_data{1,Date_col}, 'dd-mmm-yyyy'); % Convert day to SDN
    for i = 1:rows
        t_tmp = sscanf(txt_data{1,Time_col}{i},'%f:%f:%f');
        time_stamp(i,2) = t_tmp(1)*3600 + t_tmp(2)*60 + t_tmp(3) ;%seconds in day
    end
    time_stamp(:,2) = time_stamp(i,2) ./ 24 ./3600; % fraction of day
    time_stamp(:,1) = time_stamp(:,1) + time_stamp(:,2); % decimal SDN
  
    % *************************************************************************
    % NEXT GET GPS FIX(S)
    % gps data returns cell { 'lat' 'N or S' 'lon' 'E or W'}
    % *************************************************************************
    fix_ind = find(strncmp('UBX',txt_data{1,GPS_col},3));
    
    % get gps string
    if ~isempty(fix_ind)
        lat = ones(length(fix_ind),1)*NaN; % predim, the size should usually be 1
        lon = lat;
        GPS = ones(length(fix_ind),3) * NaN;
        
        for i = 1:length(fix_ind) % usually only 1 fix per cycle file
            gps = textscan(txt_data{1,GPS_col}{fix_ind(i)}, gps_format, 1,...
                'Delimiter',','); % Only use format string once
            lat = fix(gps{1}/100) + rem(gps{1}/100,fix(gps{1}/100))*100/60;
            lon = fix(gps{3}/100) + rem(gps{3}/100,fix(gps{3}/100))*100/60;
            if strcmp(gps{2},'S')
                lat = lat * -1;
            end
            if strcmp(gps{4},'W')
                lon = -lon + 360;
            end
            GPS(i,:) = [time_stamp(fix_ind(i),1), lon, lat]; %sdn lon lat
        end
        GPS = median(GPS,1);
    else
        disp('NO GPS FIX FOUND IN DATA FILE!')
    end
    clear fix_ind lat lon i
    
    
    % *************************************************************************
    % OK NOW STEP THROGH LISTED STATES AND LOOK FOR LISTED VARIABLES
    % Build matrices of data for each state
    % *************************************************************************
    profile_num = NaN; % predim
    hdr = {'SDN' 'hour of day' 'Cycle #' 'Lon' 'Lat' 'Pressure' ...
           'Temperature','Salinity'};
    hdr = [hdr 'Oxygen[uM]', 'Oxygen[%Sat]','Oxygen[TºC]'];
    hdr = [hdr, 'CHL' 'BSCAT'];
    
    for i = 1:length(states)
        state_ind = strcmp(states{i},txt_data{1,state_col}); %col vec 1= state
        if sum(state_ind) > 0
            tmp = cellfun(@(x) x(state_ind), txt_data, 'UniformOutput',false);
            
            d  = ones(sum(state_ind),13)*NaN; %predim matrix for data
            d(:,1:2) = time_stamp(state_ind,:); % add time
            d(:,4)   = GPS(2); % Add lon
            d(:,5)   = GPS(3); % Add lat

            % ********************************************************************
            % PARSE CTD STRINGS
            % STRING & COMMENT DIFF FOR DIFF STATES KIND OF A PAIN
            SBE_ct = 3; % 1 or 3 p vs pst
            if strcmp('Surface Ops', states{i})
                SBE_ind = find(strncmp('SBE41',tmp{1,comnt_col},5));
                sbe_format = '%f';
                SBE_ct = 1;
                
                % GET PROFILE NUMBER WHILE I AM HERE
                st1 = strncmp('Profile Number',tmp{1,4},7);
                if sum(st1) > 0
                    s1  = tmp{1,4}{st1};
                    if ~isempty(s1)
                        profile_num = str2num(regexp(s1,'(?<=\=\s*)\d+', ...
                                      'match','once'));
                        disp([num2str(profile_num), '   ',fname])
                    end
                end
                
            elseif strncmp('Anchor', states{i},4)
                SBE_ind = find(strncmp('SBE41',tmp{1,comnt_col},5));
                sbe_format = '%f,%f,%f';
                
            elseif strncmp('Ascend', states{i},4)
                SBE_ind = find(strncmp('SBE41',tmp{1,comnt_col},5));
                sbe_format = '%f,%f,%f';
                
            elseif strncmp('Dump', states{i},4)
                SBE_ind = find(strncmp('Unparsed',tmp{1,comnt_col},8));
                %sbe_format = '%04x%04x%04x%*02x'; %exclude bin count for now
                sbe_format = '%f,%f,%f,%*s';
                
            else % ALL OTHER STATES (REALLY A CATCH ALL FOR NOW)
                SBE_ind = find(strncmp('SBE41',tmp{1,comnt_col},5));
                sbe_format = '%f,%f,%f';
            end
            
            if ~isempty(SBE_ind)
                for j = 1:length(SBE_ind) % PUT NUMBERS IN MATRIX
                    str = strtrim(tmp{1,CTD_col}{SBE_ind(j)}); % get psal str
                    if regexp(str,'^\d') % psal line starts with number
                        ctd = sscanf(str,sbe_format);
                        if max(size(ctd)) == SBE_ct % actual = expected?
                            d(SBE_ind(j),6:6+SBE_ct-1) = ctd;
                        end
                    end
                end
            end
            % ********************************************************************
            % PARSE O2 STRINGS - 3 types of strings!!!
%             hdr = [hdr 'Oxygen[uM]', 'Oxygen[%Sat]','Oxygen[TºC]', ...
%                 'CalPhase[Deg]','TCPhase[Deg]', 'C1RPh[Deg]']; 
            O2_ind1 = find(strncmp('MEAS',tmp{1,Topt_col},4)); % New ver
            O2_ind2 = find(strncmp('%!M',tmp{1,Topt_col},3));  % new ver
            O2_ind3 = find(strncmp('%#',tmp{1,Topt_col},3));  % new ver
            O2_ind = [O2_ind1; O2_ind2; O2_ind3];
            if ~isempty(O2_ind)
                for j = 1:length(O2_ind) % PUT NUMBERS IN MATRIX
                    O2 = cell2mat(textscan(tmp{1,Topt_col}{O2_ind(j)}, ...
                        O2_format,1,'Delimiter',',', 'CollectOutput',1));
                    d(O2_ind(j),9:11) = O2(1:3);
                    %                 d(O2_ind(j),3) = sscanf(tmp{1,pres_col}{O2_ind(j)},'%f');
                end
            end 
            
            % ********************************************************************
            % PARSE FLBB STRINGS
            
            FLBB_ind = find(strncmp('99/',tmp{1,FLBB_col},3));
            if ~isempty(FLBB_ind)
                for j = 1:length(FLBB_ind) % PUT NUMBERS IN MATRIX
                    flbb = (sscanf(tmp{1,FLBB_col}{FLBB_ind(j)}, ...
                            FLBB_format))';                    
                    d(FLBB_ind(j),12:13) = flbb(1:2);
                    %d(FLBB_ind(j),3) = sscanf(tmp{1,pres_col}{FLBB_ind(j)},'%f');
                end
            end
            
            % *******************************************************************
            
            %             *** ADD NO3 & pH LOOPS WHEN NEEDED ***
            
            % *******************************************************************
            
            %    SORT DATA BY TIME BEFORE ANY TABLE LOOKUP TYPE OPPERATION
            %    DATA IN TXT FILE IS ASYNC WITH TIME DUE TO ALL THE ASYN TASKS
            [~,IX] = sort(d(:,1)); % Sort data by time due to async dataflow
            d = d(IX,:); % RAW DATA SORTED BY TIMESTAMP
            d(:,3) = profile_num;
            
            % *******************************************************************
            % EXTRACTION COMPLETED NOW CLEAN UP AND CONVERT #'S BY STATE
            % *******************************************************************
            if strcmp('Ascend', strtrim(states{i})) || ...
                    strcmp('Anchor', strtrim(states{i})) || ...
                    strcmp('Surface Ops', strtrim(states{i}))
                disp(states{i})
                % Match data - closet neighboor
                % MERGE ASCENDING DATA - 'Sampling Instruments' COMMENT
                % FOR SAMPLE COUNT, CTD FOR TIME STAMP
                % FOLLOW SIMPLE RULE:
                %  1)  GET 1st SAMPLE IN TIME FOR EACH INSTRUMENT AFTER
                %     "Sampling Instruments" COMMENT
                
                % GET ROW INDICES FOR START OF INSTUMENT SAMPLING, AS WELL AS
                % INDICIES FOR INDIVIDUAL RETURNED CTD, O2 & FLBB SAMPLES
                
                samp_ind = find(strcmp('Sampling Instruments',tmp{1,comnt_col}));
                t_ctd    = find(~isnan(d(:,6))); % Get CTD indices
                t_o2     = find(~isnan(d(:,9))); % Get O2 indices
                t_flbb   = find(~isnan(d(:,12))); % Get FLBB indices
                
                if strcmp('Surface Ops', strtrim(states{i}))
                    samp_ind = find(strcmp('State Entry',tmp{1,comnt_col}));
                    t_flbb   = []; % No good flbb at suface
                end
                
                lr_data = ones(size(samp_ind,1),size(d,2))*NaN; % predim merged
                
                % CTD WILL BE MASTER TIME STAMP (EXCEPT FOR SURFACE OPS)
                for j = 1: length(samp_ind)
                    % FIND INDICES IN d FROM INDIVIDUAL SAMPLE INDICE VECTORS
                    ind_ctd = find(t_ctd >= samp_ind(j),1,'first'); % 1st CTD after samp
                    ind_o2 = find(t_o2 >= samp_ind(j),1,'first'); % 1st o2 after samp
                    ind_flbb = find(t_flbb >= samp_ind(j),2,'first'); %first 2 FLBB after samp
                    
                    % MERGE DATA
                    if ~isempty(ind_ctd)
                        lr_data(j,1:8) = d(t_ctd(ind_ctd),1:8); % time and ctd
                    end
                    if ~isempty(ind_o2)
                        lr_data(j,9:11) = d(t_o2(ind_o2),9:11); % O2 added
                    end
                    if ~isempty(ind_flbb)
                        lr_data(j,12:13) = mean(d(t_flbb(ind_flbb),12:13),1); % Added avged 2 FLBB
                    end
                end
                
                % CORRECT O2 FOR SALINITY & DEPTH
                % Benson & Krause (cm^3/dm^3) *** USE THESE COEFFICIENTS!!!! ***
                pA = [3.88767 -0.256847 4.94457 4.05010 3.22014 2.00907]; % Temperature Coeff
                pB = [-8.17083e-3 -1.03410e-2 -7.37614e-3 -6.24523e-3]; % Salinity coff
                Co = -4.88682e-7;
                
                O2_volume =  22.3916;
                
                % SALINITY CORRECTION
                T = lr_data(:,7);
                S = lr_data(:,8);
                if strcmp('Surface Ops', strtrim(states{i}))
                    T = lr_data(:,11);   % Optode T for Air measurements
                    S = lr_data(:,11)*0; % Optode S=0 for Air measurements
                end
                
                Ts     = log((298.15 - T)./(273.15 + T));
                part1  = polyval(pB,Ts);
                S_corr = S.*part1 + S.^2 * Co;
                L      = polyval(pA,Ts) + S_corr;
                O2sol  = (1000/O2_volume) * exp(L);
                
                O2c = lr_data(:,9) .* exp(S_corr); % Aanderaa S correction to O2 concentration
                
                % DEPTH COMPENSATION - 3.2% is an emperical value from Uchida 2008
                O2c = O2c .* ((lr_data(:,6) * 0.032/1000) + 1);

                lr_data(:,9) = O2c; % S adjusted C
                lr_data(:,10) = O2c./O2sol*100; %S adjusted % sat
                
                
                % CONVERT FLBB TO USEFUL(RELATIVELY) NUMBERS
                if exist('FLBB','var') && ...
                        ~strcmp('Surface Ops', strtrim(states{i}))
                    cal_ind = find(FLBB_cal(:,1) == FLBB,1,'first');
                    if ~isempty(cal_ind)
                        lr_data(:,12) = (lr_data(:,12) - FLBB_cal(cal_ind,2)) .* ...
                            FLBB_cal(cal_ind,3); % CHL
                        
                        lr_data(:,13) = (lr_data(:,13) - FLBB_cal(cal_ind,4)) .* ...
                            FLBB_cal(cal_ind,5); % Beta_measred,  m^-1 sr^-1
                    end
                end              
                
                if strcmp('Surface Ops', strtrim(states{i}))
                    Surface = lr_data;
                end
                if strcmp('Ascend', strtrim(states{i}))
                    Ascend = lr_data;
                end
                if strcmp('Anchor', strtrim(states{i}))
                    Anchor = lr_data;
                end
            end
            
            
            if strncmp('Dump', states{i},4)
                % NO MATCHING NEEDED - Just QUICK CLEAN UP OF DATA MATRIX
                tNaN = sum(~isnan(d(:,6:end)),2) == 0; % rows with no CTD data
                cp_data = d(~tNaN,:);
                t0 = sum(cp_data(:,6:8),2) == 0;
                cp_data(t0,:)=[];
            end
            
        end
        
    end
    
    % MAKE MASTER FILES FOR DEPLOYMENT
    if exist('Ascend', 'var')
        ascend_out = [ascend_out; Ascend];
        [~,IX] = sort(ascend_out(:,1));
        ascend_out = ascend_out(IX,:);
        t1 = isnan(ascend_out(:,3));
        ascend_out(t1,3) = 1; % quick fix for no profile #1
    end
    
    if exist('Anchor', 'var')
        anchor_out = [anchor_out; Anchor];
        [~,IX] = sort(anchor_out(:,1));
        anchor_out = anchor_out(IX,:);end
    
    if exist('Surface', 'var')
        surface_out = [surface_out; Surface];
        [~,IX] = sort(surface_out(:,1));
        surface_out = surface_out(IX,:);
    end
    
    
    
end

% GET SOME INDICES FOR PLOTTING
iSDN  = find(strcmp('SDN',hdr));   
iC    = find(strcmp('Cycle #',hdr)); 
iP    = find(strcmp('Pressure',hdr)); 
iT    = find(strcmp('Temperature',hdr)); 
iS    = find(strcmp('Salinity',hdr)); 
iO    = find(strcmp('Oxygen[uM]',hdr)); 
iOsat = find(strcmp('Oxygen[%Sat]',hdr)); 
iOt   = find(strcmp('Oxygen[TºC]',hdr));
iCHL  = find(strcmp('CHL',hdr)); 
iB    = find(strcmp('BSCAT',hdr)); 



% MAKE ODV LIKE *.TXT FILES
% ************************************************************************
% BUILD LOOK UP CELL ARRAY to match variables and set format string
% ************************************************************************
% ADD A FEW VARIBLES FOR THE ODV FILE
psurf = surface_out;
%RAW ODV FILE
ODV_raw(1,:)  = {'Pressure[dbar]'        '%0.2f' 'Pressure'};
ODV_raw(2,:)  = {'Temperature[°C]'       '%0.4f' 'Temperature'};
ODV_raw(3,:)  = {'Salinity[pss]'         '%0.4f' 'Salinity'};
ODV_raw(4,:)  = {'Oxygen[µmol/kg]'       '%0.1f' 'Oxygen[uM'};
ODV_raw(5,:)  = {'OxygenSat[%]'          '%0.1f' 'Oxygen[%Sat]'};
ODV_raw(6,:)  = {'Chl_a[mg/m^3]'         '%0.4f' 'CHL'};
ODV_raw(7,:) = {'beta_700[1/(m sr)]'    '%0.6f' 'BSCAT' };





% Cruise	Station	Type	mon/day/yr	hh:mm	Lon [°E]	Lat [°N]	QF	Pressure[dbar]	QF	Temperature[°C]	QF	Salinity[pss]	QF	Sigma_theta[kg/m^3]	QF	Depth[m]	QF	Oxygen[µmol/kg]	QF	OxygenSat[%]	QF	Nitrate[µmol/kg]	QF	Chl_a[mg/m^3]	QF	b_bp700[1/m]

% ************************************************************************
% ************************************************************************
%                             MAKE SOME PLOTS
% ************************************************************************
% ************************************************************************


if fig_switch(1) == 1 & exist('Ascend','var')
    
    figure(1)
    set(gcf,'Units', 'Normalized');
    set(gcf,'Position',[0.2, 0.2, 0.6, 0.7]);
    set(gcf,'NumberTitle','Off');
    set(gcf,'Name',' CPF ASCEND DATA PLOTS');
    
    h_bnds  = [0.1 1.0];
    v_bnds  = [0.1 1.0];
    h_plots = 3; % horiz plots
    v_plots = 2; % vert plots
    
    pos = make_SubplotPos(h_bnds,v_bnds, h_plots, v_plots); % [L B W H]
    pos(1:3,2) = pos(1:3,2) - 0.025;
    pos(:,2) = pos(:,2) - 0.025;
    
    a1(1) = axes('Position',pos(1,:));
    plot(Ascend(:,iT),Ascend(:,iP),'bo')
    hold on
    plot(Ascend(:,iOt),Ascend(:,iP),'go')
    plot(cp_data(:,iT),cp_data(:,iP),'k-','LineWidth',2)
    hold off
    set(gca,'Ydir','Reverse')
    ylabel('Pressure, mbar')
    xlabel('Temperature, C')
    %title(fname)
    legend('low res', 'Oxyegen T', 'cp', 'Location','SouthEast')
    
    a1(2) = axes('Position',pos(2,:));
    plot(Ascend(:,iS),Ascend(:,iP),'bo')
    hold on
    plot(cp_data(:,iS),cp_data(:,iP),'k-','LineWidth',2)
    hold off
    set(gca,'Ydir','Reverse')
    %ylabel('Pressure, mbar')
    xlabel('Salinity, psu')
    %title(datestr(GPS(1),'mm/dd/yy'))
    
    a1(3) = axes('Position',pos(3,:));
    plot(Ascend(:,iO),Ascend(:,iP),'ro')
    hold on
    plot(O2c, lr_data(:,iP),'bo')
    plot(O2sol, lr_data(:,iP),'ko')
    hold off
    
    set(gca,'Ydir','Reverse')
    %ylabel('Depth, m')
    xlabel('Oxygen, µM')
    %s1 =[num2str(GPS(2),'%3.3f'),' N & ',num2str(GPS(3),'%3.3f'), ' E'];
    %title(s1)
    set(gca, 'Units', 'normalized')
    leg3 = legend('raw','S cor', ' O2sol');
    ax_pos = get(gca,'Position');
    leg_pos = [ax_pos(1)+ax_pos(3)/2, ax_pos(2)+ax_pos(4)+0.005, 0.1, 0.075];
    
    set(leg3, 'Position',leg_pos)
    
    
    a1(4) = axes('Position',pos(4,:));
    plot(Ascend(:,iCHL),Ascend(:,iP),'bo')
    set(gca,'Ydir','Reverse')
    ylabel('Pressure, mbar')
    xlabel('CHL, µg/L')
    
    a1(5) = axes('Position',pos(5,:));
    plot(Ascend(:,iB),Ascend(:,iP),'bo')
    set(gca,'Ydir','Reverse')
    %ylabel('Depth, m')
    xlabel('Beta, m^{-1}sr^{-1}')
    
    a1(6) = axes('Position',pos(6,:));
    plot(Ascend(:,iSDN),Ascend(:,iP),'b-','LineWidth',2)
    set(gca,'Ydir','Reverse')
    datetick('x','HH:MM')
    %ylabel('Depth, m')
    xlabel('Time')
    
    txt_ax = axes('units','normalized','Position',[0 0 1 1],...
        'Visible', 'off');
    txt1_str = {['Coastal Profiling float file : ',fname,', Profile ',num2str(profile_num)], ...
        datestr(GPS(1),'mmm dd yyyy'), ...
        [num2str(GPS(2),'%3.3f'),' E & ',num2str(GPS(3),'%3.3f'), ' N']};
    
    txt1 = text(0.5, 0.93, txt1_str, 'fontsize', 16,...
        'HorizontalAlignment', 'center');
end

if fig_switch(2) == 1
    
    figure(2)
    set(gcf,'Units', 'Normalized');
    set(gcf,'Position',[0.2, 0.2, 0.6, 0.7]);
    set(gcf,'NumberTitle','Off');
    set(gcf,'Name',' CPF PARK DATA PLOTS');
    
    h_bnds  = [0.1 1.0];
    v_bnds  = [0.1 1.0];
    h_plots = 1; % horiz plots
    v_plots = 4; % vert plots
    
    pos = make_SubplotPos(h_bnds,v_bnds, h_plots, v_plots); % [L B W H]
    pos(1:3,2) = pos(1:3,2) - 0.025;
    pos(:,2) = pos(:,2) - 0.025;
    
    a1(1) = axes('Position',pos(1,:));
    plot(Ascend(:,iSDN),Ascend(:,iP),'bo')
    hold on
    plot(cp_data(:,iSDN),cp_data(:,iP),'k-','LineWidth',2)
    hold off
    set(gca,'Ydir','Reverse')
    ylabel('Pressure, mbar')
    xlabel('Temperature, C')
    %title(fname)
    legend('low res', 'cp', 'Location','SouthEast')

end
IND = iT;
% Waterfall Plot for Gene
if fig_switch(3) == 1
    figure(3);
    FS = 16;
     % Choose variable
    cycles = unique(ascend_out(:,iC));
    x_lim = [min(ascend_out(:,iSDN)) max(ascend_out(:,iSDN))];
    y_lim = [min(ascend_out(:,IND)) max(ascend_out(:,IND))];
    for i = 1:size(cycles,1)
        t1 = ascend_out(:,iC) == cycles(i);
        tmp = ascend_out(t1,:);
        
        % QUICK FIX FOR REPEATED PROFILES
        [~,ia,~] = unique(tmp(:,iP));
        tmp = tmp(ia,:);
        
        
        
        
        plot3(tmp(:,iSDN),tmp(:,IND),tmp(:,iP), 'LineWidth', 2)
        %plot3(tmp(:,iSDN),tmp(:,IND),tmp(:,iP),'k-', 'LineWidth', 2)
        if i == 1
            set(gca, 'Xlim',x_lim)
            set(gca, 'Ylim',y_lim)
            set(gca,'ZDir', 'Reverse')
            zlabel('Depth, m','FontSize', FS)
            ylabel(hdr{IND}, 'FontSize', FS)
            grid on
            hold on
        end
    end
end
hold off
datetick('x','mm/dd HH:MM','keeplimits','keepticks')
    
    
% Waterfall Plot for Gene
if fig_switch(4) == 1
    figure(4);
    FS = 16;

    cycles = unique(ascend_out(:,iC));
    max_depth = ceil(max(ascend_out(:,iP)));
    data_lim = [min(ascend_out(:,IND)) max(ascend_out(:,IND))];
    
    % BUILD Matrices for countour plot
    Z = (1:0.5: max_depth)';
    SDN = (ones(size(cycles))* NaN);
    data = ones(size(Z,1),size(cycles,1)) * NaN;
    for i = 1:size(cycles)
        t1 = ascend_out(:,iC) == cycles(i);
        tmp = ascend_out(t1,:);
        % QUICK FIX FOR REPEATED PROFILES
        [~,ia,~] = unique(tmp(:,iP));
        tmp = tmp(ia,:);
        
        SDN(i) = tmp(1,iSDN);
        data(:,i) = interp1(tmp(:,iP),tmp(:,IND),Z);
    end
    
    contourf(SDN,Z,data,20,'linecolor', 'none')
    if strcmp(hdr{IND},'CHL')
        str ='Chl (µg L^{-1}) ';
        title({'CPF Trial  Jan 24-27 2017', str})
    elseif strcmp(hdr{IND},'BSCAT')
        str ='Backscatter  (m^{-1}sr^{-1})';
        title({'CPF Trial  Jan 24-27 2017', str})
    else
        title({'CPF Trial  Jan 24-27 2017', hdr{IND}})
    end

        
    set(gca, 'FontSize', FS);
    caxis(data_lim);
    set(gca,'Ydir', 'reverse')
    
    ylabel('Depth, m','FontSize', FS)
    colorbar
    
    set(gca, 'FontSize', FS);
    
    hold on
    for j= 1:size(cycles,1)
        t1 = ascend_out(:,iC) == cycles(j);
        tmp = ascend_out(t1,:);
        plot(tmp(:,iSDN),tmp(:,iP),'ko', 'MarkerSize',2)
    end
    hold off
    datetick('x', 'mm/dd', 'keeplimits')
end
        
    
    

    
    
    
    
    
toc
    
 