%%%% API to grab platform data from Argovis

clear all

%%%% set platform
plat_bufr = '2902747';%'5905646';%'2902747';%'5904468';%'5905268';%'4900141';%;%;%';%'5905268';%
%%%%
URL_name  = 'https://argovis.colorado.edu/';%'http://206.189.72.50:3000/';

url = [URL_name 'catalog/platforms/' plat_bufr '/']

%%%% set options for webread
options = weboptions('Timeout',20,'UserAgent', 'http://www.whoishostingthis.com/tools/user-agent/');

%%%% meta info to get %%%%
meta_info_num          = {'DATA_MODE' ...
    'date' 'date_qc' 'position_qc' 'cycle_number' 'lat' 'lon' ...
    'platform_number' 'pres_max_for_TEMP' 'pres_min_for_TEMP' ...
    'pres_max_for_PSAL' 'pres_min_for_PSAL' 'BASIN' ...
    'DIRECTION' 'isDeep' 'containsBGC' 'date_added'};

meta_info_char         = {'POSITIONING_SYSTEM' 'PLATFORM_TYPE' 'PI_NAME' ...
    'x_id' 'dac' 'VERTICAL_SAMPLING_SCHEME' };

%%%% variable info to get %%%%
var_info                = {'measurements' 'station_parameters' 'nc_url' 'bgcMeas'};
vars_toget              = {'temp' 'pres' 'psal'};
deepvars_toget          = {'temp' 'pres' 'psal' 'pres_qc' 'temp_qc' 'psal_qc'};
bgcvars_toget           = {'temp' 'pres' 'psal' 'pres_qc' 'temp_qc' 'psal_qc'};

%%%% Set NaN/fillvalue %%%%
NaN_Argovis = -999;


%%%% API call in Matlab to Argovis
data = webread(url,options);

