%%%% API to grab profile data from Argovis

clear all

%%%% set platform and cycle number
plat_bufr = '5900400';%'4900141';
cyc_bufr  = '30';

url = ['https://argovis.colorado.edu/catalog/profiles/' plat_bufr '_' cyc_bufr '/']
%%%% set options for webread
options = weboptions('Timeout',20,'UserAgent', 'http://www.whoishostingthis.com/tools/user-agent/');

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


%%%% meta info to get %%%%
meta_info                = {'POSITIONING_SYSTEM' 'PLATFORM_TYPE' 'DATA_MODE' 'PI_NAME' ...
    'max_pres' 'date' 'position_qc' 'cycle_number' 'lat' 'lon' ...
    'dac' 'platform_number' 'x_id' 'VERTICAL_SAMPLING_SCHEME' 'BASIN' ...
    'pres_max_for_TEMP' 'pres_min_for_TEMP' 'pres_max_for_PSAL' 'pres_min_for_PSAL'};

%%%% variable info to get %%%%
var_info                = {'measurements' 'station_parameters' 'nc_url'};
vars_toget              = {'temp' 'pres' 'psal'};



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

%%%% check if there is anything in 'data' first
if ~isempty(data)
    % grab meta info
    for j = 1:length(meta_info)
        meta_bufr = ['d_' meta_info{j}];
        eval([meta_bufr '= {data(:).' meta_info{j} '};'])
    end
    
    sz = getfield(data,'measurements');
    [t_len tz] = size(sz);
    
    %%%% Allocate T, S and P related variables %%%%
    T        = nan(1,t_len);
    P        = T;
    S        = T;
    
    % 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 isfield(data,var_info{jj}) == 0
            eval([var_bufr ' = [data.' var_info{jj} '];'])
        elseif isfield(data,var_info{jj}) == 1
            eval([var_bufr ' = extractfield(data,''' var_info{jj} ''');'])
        end
    end
    
    
    % sort the profiles by cycle number
    tt1 = cell2mat(d_measurements);
    a1 = d_station_parameters{1};
    [numparam cv] = size(a1);
    
    for jp = 1:numparam
        vars_bufr = [vars_toget{jp}];
        switch vars_bufr
            case 'temp'
                eval(['T = extractfield(tt1,''' vars_toget{jp} ''');'])
            case 'pres'
                eval(['P = extractfield(tt1,''' vars_toget{jp} ''');'])
            case 'psal'
                eval(['S_bfr = extractfield(tt1,''' vars_toget{jp} ''');']);
                S_bfr(S_bfr==NaN_Argovis) = nan;
                S = S_bfr;
        end
        
    end
end




% plot T/S/P
figure(1)
clf(1)
title('Salinity vs depth profile')
set(gca,'Ydir','reverse')
hold on
plot(S,P)
ylabel('dbars');
xlabel('psu');
hold off

% plot T/S/P
figure(2)
clf(2)
title('Temperature vs depth profile')
set(gca,'Ydir','reverse')
hold on
plot(T,P)
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
plot(S,T)
ylabel('degrees C');
xlabel('psu');
hold off

