% adv_ts.m  An mfile to plot the (optionally filtered)
%           timeseries of current velocity data from South
%           Carolina ADV data.

%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use of this program is described in:
%
% Armstrong, Brandy N., Warner, John C., List, Jeff H., Martini, 
% Marinna A., Montgomery, Ellyn T., Traykovski, Peter, Voulgaris, George 
% 2014, Coastal Change Processes Project data report for oceanographic 
% observations near Fire Island, New York, February through May  
% 2014 : U.S. Geological Survey Open-File Report 2014-xxxx, available 
% online at http://pubs.usgs.gov/of/2014/xxxx/.
%
% Program written in Matlab v8.0.0.755
% Program ran on PC with Windows 7 64bit
%
% "Although this program has been used by the USGS, no warranty,
% expressed or implied, is made by the USGS or the United States
% Government as to the accuracy and functioning of the program
% and related program material nor shall the fact of distribution
% constitute any such warranty, and no responsibility is assumed
% by the USGS in connection therewith."
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% B.Armstrong 06/20/14, Raw ADV data is processed and saved to netCDF files.
%                       It is assumed that the netCDF files are stored in a
%                       directory defined by the variable 'dataDirectory'.
%                       To plot low-pass filtered current velocities set the
%                       switch 'filt' to 'yes', otherwise (filt='no')
%                       unfiltered current velocities are plotted.
%
% Dependencies:
%       smart_interp.m
%       PL66TN.m
%       julian.m
%       gregorian.m
%       suptitle.m
%       tight_subplot.m
%       gmean.m
%       


clear
more off

% define data and plot output directories
dataDirectory = '\\IGSAGIEGGS-FILE\Stg-proc\data\FireIsland_2014\candidate_final_files';
plotDirectory = 'I:\FireIsland\FI_14_WEBOFR\PLOTS';

% define ADV data filenames
dataFiles={'9916advs-cal-trmclean.nc','9917advs-cal-trm.nc','9885advs-cal-trm.nc'}%,Site 2 fell over Feb 13
datanames={'Site 3','Site 3','Site 2'}%, Site 2 fell over Feb 13th
%%
% waveFiles={'9861whp-cal.nc','9892awWvs-p.nc',...
%     '9921whp-cal.nc','9981whp-cal.nc','10001whp-cal.nc','10021whp-cal.nc','10041whp-cal.nc'};
% wavenameFiles={'Site 1','Site 2','Site 3','Site 6','Site 7','Site 8','Site 9'};
%%
nFiles=length(dataFiles);

% define parameters for plots
filt='no';                                         %filtering switch, 'yes' or 'no'
col=get(0,'defaultaxescolororder');                 %plot color order
% ylab={ {'Significant Wave','Height (m)'},{'Sensor Range','to Boundary','(m)'},...
%     {'Eastward','Velocity','(cm/s)'},...
%     {'Northward','Velocity','(cm/s)'},...
%     {'Eastward','Velocity STD','(cm/s)'},...
%     {'Northward','Velocity STD','(cm/s)'},...          %plot ylabels for stick plots
%     };
ylab={ {'Sensor Range','to Boundary (m)'},...
    {'Eastward','Velocity (cm/s)'},...
    {'Northward','Velocity (cm/s)'},...
    {'Eastward','Velocity STD (cm/s)'},...
    {'Northward','Velocity STD (cm/s)'},...          %plot ylabels for stick plots
    };

startTime=julian(2014,2,5,00);
stopTime=julian(2014,05,10,00);
timediff=stopTime-startTime;                                %plot xlimits extend 5 percent
xlims=[(startTime-timediff*0.05) (stopTime+timediff*0.05)]; %beyond start time and stop time
xt=[];
for yy=2014:2014
    for mm=1:12
        tic=julian(yy,mm,01,00);
        if tic>=xlims(1) & tic<=xlims(2)
            xt=[xt; tic];
        end
    end