%%%% check if there is anything in 'data' first
if ~isempty(data)
    c_len = length(data);
    %%%% Allocate T, S and P related variables %%%%
    T        = cell(1,c_len);
    P        = T;
    S        = T;
    T_QC     = T;
    P_QC     = T;
    S_QC     = T;
    %%%% go through each cycle and grab the data
    for jk = 1:c_len
        % grab numerical/same size meta info
        for j = 1:length(meta_info_num)
            meta_bufr = ['d_' meta_info_num{j}];
            if iscell(data)
                % see if field exists
                if  isfield(data{jk},meta_info_num{j}) == 1
                    eval([meta_bufr '(jk,:) = [data{jk}.' meta_info_num{j} '];'])
                else
                    % if field doesn't exists, create field
                    if jk ==1
                        eval([meta_bufr '(jk,:) = ' num2str(NaN_Argovis) ';'])
                    else
                        if islogical(eval([meta_bufr '(jk-1,:)';]))
                            eval([meta_bufr '(jk,:) = 0;'])
                        elseif islogical(eval([meta_bufr '(jk-1,:)';])) == 0
                            eval([meta_bufr '(jk,:) = ' num2str(NaN_Argovis) ';'])
                        end
                    end
                    
                end
            elseif isstruct(data)
                % see if field exists
                if  isfield(data(jk),meta_info_num{j}) == 1
                    eval([meta_bufr '(jk,:) = [data(jk).' meta_info_num{j} '];'])%
                else
                    % if field doesn't exists, create field
                    if jk ==1
                        eval([meta_bufr '(jk,:) = ' num2str(NaN_Argovis) ';'])
                    else
                        if islogical(eval([meta_bufr '(jk-1,:)';]))
                            eval([meta_bufr '(jk,:) = 0;'])
                        elseif islogical(eval([meta_bufr '(jk-1,:)';])) == 0
                            eval([meta_bufr '(jk,:) = ' num2str(NaN_Argovis) ';'])
                        end
                    end
                end
            end
        end
        % grab char/different sized meta info
        for j = 1:length(meta_info_char)
            meta_bufr = ['d_' meta_info_char{j}];
            if iscell(data)
                if  isfield(data{jk},meta_info_char{j}) == 1
                    %eval([meta_bufr '= {data{jk}.' meta_info_char{j} '};'])
                    eval([meta_bufr '{jk,:} = [data{jk}.' meta_info_char{j} '];'])
                    
                end
            elseif isstruct(data)
                if  isfield(data(jk),meta_info_char{j}) == 1
                    %eval([meta_bufr '= {data(jk).' meta_info_char{j} '};'])
                    eval([meta_bufr '{jk,:}= [data(jk).' meta_info_char{j} '];'])
                end
            end
        end
        
        
        % extract temperature, pressure, salinity parameters and their metadata
        % Note:  some data are returned as cell arrays instead of structures
        %
        for jj = 1:length(var_info)
            var_bufr = ['d_' var_info{jj}];
            if iscell(data)
                if isfield(data{jk},var_info{jj})
                    % make sure it isn't empty
                    if isempty(eval(['data{jk}.' var_info{jj} ';'])) == 0
                        eval([var_bufr '(jk,:) = extractfield(data{jk},''' var_info{jj} ''');'])
                        %   eval([var_bufr '(jk,:) = [data{jk}.' var_info{jj} '];'])
                    else
                        eval([var_bufr '{jk} = ' num2str(NaN_Argovis) ';'])
                    end
                end
            elseif isstruct(data)
                if isfield(data(jk),var_info{jj})
                    eval([var_bufr '(jk,:) = extractfield(data(jk),''' var_info{jj} ''');'])
                end
            end
        end
        
        
        % determine if a core, BGC or Deep float
        if exist('d_isDeep') == 1 
            prog_bufr = deepvars_toget;
            meas_bufr = d_measurements;
        elseif d_containsBGC(jk) == 1
            prog_bufr = bgcvars_toget;
            meas_bufr = d_bgcMeas;
        else
            prog_bufr = vars_toget;
            meas_bufr = d_measurements;
        end
        
        % sort the profiles by cycle number
        tt1 = cell2mat(meas_bufr(jk));
        [numparam sz] = size(d_station_parameters{jk});
        for jp = 1:numparam
            vars_bufr = [prog_bufr{jp}];
            switch vars_bufr
                case 'temp'
                    eval(['T{jk} = extractfield(tt1,''' prog_bufr{jp} ''');'])
                case 'pres'
                    eval(['P{jk} = extractfield(tt1,''' prog_bufr{jp} ''');'])
                case 'psal'
                    eval(['S_bfr = extractfield(tt1,''' prog_bufr{jp} ''');']);
                    S_bfr(S_bfr==NaN_Argovis) = nan;
                    S{jk} = S_bfr;
                case 'temp_qc'
                    eval(['T_QC{jk} = extractfield(tt1,''' prog_bufr{jp} ''');'])
                case 'pres_qc'
                    eval(['P_QC{jk} = extractfield(tt1,''' prog_bufr{jp} ''');'])
                case 'psal_qc'
                    eval(['S_QC_bfr = extractfield(tt1,''' prog_bufr{jp} ''');']);
                    S_QC_bfr(S_QC_bfr==NaN_Argovis) = nan;
                    S_QC{jk} = S_QC_bfr;
            end
            
        end
    end
end


% sort cycle number, but keep index
[cnum,cind] = sort(d_cycle_number);


% plot T/S/P
figure(1)
clf(1)
title('Salinity vs depth profiles')
set(gca,'Ydir','reverse')
hold on
for pp = 1:c_len
    
    plot(S{pp},P{pp})
end
ylabel('dbars');
xlabel('psu');
hold off

% plot T/S/P
figure(2)
clf(2)
title('Temperature vs depth profiles')
set(gca,'Ydir','reverse')
hold on
for pp = 1:c_len
    
    plot(T{pp},P{pp})
end
ylabel('dbars');
xlabel('degrees C');
hold off

% plot T/S/P
figure(3)
clf(3)
title('Temperature vs Salinity')
set(gca,'Ydir','Normal')
hold on
for pp = 1:c_len
    
    plot(S{pp},T{pp})
end
ylabel('degrees C');
xlabel('psu');
hold off



% plot locations
figure(4)
clf(4)
% get lat/lon
lat = d_lat(cind);
lon = d_lon(cind);
minlat = ceil(min(lat))-2;
maxlat = ceil(max(lat))+2;
minlon = ceil(min(lon))-3;
maxlon = ceil(max(lon))+3;

worldmap([minlat maxlat],[minlon maxlon])
load geoid
load coastlines
geoshow(coastlat,coastlon)
hold on
scatterm(lat(1),lon(1),100,'r','filled')
scatterm(lat(2:end),lon(2:end),50,'b','filled')
hold off


