% BW_Plots 
%
% Coast line indicators and nourishment plots along the Dutch coast:
% - BEACH WIDTH at Mean Low Water 
% - BEACH WIDTH at Mean High Water 
%
% Beach width in the plots is defined with respect to the intersection of the profile with +3 NAP
% 
%	---------------------------------------
% 
%       Giorgio Santinelli
%
%       Giorgio.Santinelli@deltares.nl
%
%       Deltares
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%	---------------------------------------
%
% $Id: BW_Plots.m 9013 2016-12-21 08:00:07Z santinel $
% $Date: 2016-12-21 09:00:07 +0100 (Wed, 21 Dec 2016) $
% $Author: santinel $
% $Revision: 9013 $
% $HeadURL: https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/coastline_graphs_beheerregister/scripts/BW_Plots.m $
% $Keywords$ 
%

clear
close all

%% read .nc files
BWpath         = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/strandbreedte/';
NOURpath       = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/suppleties/';
% online nc throw the following error: 'NC_UNLIMITED in the wrong index (NC_EUNLIMPOS)'
% nourishments.nc online dataset has to be fixed.
NOURpath       = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/suppleties/'; 

BWurl          = 'BW.nc';
NOURurl        = 'nourishments.nc';

id       = nc_varget([BWpath BWurl], 'id');

% read area
areacode = nc_varget([BWpath BWurl], 'areacode');
areaname = nc_varget([BWpath BWurl], 'areaname');

% read time (1 - Jan - XXXX represents year XXXX on the plots)
time_JARKUS = nc_cf_time([BWpath BWurl]); % year

BW_MHW   = nc_varget([BWpath BWurl], 'beach_width_at_mean_high_water');
BW_MLW   = nc_varget([BWpath BWurl], 'beach_width_at_mean_low_water');

% time re-definition to yyyy.mm...
time_JARKUS = str2num(datestr(time_JARKUS,'yyyy')); % + (str2num(datestr(time_JARKUS,'mm'))-1)/12;

BW_MHW_JARKUS  = BW_MHW';
BW_MLW_JARKUS  = BW_MLW';

% distinguish between new and old database
commonID = false(size(BW_MHW_JARKUS,1),1);
for ii = 1:size(BW_MHW_JARKUS,1)
    if any(~isnan(BW_MHW_JARKUS(ii,time_JARKUS<1965))) ||...
        any(~isnan(BW_MLW_JARKUS(ii,time_JARKUS<1965)));
        commonID(ii) = true;
    end
end

%% read .nc file of nourishments (m3/m)
NOUR_ntime = str2num(datestr(nc_cf_time([NOURpath NOURurl], 'time'),'yyyy')); % year of beg_date

NOUR_beach = nc_varget([NOURpath NOURurl], 'volume',[0 0 0],[-1 -1 1]); % beach
NOUR_shore = nc_varget([NOURpath NOURurl], 'volume',[0 0 1],[-1 -1 1]); % shoreface
NOUR_dune  = nc_varget([NOURpath NOURurl], 'volume',[0 0 2],[-1 -1 1]); % dune
NOUR_other = nc_varget([NOURpath NOURurl], 'volume',[0 0 3],[-1 -1 1]); % other

TIME_start_beach_n     = nc_varget([NOURpath NOURurl], 'time_start', [0 0 0],[-1 -1 1]) + datenum('1970','yyyy'); % actual date;
TIME_end_beach_n       = nc_varget([NOURpath NOURurl], 'time_end', [0 0 0],[-1 -1 1]) + datenum('1970','yyyy');
TIME_start_shore_n     = nc_varget([NOURpath NOURurl], 'time_start', [0 0 1],[-1 -1 1]) + datenum('1970','yyyy');
TIME_end_shore_n       = nc_varget([NOURpath NOURurl], 'time_end', [0 0 1],[-1 -1 1]) + datenum('1970','yyyy');
TIME_start_dune_n      = nc_varget([NOURpath NOURurl], 'time_start', [0 0 2],[-1 -1 1]) + datenum('1970','yyyy');
TIME_end_dune_n        = nc_varget([NOURpath NOURurl], 'time_end', [0 0 2],[-1 -1 1]) + datenum('1970','yyyy');
TIME_start_other_n     = nc_varget([NOURpath NOURurl], 'time_start', [0 0 3],[-1 -1 1]) + datenum('1970','yyyy');
TIME_end_other_n       = nc_varget([NOURpath NOURurl], 'time_end', [0 0 3],[-1 -1 1]) + datenum('1970','yyyy');

