% KL_Plots 
%
% Coast line indicators and nourishment plots along the Dutch coast
%
% NB. time in BKL (TKL, TND) ends in 2016 (defined and predicted coast lines)
%     time in MKL (DF) ends in 2016 (measured coast line)
%
%	---------------------------------------
% 
%       Giorgio Santinelli
%
%       Giorgio.Santinelli@deltares.nl
%
%       Deltares
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%	---------------------------------------
%
% $Id: KL_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/KL_Plots.m $


clear all
close all

%% read .nc files
% KLpath         = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/BKL_TKL_MKL/';
KLpath         = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/BKL_TKL_MKL/';
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/'; 

MKLurl         = 'MKL.nc';
BKL_TKL_TNDurl = 'BKL_TKL_TND.nc';
% NOURurl        = 'suppleties.nc';
NOURurl        = 'nourishments.nc';

id       = nc_varget([KLpath MKLurl], 'id');

% read area
areacode = nc_varget([KLpath MKLurl], 'areacode');
areaname = nc_varget([KLpath MKLurl], 'areaname');

% read time
MKLyear  = nc_cf_time([KLpath MKLurl]); % year
MKLtime  = nc_varget([KLpath MKLurl], 'time_MKL') + datenum('1970','yyyy') ; % actual date
BKLtime  = nc_cf_time([KLpath BKL_TKL_TNDurl]); % fairly 1 more than MKL !

MKL      = nc_varget([KLpath MKLurl], 'momentary_coastline');
TKL      = nc_varget([KLpath BKL_TKL_TNDurl], 'testing_coastline');
BKL      = nc_varget([KLpath BKL_TKL_TNDurl], 'basal_coastline');

% time re-definition to yyyy.mm...
for ii = 1:numel(MKLtime) 
    if ~isnan(MKLtime(ii))
        MKLtime(ii) = str2num(datestr(MKLtime(ii),'yyyy')) + (MKLtime(ii) - datenum(str2num(datestr(MKLtime(ii),'yyyy')),1,1))/365;
    else
        MKLtime(ii) = NaN;
    end
end
BKLtime  = str2num(datestr(BKLtime,'yyyy'));

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

% NOUR_beach = nc_varget([NOURpath NOURurl], 'vol_beach');
% NOUR_shore = nc_varget([NOURpath NOURurl], 'vol_shoreface');
% NOUR_dune  = nc_varget([NOURpath NOURurl], 'vol_dune');
% NOUR_other = nc_varget([NOURpath NOURurl], 'vol_other');

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_beach') + datenum('1970','yyyy'); % actual date;
% TIME_end_beach_n       = nc_varget([NOURpath NOURurl], 'time_end_beach') + datenum('1970','yyyy');
% TIME_start_shore_n     = nc_varget([NOURpath NOURurl], 'time_start_shoreface') + datenum('1970','yyyy');
% TIME_end_shore_n       = nc_varget([NOURpath NOURurl], 'time_end_shoreface') + datenum('1970','yyyy');
% TIME_start_dune_n      = nc_varget([NOURpath NOURurl], 'time_start_dune') + datenum('1970','yyyy');
% TIME_end_dune_n        = nc_varget([NOURpath NOURurl], 'time_end_dune') + datenum('1970','yyyy');
% TIME_start_other_n     = nc_varget([NOURpath NOURurl], 'time_start_other') + datenum('1970','yyyy');
% TIME_end_other_n       = nc_varget([NOURpath NOURurl], 'time_end_other') + datenum('1970','yyyy');

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...
KLfolder = 'KL_Plots_withtrends';
mkdir(KLfolder);

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

% definition in yyyy to avoid issues for datetick command
dateini = 1960;       
datefin = 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) % 1090 as a test

    disp([num2str(i) '/' num2str(length(id))])
    figure('Visible','Off')

    %% 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);
            set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            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);
            set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            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);
            set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            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);
            set(gca,'XLimMode','manual','Xlim',[dateini datefin]);
            set(gca,'XTick', [],'XTickLabel', []);
            hold on            
        end    
    end

    ylabel('Nourishment volume [m  ^3/m]','FontSize',12) %6 thumb
    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));
    
    %% MKL, TKL, BKL

    HandleKL = axes('Position',get(HandleNou,'Position'));
        
    % compute linear trend 1965 - 1990
    mkl1 = MKL(MKLtime(:,i)<1990 & MKLtime(:,i)>=1965,i); mkl1time = MKLtime(MKLtime(:,i)<1990 & MKLtime(:,i)>=1965,i);
    if sum(~isnan(mkl1))>6 % ...arbirtary number of points to allow for regression
        Mb1 = polyfit(mkl1time(~isnan(mkl1)),mkl1(~isnan(mkl1)),1); mkl1_trend = polyval(Mb1, mkl1time(~isnan(mkl1)));
        MTR1 = plot(mkl1time(~isnan(mkl1)),mkl1_trend,'b-'); hold on; % params are b1
    end
    mkl2 = MKL(MKLtime(:,i)>=1990,i); mkl2time = MKLtime(MKLtime(:,i)>=1990,i);
    if sum(~isnan(mkl2))>6 % ...arbirtary number of points to allow for regression
        Mb2 = polyfit(mkl2time(~isnan(mkl2)),mkl2(~isnan(mkl2)),1); mkl2_trend = polyval(Mb2, mkl2time(~isnan(mkl2)));
        MTR2 = plot(mkl2time(~isnan(mkl2)),mkl2_trend,'b-'); hold on; % params are b2
    end

    M = plot(MKLtime(:,i), MKL(:,i),'bx','LineWidth',2,'MarkerSize',8); % plot(MKLyear, MKL,'bo'); %1; 3 thumb
    hold on
    T = plot(BKLtime, TKL(:,i),'o','LineWidth',2,'MarkerSize',8,'Color',[0 .5 0]);%1; 3 thumb
    B = plot(BKLtime, BKL(:,i),'+','LineWidth',2,'MarkerSize',8,'Color',[1/3 0 1/3]);%1; 3 thumb
    
    set(HandleKL,'YAxisLocation','right','Color','none');
    set(HandleKL,'XLimMode','manual','Xlim',[dateini datefin]);

    % 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 %5thumb
    xlabel('Year','FontSize',12); ylabel('Distance wrt RSP [m]','FontSize',12)%12 %12 thumb
    title(['MKL - TKL - BKL : ' char(cellstr(areaname(i,:))) ' (' num2str(areacode(i)) '), transect '...
        num2str(id(i) - areacode(i)*1000000)],'FontSize',12,'FontWeight','bold') %6 thumb
    legendKL = legend([M; T; B], {[' MKL'; ' TKL'; ' BKL']}, 'Location', 'NorthWest');  
%   %% thumb: 
%     set(gcf, 'PaperUnits', 'inches');
% set(gcf, 'PaperSize', [1.4 1]);
% set(gcf, 'PaperPositionMode', 'manual');
% set(gcf, 'PaperPosition', [0 0 3 2]);
% print('-dpng','res.png')
% %%
    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',[KLfolder filesep char(cellstr(areaname(i,:))) '_' num2str(id(i))])
    %print as matfiles
    %savefig([KLfolder filesep KLfolder 'mat' filesep char(cellstr(areaname(i,:))) '_' num2str(id(i))])
    
    close all
    clear('hvol_st','hvol_on','hvol_dn','hvol_ot','M','T','B');

end