%
%  gliderCTD_3DPlots.m
%
%  Purpose: Generate set of 3D plots of glider CTD data with bathymetry
%
%  Author:  William Stark
%           Marine Sciences Department
%           UNC-Chapel Hill
%
%  Created: 11 June 2012
%
%////////////////////////////////////////////////////////////////////////////////////

function gliderCTD_3DPlots(config, nLegEndPoints, strLegEndPoints,...
                           strDeploymentNumber, strLegNumber, legNumber, lonlim, latlim,...
                           ztop, zbottom, gpsLat, gpsLon, depth, pres,...
                           salinCorrected, salinBounds, densCorrected, densBounds,...
                           temp, tempBounds, chlor, chlorBounds,...
                           plotFlag_Temperature3D, plotFlag_Salinity3D,...
                           plotFlag_Density3D, plotFlag_Chlorophyll3D,...
                           plotFlag_AllGliderTracks)

                       
    % get start/end points strings and indices for this leg...
    nLegStart = nLegEndPoints(legNumber+1, 1);
    nLegEnd = nLegEndPoints(legNumber+1, 2);
    strLegStart = char(strLegEndPoints(legNumber+1, 1));
    strLegEnd = char(strLegEndPoints(legNumber+1, 2));
                                              
    % select data corresponding to the passed-in leg endpoints...
    gpsLat = gpsLat(nLegStart:nLegEnd);
    gpsLon = gpsLon(nLegStart:nLegEnd);
    pres = pres(nLegStart:nLegEnd);
    depth = depth(nLegStart:nLegEnd);
    temp = temp(nLegStart:nLegEnd);
    salinCorrected = salinCorrected(nLegStart:nLegEnd);
    densCorrected = densCorrected(nLegStart:nLegEnd);
    chlor = chlor(nLegStart:nLegEnd);
    
    % set strings for plot titles...
    strGliderName = config.glider_name;
    strDeployment = ['Deployment ', strDeploymentNumber];
    if (strcmp(strLegNumber, '0'))
        strLeg = 'Complete';
    else
        strLeg = ['Leg ', strLegNumber, '   ( ', strLegStart, ' to ', strLegEnd, ' )'];
    end
    
    
    
    % mooring locations LB1, LB2 and LB3...
    % LB1  (shelf):         33 10.172 N   78 20.007 W
    % LB2  (shelf break):   32 56.419 N   78 05.926 W
    % LB2  (upper slope):   32 51.142 N   78 00.793 W
    lb1Lat = 3300 + 10.172;   lb1Lon = -7800 - 20.007;
    lb2Lat = 3200 + 56.419;   lb2Lon = -7800 - 5.926;
    lb3Lat = 3200 + 51.142;   lb3Lon = -7800 - 0.793;
    
    % convert lats and lons to digital degrees...
    lb1Lat = ddmm2decdeg(lb1Lat);   lb1Lon = ddmm2decdeg(lb1Lon);
    lb2Lat = ddmm2decdeg(lb2Lat);   lb2Lon = ddmm2decdeg(lb2Lon);
    lb3Lat = ddmm2decdeg(lb3Lat);   lb3Lon = ddmm2decdeg(lb3Lon);

    % arrays for drawing vertical marker lines...
    LB1_X = [lb1Lon lb1Lon];   LB1_Y = [lb1Lat lb1Lat];   LB1_Z = [0 zbottom];
    LB2_X = [lb2Lon lb2Lon];   LB2_Y = [lb2Lat lb2Lat];   LB2_Z = [0 zbottom];
    LB3_X = [lb3Lon lb3Lon];   LB3_Y = [lb3Lat lb3Lat];   LB3_Z = [0 zbottom];
    
    
    % LOAD ETOPO1 BATHYMETRY ////////////////////////////////////////////////////////////
    % load etopo1 dataset...
    % etopo usage:  [map,maplegend] = etopo(dirname, scalefactor, latlim, lonlim)
    [Z,refvec] = etopo('BATHYMETRY/DATA/etopo/etopo1_bed_c.flt', 1, latlim, lonlim);
    % mask above sea-level (land) or below the passed-in depth (zbottom)
    idx = find(Z>0 | Z<zbottom);
    Z(idx) = NaN;
    [Nrows, Ncols]= size(Z);
    Xspace = linspace(lonlim(1), lonlim(2), Ncols);
    Yspace = linspace(latlim(1), latlim(2), Nrows);
    [XI, YI] = meshgrid(Xspace, Yspace);
    %////////////////////////////////////////////////////////////////////////////////////

    % OR...
    
    % LOAD COASTAL RELIEF MODEL (CRM) Vol 2 BATHYMETRY //////////////////////////////////