%% Figures...
BWfolder = 'BW_Plots_withtrends';
mkdir(BWfolder);

% nourishment 'fixed' duration set to
nourduration = 0.5; % halfayear

% definition in yyyy to avoid issues for datetick command
dateini     = 1960;       datefin = 2020;
dateini_old = 1840;   datefin_old = 2020;

TIME_start_beach = NaN(size(TIME_start_beach_n,1),size(TIME_start_beach_n,2)); 
TIME_end_beach   = NaN(size(TIME_end_beach_n,1),size(TIME_end_beach_n,2));
TIME_start_shore = NaN(size(TIME_start_shore_n,1),size(TIME_start_shore_n,2)); 
TIME_end_shore   = NaN(size(TIME_end_shore_n,1),size(TIME_end_shore_n,2)); 
TIME_start_dune  = NaN(size(TIME_start_dune_n,1),size(TIME_start_dune_n,2));   
TIME_end_dune    = NaN(size(TIME_end_dune_n,1),size(TIME_end_dune_n,2)); 
TIME_start_other = NaN(size(TIME_start_other_n,1),size(TIME_start_other_n,2)); 
TIME_end_other   = NaN(size(TIME_end_other_n,1),size(TIME_end_other_n,2)); 


for i=1:length(id)
    
	disp([num2str(i) '/' num2str(length(id))])
    figure('Visible','Off'); hold on;

    %% Nourishments + add axis

    hvol_st = []; hvol_on = []; hvol_dn = []; hvol_ot = [];
    
    for j = 1:length(NOUR_ntime)
        if ~isnan(NOUR_beach(i,j)) % beach nourishment
            if ~isnan(TIME_start_beach_n(i,j))
                TIME_start_beach(i,j) = str2double(datestr(TIME_start_beach_n(i,j),'yyyy')) + (str2double(datestr(TIME_start_beach_n(i,j),'mm'))-1)/12;
                TIME_end_beach(i,j) = str2double(datestr(TIME_end_beach_n(i,j),'yyyy')) + (str2double(datestr(TIME_end_beach_n(i,j),'mm'))-1)/12;
            end
            hvol_st = fill([TIME_start_beach(i,j), TIME_start_beach(i,j),...
                TIME_start_beach(i,j) + nourduration, TIME_start_beach(i,j) + nourduration],...
                [0, NOUR_beach(i,j), NOUR_beach(i,j), 0],[1 0.69 0.39]); % fill the plot
            set(hvol_st,'EdgeColor',[1 0.69 0.39],'EdgeAlpha',0.2);
            if commonID(i) % both old and new database
                set(gca,'XLimMode','manual','Xlim',[dateini_old datefin_old]);
            else
                set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            end
            set(gca,'XTick', [],'XTickLabel', []);    
            hold on        
        end
        if ~isnan(NOUR_shore(i,j)) % shoreface nourishment
            if ~isnan(TIME_start_shore_n(i,j))
                TIME_start_shore(i,j) = str2double(datestr(TIME_start_shore_n(i,j),'yyyy')) + (str2double(datestr(TIME_start_shore_n(i,j),'mm'))-1)/12;
                TIME_end_shore(i,j) = str2double(datestr(TIME_end_shore_n(i,j),'yyyy')) + (str2double(datestr(TIME_end_shore_n(i,j),'mm'))-1)/12;
            end
            hvol_on = fill([TIME_start_shore(i,j), TIME_start_shore(i,j),...
                TIME_start_shore(i,j) + nourduration, TIME_start_shore(i,j) + nourduration],...
                [0, NOUR_shore(i,j), NOUR_shore(i,j), 0],[0.04 0.52 0.78]);
            set(hvol_on,'EdgeColor',[0.04 0.52 0.78],'EdgeAlpha',0.2);
            if commonID(i) % both old and new database
                set(gca,'XLimMode','manual','Xlim',[dateini_old datefin_old]);
            else
                set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            end
            set(gca,'XTick', [],'XTickLabel', []);        
            hold on          
        end
        if ~isnan(NOUR_dune(i,j))  % dune nourishment
            if ~isnan(TIME_start_dune_n(i,j))
                TIME_start_dune(i,j) = str2double(datestr(TIME_start_dune_n(i,j),'yyyy')) + (str2double(datestr(TIME_start_dune_n(i,j),'mm'))-1)/12;
                TIME_end_dune(i,j) = str2double(datestr(TIME_end_dune_n(i,j),'yyyy')) + (str2double(datestr(TIME_end_dune_n(i,j),'mm'))-1)/12;
            end            
            hvol_dn = fill([TIME_start_dune(i,j), TIME_start_dune(i,j),...
                TIME_start_dune(i,j) + nourduration, TIME_start_dune(i,j) + nourduration],...
                [0, NOUR_dune(i,j), NOUR_dune(i,j), 0],[0.5 0.5 0]);
            set(hvol_dn,'EdgeColor',[0.5 0.5 0],'EdgeAlpha',0.2);
            if commonID(i) % both old and new database
                set(gca,'XLimMode','manual','Xlim',[dateini_old datefin_old]);
            else
                set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            end
            set(gca,'XTick', [],'XTickLabel', []);        
            hold on           
        end
        if ~isnan(NOUR_other(i,j)) % other type of nourishment
            if ~isnan(TIME_start_other_n(i,j))
                TIME_start_other(i,j) = str2double(datestr(TIME_start_other_n(i,j),'yyyy')) + (str2double(datestr(TIME_start_other_n(i,j),'mm'))-1)/12;
                TIME_start_other(i,j) = str2double(datestr(TIME_start_other_n(i,j),'yyyy')) + (str2double(datestr(TIME_start_other_n(i,j),'mm'))-1)/12;
            end            
            hvol_ot = fill([TIME_start_other(i,j), TIME_start_other(i,j),...
                TIME_start_other(i,j) + nourduration, TIME_start_other(i,j) + nourduration],...
                [0, NOUR_other(i,j), NOUR_other(i,j), 0],[1 0 0]);
            set(hvol_ot,'EdgeColor',[1 0 0],'EdgeAlpha',0.2);
            if commonID(i) % both old and new database
                set(gca,'XLimMode','manual','Xlim',[dateini_old datefin_old]);
            else
                set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            end
            set(gca,'XTick', [],'XTickLabel', []); 
            hold on            
        end    
    end
    ylabel('Nourishment volume [m  ^3/m]','FontSize',12)
    set(gca,'XTick', [],'XTickLabel', []);    

    % routine to display legend [dumb...]
    Mhvol     = [' Beach    ';' Shoreface';' Dune     ';' Other    '];
    if isempty(hvol_st); Mhvol(find(ismember(Mhvol,' Beach    ', 'rows')),:) = []; end
    if isempty(hvol_on); Mhvol(find(ismember(Mhvol,' Shoreface', 'rows')),:) = []; end
    if isempty(hvol_dn); Mhvol(find(ismember(Mhvol,' Dune     ', 'rows')),:) = []; end
    if isempty(hvol_ot); Mhvol(find(ismember(Mhvol,' Other    ', 'rows')),:) = []; end

    % do not display ticks and labels if no nourishment occurred
    if isempty(hvol_st) && isempty(hvol_on) && isempty(hvol_dn) && isempty(hvol_ot)
        set(gca,'YTick', [],'YTickLabel', []);
    end

    hvol      = ([hvol_st; hvol_on; hvol_dn; hvol_ot]); 
    legend(hvol, char(Mhvol), 'Location', 'SouthWest');
    HandleNou = gca;

    % set # of ticks to 10
    ylimits = get(gca,'YLim');
    yinc    = (ylimits(2)-ylimits(1))/10;
    set(gca,'YTick', ylimits(1):yinc:ylimits(2));
    
    %% BW_MLW, BW_MHW

    HandleBW = axes('Position',get(HandleNou,'Position'));

    % compute linear trend 1965 - 1990
    bwl1 = BW_MLW_JARKUS(i,time_JARKUS<1990 & time_JARKUS>=1965); bwl1time = time_JARKUS(time_JARKUS<1990 & time_JARKUS>=1965)';
    bwh1 = BW_MHW_JARKUS(i,time_JARKUS<1990 & time_JARKUS>=1965); bwh1time = time_JARKUS(time_JARKUS<1990 & time_JARKUS>=1965)';
    if sum(~isnan(bwl1))>6 % ...arbirtary number of points to allow for regression
        Lb1 = polyfit(bwl1time(~isnan(bwl1)),bwl1(~isnan(bwl1)),1); bwl1_trend = polyval(Lb1, bwl1time(~isnan(bwl1)));
        LTR1 = plot(bwl1time(~isnan(bwl1)),bwl1_trend,'-b'); hold on; % params are b1
    end
    if sum(~isnan(bwh1))>6 % ...arbirtary number of points to allow for regression
        Hb1 = polyfit(bwh1time(~isnan(bwh1)),bwh1(~isnan(bwh1)),1); bwh1_trend = polyval(Hb1, bwh1time(~isnan(bwh1)));
        HTR1 = plot(bwh1time(~isnan(bwh1)),bwh1_trend,'-r'); hold on; % params are b1
    end
    bwl2 = BW_MLW_JARKUS(i,time_JARKUS>=1990); bwl2time = time_JARKUS(time_JARKUS>=1990)';
    bwh2 = BW_MHW_JARKUS(i,time_JARKUS>=1990); bwh2time = time_JARKUS(time_JARKUS>=1990)';
    if sum(~isnan(bwl2))>6 % ...arbirtary number of points to allow for regression
        Lb2 = polyfit(bwl2time(~isnan(bwl2)),bwl2(~isnan(bwl2)),1); bwl2_trend = polyval(Lb2, bwl2time(~isnan(bwl2)));
        LTR2 = plot(bwl2time(~isnan(bwl2)),bwl2_trend,'-b'); hold on; % params are b2
    end
    if sum(~isnan(bwh2))>6 % ...arbirtary number of points to allow for regression
        Hb2 = polyfit(bwh2time(~isnan(bwh2)),bwh2(~isnan(bwh2)),1); bwh2_trend = polyval(Hb2, bwh2time(~isnan(bwh2)));
        HTR2 = plot(bwh2time(~isnan(bwh2)),bwh2_trend,'-r'); hold on; % params are b2
    end
    
    % plot parameters
    L = plot(time_JARKUS, BW_MLW_JARKUS(i,:),'bo','LineWidth',2,'MarkerFaceColor','b','MarkerSize',4);    
    hold on
    H = plot(time_JARKUS, BW_MHW_JARKUS(i,:),'ro','LineWidth',2,'MarkerFaceColor','r','MarkerSize',4);
 
    set(HandleBW,'YAxisLocation','right','Color','none');
    if commonID(i)
        set(gca,'XLimMode','manual','Xlim',[dateini_old datefin_old]);
    else
        set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
    end

    % set # of ticks to 10
    ylimits = get(gca,'YLim');
    yinc    = (ylimits(2)-ylimits(1))/10;
    set(gca,'YTick', ylimits(1):yinc:ylimits(2));

    % figure opt
    set(gcf,'Position',[5 35 1040 760]); 
    set(gca,'FontSize',12); grid on
    xlabel('Year','FontSize',12); ylabel('Distance between dune boundary and sea boundary [m]','FontSize',12)
    title(['Beach width : ' char(cellstr(areaname(i,:))) ' (' num2str(areacode(i)) '), transect '...
        num2str(id(i) - areacode(i)*1000000)],'FontSize',12,'FontWeight','bold')
	leghandle = legend([L; H],[' BW @ MLW'; ' BW @ MHW'],'Location', 'NorthWest'); % set(leghandle,'Position',[0.155 0.81 0.0971 0.0877]);
    if strcmp(char(cellstr(areaname(i,:))),'Maasvlakte / slufter'); areaname(i,1:20) = 'Maasvlakte          '; end;
    if strcmp(char(cellstr(areaname(i,:))),'Oosterschelde / Neeltje Jans'); areaname(i,1:28) = 'Oosterschelde               '; end;
    print('-dpng','-r300',[BWfolder filesep char(cellstr(areaname(i,:))) '_' num2str(id(i))])

    close all
    clear('hvol_st','hvol_on','hvol_dn','hvol_ot','L','H');


end