end
ylims=[0 5;0 1;-30 30;-30 30;0 30; 0 30;];      %u,v plot ylimits

% 'jd_int' is the time array onto which all
% data is interpolated. data gaps larger than
% 'maxGap' hours are not interpolated over
delta_t = 1/24;
jd_int = [startTime:delta_t:stopTime]';
maxGap = 3;

% initialize variables
jd=cell(nFiles,1);
depth=cell(nFiles,1);
u=cell(nFiles,1);
v=cell(nFiles,1);
ustd=cell(nFiles,1);
vstd=cell(nFiles,1);
brange=cell(nFiles,1);
varList={'u','v','ustd','vstd','brange','pressure'};
nVars=length(varList);
%% Load site wave data
% for f=1:length(waveFiles)
%     ncwaves=(fullfile(dataDirectory,waveFiles{f}));
%     time=double(ncread(ncwaves,'time'));
%     time2=double(ncread(ncwaves,'time2'));
%     jd_waves = time + (time2/3600/1000/24);
%     waveDelta_t=gmean(diff(jd_waves));
%     hsig=squeeze(ncread(ncwaves,'wh_4061'));
%     try
%         theFillValue=ncreadatt(ncwaves,'wh_4061','_FillValue');
%     catch
%         theFillValue=1.0E35
%     end
%     hsig(hsig >= theFillValue)=nan;
%     hsig(hsig <= 0)=nan;
%     hsig_int(:,f) = smart_interp([jd_waves], [hsig],...
%         jd_int,3);
% end
%%
for f=1:length(dataFiles)
       if ~isempty(dataFiles{f})
        nc=(fullfile(dataDirectory,dataFiles{f}));
        jd{f}=double(ncread(nc,'time')) + (double(ncread(nc,'time2'))/3600/1000/24);
        u{f}=squeeze(ncread(nc,'u_1205'));                          %eastward velocity, cm/s
        ustd{f}=squeeze(ncread(nc,'USTD_4097'));                    %eastward velocity standard deviation, cm/s
        v{f}=squeeze(ncread(nc,'v_1206'));                          %northward velocity, cm/s
        vstd{f}=squeeze(ncread(nc,'VSTD_4098'));                    %northward velocity standard deviation, cm/s
        brange{f}=squeeze(ncread(nc,'brange'));                     %sensor range to boundary, m
        try
        pressure{f}=squeeze((ncread(nc,'P_4023')-1000)/100);        %pressure, mbar
        catch
        pressure{f}=nan; 
        end
        depth{f}=squeeze(ncread(nc,'depth'));                       %bin depths below surface, mbs
        try
            theFillValue=ncreadatt(nc,'u_1205','_FillValue');
        catch
            theFillValue=1.0E35
        end
        delta_t = gmean(diff(jd{f}));                  %time step, julian days
        site=dataFiles{f}(1:4);                         %site #
    end

    badInd = find( u{f}+v{f} >= theFillValue );
    u{f}(badInd) = nan;
    v{f}(badInd) = nan;

    badInd = find( ustd{f}+vstd{f} >= theFillValue );
    ustd{f}(badInd) = nan;
    vstd{f}(badInd) = nan;
    
    badInd = find(brange{f} >= theFillValue );
    brange{f}(badInd) = nan;

    jd_all=[jd{f}];
    for var=1:nVars
        eval([varList{var},'_all=[',varList{var},'{f}];'])
    end

    % interpolate data onto 'jd_int'
    for var=1:nVars
        eval([varList{var},'_all_int=smart_interp(jd_all, ',...
            varList{var},'_all, jd_int, maxGap);'])
    end


    % (optionally filter the velocities)
    switch filt
        case 'yes'
            disp('Low-pass filtering u,v current velocities');
            for var=1:nVars
                eval([varList{var},'_all_int=PL66TN(',...
                    varList{var},'_all_int, delta_t*24, 33);'])
            end
        otherwise
            disp('Not filtering current velocities');
    end

    % combine data from all sites in an array for plotting

    for var=1:nVars
        eval([varList{var},'_all_comb(:,f)=',...
            varList{var},'_all_int;'])
    end