%     % load crm dataset...
%     samplefactor = 1;
%     [Z,refvec] = crmBinaryRead('BATHYMETRY/DATA/crm/se_atl_crm_v1.flt', samplefactor, latlim, lonlim);
%     % mask above sea-level (land) or below the passed-in depth (zbottom)
%     idx = find(Z>0 | Z<zbottom);
%     Z(idx) = NaN;
%     [Nrows, Ncols]= size(Z);
%     Xspace = linspace(lonlim(1), lonlim(2), Ncols);
%     Yspace = linspace(latlim(1), latlim(2), Nrows);
%     [XI, YI] = meshgrid(Xspace, Yspace);
    %////////////////////////////////////////////////////////////////////////////////////

    
    
    % load East coast border data set...
    load('BATHYMETRY/DATA/world/eastUS.mat');
    whichLAT = find(cillat<latlim(1) | cillat>latlim(2));
    cillat(whichLAT) = NaN*ones(size(whichLAT));
    clear whichLAT;
    whichLON = find(cillong<lonlim(1) | cillong>lonlim(2));
    cillong(whichLON) = NaN*ones(size(whichLON));
    clear whichLON;

    
    
    %***** DRAW 3D TEMPERATURE PLOT *****************************************************
    if (plotFlag_Temperature3D==1)
        % 3D color plot of temperature (with bathymetry surface)...
        figure('Position', [500,500,1600,900]);
        % plot the coastline...
        plot3(cillong, cillat, 0*ones(size(cillong)), 'k-', 'linewidth', [3]);
        hold on;        
        % plot the bathymetry surface...
        HndlBATH = surf(XI, YI, Z);
        %set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', [0.5 0.5 0.5]);
        set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', 'none');
        set(gca, 'box', 'on', 'position', [0.1227 0.2024 0.7727 0.6235]);    
        % lighting and shading bath...
        camlight right;
        lighting phong;
        material dull;
        set(HndlBATH, 'edgecolor', 'none');    
        hold on;
        % vertical marker lines at mooring locations
        plot3(LB1_X, LB1_Y, LB1_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB2_X, LB2_Y, LB2_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB3_X, LB3_Y, LB3_Z, 'k', 'linewidth', 5);
        hold on;
        % surface marker symbol at mooring locations
        plot3(lb1Lon, lb1Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb2Lon, lb2Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb3Lon, lb3Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        % plot temperature profile
        hc = ccplot3(gpsLon, gpsLat, -depth, temp, tempBounds, '.', 10);
        grid on;
        axis([lonlim latlim zbottom ztop]);
        hc = colorbar;
        set(hc, 'fontsize', 12);
        xlabel('Longitude', 'fontsize', 18);
        ylabel('Latitude', 'fontsize', 18);
        zlabel('Depth (m)', 'fontsize', 18);
        title(['TEMPERATURE (°C)  -  ', strGliderName, ' , ', strDeployment, ' , ', strLeg, '  '], 'fontsize', 20, 'fontweight', 'bold');

        % SAVE FILE and SAVE VIEW buttons
%         global prefilename pixcount HndlSAVE
%         pixcount = 1;
%         prefilename = 'etopo1_example';
%         HndlSAVE = uicontrol( ...
%             'Style','pushbutton', ...
%             'Units','normalized', ...
%             'Position',[.75 .05 .20 .05], ...
%             'String',['SAVE ' prefilename '_' sprintf('%02d', pixcount)], ...
%             'Callback',['save_fig;']); 
% 
%         HndlVIEW = uicontrol( ...
%             'Style','pushbutton', ...
%             'Units','normalized', ...
%             'Position',[.75 .00 .20 .05], ...
%             'String',['SAVE VIEW'], ...
%             'Callback',['[AZ, EL] = view; viewdata = [AZ, EL]; save(''./viewdata.mat'', ''viewdata'')']); 
    end


    %***** DRAW 3D SALINITY PLOT *****************************************************
    if (plotFlag_Salinity3D==1)
        % 3D color plot of salinity (with bathymetry surface)...
        figure('Position', [500,500,1600,900]);
        % plot the coastline...
        plot3(cillong, cillat, 0*ones(size(cillong)), 'k-', 'linewidth', [3]);
        hold on;
        % plot the bathymetry surface...
        HndlBATH = surf(XI, YI, Z);
        %set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', [0.5 0.5 0.5]);
        set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', 'none');
        set(gca, 'box', 'on', 'position', [0.1227 0.2024 0.7727 0.6235]);
        % lighting and shading bath...
        camlight right;
        lighting phong;
        material dull;
        set(HndlBATH, 'edgecolor', 'none');
        hold on;
        % vertical marker lines at mooring locations
        plot3(LB1_X, LB1_Y, LB1_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB2_X, LB2_Y, LB2_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB3_X, LB3_Y, LB3_Z, 'k', 'linewidth', 5);
        hold on;
        % surface marker symbol at mooring locations
        plot3(lb1Lon, lb1Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb2Lon, lb2Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb3Lon, lb3Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        % plot salinity profile
        hc = ccplot3(gpsLon, gpsLat, -depth, salinCorrected, salinBounds, '.', 10);
        grid on;
        axis([lonlim latlim zbottom ztop]);
        hc = colorbar;
        set(hc, 'fontsize', 12);
        xlabel('Longitude', 'fontsize', 18);
        ylabel('Latitude', 'fontsize', 18);
        zlabel('Depth (m)', 'fontsize', 18);
        title(['SALINITY (psu)  -  ', strGliderName, ' , ', strDeployment, ' , ', strLeg, '  '], 'fontsize', 20, 'fontweight', 'bold');
    end

    
    %***** DRAW 3D DENSITY PLOT *****************************************************
    if (plotFlag_Density3D==1)
        % 3D color plot of density (with bathymetry surface)...
        figure('Position', [500,500,1600,900]);
        % plot the coastline...
        plot3(cillong, cillat, 0*ones(size(cillong)), 'k-', 'linewidth', [3]);
        hold on;
        % plot the bathymetry surface...
        HndlBATH = surf(XI, YI, Z);
        %set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', [0.5 0.5 0.5]);
        set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', 'none');
        set(gca, 'box', 'on', 'position', [0.1227 0.2024 0.7727 0.6235]);
        % lighting and shading bath...
        camlight right;
        lighting phong;
        material dull;
        set(HndlBATH, 'edgecolor', 'none');
        hold on;
        % vertical marker lines at mooring locations
        plot3(LB1_X, LB1_Y, LB1_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB2_X, LB2_Y, LB2_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB3_X, LB3_Y, LB3_Z, 'k', 'linewidth', 5);
        hold on;
        % surface marker symbol at mooring locations
        plot3(lb1Lon, lb1Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb2Lon, lb2Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb3Lon, lb3Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        % plot density profile
        hc = ccplot3(gpsLon, gpsLat, -depth, densCorrected, densBounds, '.', 10);
        grid on;
        axis([lonlim latlim zbottom ztop]);
        hc = colorbar;
        set(hc, 'fontsize', 12);
        xlabel('Longitude', 'fontsize', 18);
        ylabel('Latitude', 'fontsize', 18);
        zlabel('Depth (m)', 'fontsize', 18);
        title(['DENSITY (kg m-3)  -  ', strGliderName, ' , ', strDeployment, ' , ', strLeg, '  '], 'fontsize', 20, 'fontweight', 'bold');
    end
    
    
    %***** DRAW 3D CHLOROPHYLL PLOT *****************************************************
    if (plotFlag_Chlorophyll3D==1)
        % 3D color plot of chlorophyll (with bathymetry surface)...
        figure('Position', [500,500,1600,900]);
        % plot the coastline...
        plot3(cillong, cillat, 0*ones(size(cillong)), 'k-', 'linewidth', [3]);
        hold on;
        % plot the bathymetry surface...
        HndlBATH = surf(XI, YI, Z);
        %set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', [0.5 0.5 0.5]);
        set(HndlBATH, 'facecolor', [0.75 0.75 0.75], 'edgecolor', 'none');
        set(gca, 'box', 'on', 'position', [0.1227 0.2024 0.7727 0.6235]);
        % lighting and shading bath...
        camlight right;
        lighting phong;
        material dull;
        set(HndlBATH, 'edgecolor', 'none');
        hold on;
        % vertical marker lines at mooring locations
        plot3(LB1_X, LB1_Y, LB1_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB2_X, LB2_Y, LB2_Z, 'k', 'linewidth', 5);
        hold on;
        plot3(LB3_X, LB3_Y, LB3_Z, 'k', 'linewidth', 5);
        hold on;
        % surface marker symbol at mooring locations
        plot3(lb1Lon, lb1Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb2Lon, lb2Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        plot3(lb3Lon, lb3Lat, 0, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','k', 'MarkerSize', 12);
        hold on;
        % plot chlorophyll profile
        hc = ccplot3(gpsLon, gpsLat, -depth, chlor, chlorBounds, '.', 10);
        grid on;
        axis([lonlim latlim zbottom ztop]);
        hc = colorbar;
        set(hc, 'fontsize', 12);
        xlabel('Longitude', 'fontsize', 18);
        ylabel('Latitude', 'fontsize', 18);
        zlabel('Depth (m)', 'fontsize', 18);
        title(['CHLOROPHYLL (ug/l)  -  ', strGliderName, ' , ', strDeployment, ' , ', strLeg, '  '], 'fontsize', 20, 'fontweight', 'bold');
    end
    
    
    %***** DRAW PLOT OF COMPLETE GLIDER TRACKS *****************************************************
    if (plotFlag_AllGliderTracks==1)
        % LOAD AND CONCATONATE ALL DATA FOR PELAGIA ///////////////////////////////    
        gpsLat_TOTAL_PELAGIA = [];
        gpsLon_TOTAL_PELAGIA = [];
        for i=1:3
            % mat file path string...
            strMatFilePath = strcat('GLIDER_DATA_LEVEL1/CTD/Pelagia_CTD_Deployment', num2str(i), '.mat');
            % load glider sensor data from mat file...
            load(strMatFilePath);
            % concatonate data into a single vector...
            gpsLat_TOTAL_PELAGIA = [gpsLat_TOTAL_PELAGIA; gpsLat];
            gpsLon_TOTAL_PELAGIA = [gpsLon_TOTAL_PELAGIA; gpsLon];
        end

        % LOAD AND CONCATONATE ALL DATA FOR RAMSES ////////////////////////////////    
        gpsLat_TOTAL_RAMSES = [];
        gpsLon_TOTAL_RAMSES = [];
        for i=1:3
            % mat file path string...
            strMatFilePath = strcat('GLIDER_DATA_LEVEL1/CTD/Ramses_CTD_Deployment', num2str(i), '.mat');
            % load glider sensor data from mat file...
            load(strMatFilePath);
            % concatonate data into a single vector...
            gpsLat_TOTAL_RAMSES = [gpsLat_TOTAL_RAMSES; gpsLat];
            gpsLon_TOTAL_RAMSES = [gpsLon_TOTAL_RAMSES; gpsLon];        
        end

        % set new lat/lon and sea bottom bounds for the 2D glider track plot...
        lonlim = [-79 -77];  latlim = [32 34];
        zbottom = -1100;  % 1100m depth encompasses all bathymetry data bounded by
                          % the above lat/lon limits

%         % load etopo1 dataset...
%         % etopo usage:  [map,maplegend] = etopo(dirname, scalefactor, latlim, lonlim)
%         [Z,refvec] = etopo('BATHYMETRY/DATA/etopo/etopo1_bed_c.flt', 1, latlim, lonlim);
%         % mask above sea-level (land) or below the passed-in depth (zbottom)
%         idx = find(Z>0 | Z<zbottom);
%         Z(idx) = NaN;
%         [Nrows, Ncols]= size(Z);
%         Xspace = linspace(lonlim(1), lonlim(2), Ncols);
%         Yspace = linspace(latlim(1), latlim(2), Nrows);
%         [XI, YI] = meshgrid(Xspace, Yspace);
% 
%         % load East coast border data set...
%         load('BATHYMETRY/DATA/world/eastUS.mat');
%         whichLAT = find(cillat<latlim(1) | cillat>latlim(2));
%         cillat(whichLAT) = NaN*ones(size(whichLAT));
%         clear whichLAT;
%         whichLON = find(cillong<lonlim(1) | cillong>lonlim(2));
%         cillong(whichLON) = NaN*ones(size(whichLON));
%         clear whichLON;    

        % plot of complete glider tracks (all 3 deployments) with contour lines...
        figure('Position', [500,500,1200,1200]);
        % plot the coastline...
        plot(cillong, cillat, 'k-', 'linewidth', [5]);
        hold on;
        % plot the bathymetry contours (black lines) and labels...
        [C,h] = contour(XI, YI, -Z, [20 30 60 120 200 300 400 500 600 700 800 900 1000], 'LineColor', [0 0 0]);
        clabel(C, h, 'FontSize', 14);
        hold on;
        % plot the complete tracks for Pelagia...
        plot(gpsLon_TOTAL_PELAGIA, gpsLat_TOTAL_PELAGIA, 'b.', 'MarkerSize', 15);
        hold on;
        % plot the complete tracks for Ramses...
        plot(gpsLon_TOTAL_RAMSES, gpsLat_TOTAL_RAMSES, 'r.', 'MarkerSize', 15);
        hold on;
        % draw symbol at each mooring location
        plot(lb1Lon, lb1Lat, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','g', 'MarkerSize', 15);
        hold on;
        plot(lb2Lon, lb2Lat, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','g', 'MarkerSize', 15);
        hold on;
        plot(lb3Lon, lb3Lat, 'ko', 'LineWidth', 3, 'MarkerEdgeColor','k', 'MarkerFaceColor','g', 'MarkerSize', 15);
        axis([lonlim latlim]);
        xlabel('Longitude', 'fontsize', 18);
        ylabel('Latitude', 'fontsize', 18);
        title(['Pelagia (Blue) and Ramses (Red) - Complete Glider Tracks    '], 'fontsize', 20, 'fontweight', 'bold');
    end


end