end
    %%%%%%%%%%%%%%%%%%%%%% U,V TIME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
%     ydata=[vstd_all_comb(:,f),...
%         ustd_all_comb(:,f),...
%         v_all_comb(:,f),...
%         u_all_comb(:,f),...
%         brange_all_comb(:,f),...
%         hsig_int(:,1)];
    figure;set(gcf,'position',[100 25 850 1100]);
%     ha = tight_subplot(6,1,[.04 .3],[.1 .1],[.1 .1]) ;
     ha = tight_subplot(5,1,[.04 .3],[.1 .1],[.1 .1]) ;
   
%     axes(ha(1));
% plot(jd_int,hsig_int,'LineWidth',1.2);ylim(ylims(1,:));
% legend(wavenameFiles,'FontSize',7,'Location','NorthWest','Orientation','Horizontal');

axes(ha(1));
plot(jd_int,brange_all_comb,'LineWidth',1.2);ylim(ylims(2,:));
legend(datanames,'FontSize',7,'Location','NorthWest','Orientation','Horizontal');

axes(ha(2));
plot(jd_int,u_all_comb,'LineWidth',1.2);ylim(ylims(3,:));
legend(datanames,'FontSize',7,'Location','SouthWest','Orientation','Horizontal');

axes(ha(3));
plot(jd_int,v_all_comb,'LineWidth',1.2);ylim(ylims(4,:));
legend(datanames,'FontSize',7,'Location','SouthWest','Orientation','Horizontal');

axes(ha(4));
plot(jd_int,ustd_all_comb,'LineWidth',1.2);ylim(ylims(5,:));
legend(datanames,'FontSize',7,'Location','NorthWest','Orientation','Horizontal');

axes(ha(5));
plot(jd_int,vstd_all_comb,'LineWidth',1.2);ylim(ylims(6,:));
legend(datanames,'FontSize',7,'Location','NorthWest','Orientation','Horizontal');


   
    % reformat xlims, ylabels, lines
    for h=1:length(ha)
        axes(ha(h))
        set(gca,'xlim',xlims,'xtick',xt)
        ylabhan=get(gca,'Ylabel');
        set(ylabhan,'String',ylab{h})
        pos=get(ylabhan,'position');
        set(get(gca,'Ylabel'),'position',[julian([2014,1,28,0,0,0]) pos(2) pos(3)])
        if h~=length(ha)
            linehan=findobj(gca,'Type','line','color','b');
            set(linehan,'color',col(1,:));
            linehan=findobj(gca,'Type','line','color',[0 .5 0]);
            set(linehan,'color',col(2,:));
        end
    end

    % re-do xlabels
    for h=1:length(ha)
    axes(ha(h))
    set(gca,'XTickLabel',{''})
    end
    axes(ha(5))
    for tic=1:length(xt)
         xtg=gregorian(xt(tic));
        xtd=datenum(xtg);
        xtl={[datestr(xtd,3),' 1 ',datestr(xtd,10)]};
        xtlpos=ylims(1,1)-1.5;
        text(xt(tic),xtlpos,xtl,'horizontalalignment','center',...
            'verticalalignment','top')
    end

    % give it a title and export to .pdf
    switch filt
        case 'yes'
            set(gcf,'PaperPositionMode','Auto')
            suptitle([{'Low-Passed ADV Bottom Water Flow Observations',...
                ['Sites 3 ']}]);
            print(fullfile(plotDirectory,['ofr2014-xxxx-FI14_adv_sites_lp']),'-dpdf');
        otherwise
            set(gcf,'PaperPositionMode','Auto')
            suptitle([{'ADV Bottom Water Flow Observations',...
                ['Sites 3 ']}]);
            print(fullfile(plotDirectory,['ofr2014-xxxx-FI14_adv_sites']),'-dpdf');
    end




