% jarkus_info_KLWLBWfig2kml
%
% Information on Jarkus transects + figures of 
% - Coastline (Kustlijn) plots: KL
% - Waterline and DuneFoot (Waterlijn en DuinVoet) plots: WL
% - BeachWidth (StrandBreedte) plots: BW
%
% [no calls to GE-visualization API]
%
% See also: 
% jarkus_info2kml
%
% giorgio.santinelli@deltares.nl
%
%%%%%%%%%%%%%%%%%%


%% settings

OPT.ncpath              = 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/jarkus/profiles/transect.nc';
% TU mirror!!
% OPT.ncpath              = 'http://opendap.tudelft.nl/thredds/dodsC/data2/deltares/rijkswaterstaat/jarkus/profiles/transect.nc';
% OPT.ncpath              = 'd:\JARKUSdata\transect.nc';

% OPT.fileName            = 'Jarkus_info_fig.kml';
OPT.relativepath        = 'rijkswaterstaat\jarkus';
OPT.basepath_local      = 'F:\_KML\';
OPT.basepath_www        = 'http://kml.deltares.nl/kml';
OPT.templatepath           = 'Template4Jarkus_info_KLWLBWfig2kml.html';

OPT.iconnormalState     = 'http://maps.google.com/mapfiles/kml/shapes/open-diamond.png';
OPT.iconhighlightState  = 'http://maps.google.com/mapfiles/kml/shapes/open-diamond.png';
OPT.scalenormalState    = 0.5;
OPT.scalehighlightState = 0.7;

% figures path
KLpath                  = 'http://kml.deltares.nl/kml/rijkswaterstaat/testGiorgio/tn/KL_Plots/';
WLpath                  = 'http://kml.deltares.nl/kml/rijkswaterstaat/testGiorgio/tn/WL_Plots/';
BWpath                  = 'http://kml.deltares.nl/kml/rijkswaterstaat/testGiorgio/tn/BW_Plots/';


%% geo information
lat           = nc_varget(OPT.ncpath,'lat');
lon           = nc_varget(OPT.ncpath,'lon');
xRSP          = nc_varget(OPT.ncpath,'cross_shore');
min_cross     = nc_varget(OPT.ncpath,'min_cross_shore_measurement');
max_cross     = nc_varget(OPT.ncpath,'max_cross_shore_measurement');

%% displayed information
area          = cellstr(nc_varget(OPT.ncpath,'areaname'));
areacode      = cellstr(num2str(nc_varget(OPT.ncpath,'areacode')));
areaNumcode   = nc_varget(OPT.ncpath,'areacode');
id            = nc_varget(OPT.ncpath,'id');
time          = nc_cf_time(OPT.ncpath,'time');
time_bathy    = nc_cf_time(OPT.ncpath,'time_bathy');
time_topo     = nc_cf_time(OPT.ncpath,'time_topo');
MHW           = nc_varget(OPT.ncpath,'mean_high_water');
MLW           = nc_varget(OPT.ncpath,'mean_low_water');
rsp_lat       = nc_varget(OPT.ncpath,'rsp_lat');
rsp_lon       = nc_varget(OPT.ncpath,'rsp_lon');
angle         = nc_varget(OPT.ncpath,'angle');

date          = datestr(time,'dd-mm-yyyy');

%% make GE-lines of transects
mkdir('lines')

timeIn  = time;
timeOut = time(2:end); timeOut(end+1) = time(end)+365;

% pre-allocation
min_real_cross = NaN(length(time),length(id));
max_real_cross = NaN(length(time),length(id));

[~, m, ~] = unique(area); m = sort(m); 
n         = vertcat(1, (m(1:end-1)+1));

for k = 1:length(m) %k = 6 % NHtest,
    disp(area(m(k)))

for i = 1:length(time)
    disp(date(i,:))
    lat2           = [];
    lon2           = [];

    for jj = 1:length(n(k):m(k)) % min / max cross_shore values matrix
        j = jj+n(k)-1;
        if min_cross(i,j) ~= max_cross(i,j)
            min_real_cross(i,j) = min_cross(i,j);
            max_real_cross(i,j) = max_cross(i,j);
        else
            min_real_cross(i,j) = NaN; max_real_cross(i,j) = NaN;
        end
    end
    for jj = 1:length(n(k):m(k))
        j = jj+n(k)-1;
        if ~isnan(min_real_cross(i,j))
            dum_lat = lat(j,[min_real_cross(i,j) max_real_cross(i,j)]);
            lat2    = vertcat(lat2, dum_lat);
            dum_lon = lon(j,[min_real_cross(i,j) max_real_cross(i,j)]);
            lon2    = vertcat(lon2, dum_lon);
        end
    end
    if ~isempty(lat2)
    KMLline(lat2',lon2',...
       'fileName',['lines\line_', datestr(time(i),'yyyy'), '.kml'],...
        'kmlName',datestr(time(i),'yyyy'),...
         'timeIn',timeIn(i),...
        'timeOut',timeOut(i),...
      'lineColor',[0 0 0],...
      'lineAlpha',.7);

    clear lat2 lon2
    end
end
namet = 'Transects';

sourceline = cell(1,length(time));
for i = 1:length(time)
    sourceline(i) = {['lines\line_', datestr(time(i),'yyyy'), '.kml']}; 
end

KMLmerge_files('fileName',[char(area(m(k),:)), '_line.kml'],...
        'sourceFiles',sourceline,...
        'foldernames',cellstr(datestr(time,'yyyy')),...
            'kmlName',namet,...
  'deleteSourceFiles',true);


%% make GE-points of location of beach poles (RSP)
mkdir('points')

OPT.fid = fopen([char(area(m(k),:)), '_point.kml'],'w');
name1 = 'RSP points';   

% HEADER
OPT_header = struct(...
    'name'       ,name1,...
    'open'       ,0,...
    'description','');

output = KML_header(OPT_header);

% STYLE for pushpin
output = [output ...
    '<StyleMap id="pushpin">\n'...
    ' <Pair><key>normal</key><styleUrl>#pushpin_highlight</styleUrl></Pair>\n'...
    ' <Pair><key>highlight</key><styleUrl>#pushpin_highlight</styleUrl></Pair>\n'... % highligth instead of normal because of some problems w/ KMLmerge_files
    '</StyleMap>\n'...
    '<Style id="pushpin_highlight">\n'...
    ' <IconStyle>\n'...
    ' <scale>' num2str(OPT.scalenormalState) '</scale>\n'...
    ' <Icon><href>'    OPT.iconnormalState '</href></Icon>\n'...
    ' </IconStyle>\n'...
    ' <LabelStyle><color>000000ff</color><scale>0.5</scale></LabelStyle>\n'... % <LabelStyle><color>000000ff</color><scale>0</scale></LabelStyle>\n'... % no text except when mouse hoover
    ' </Style>\n'...
    '<Style id="pushpin_highlight">\n'...
    ' <BalloonStyle><text>\n'...             
     ' <h3>$[name]</h3>'... % variable per dot 
     ' $[description]\n'... % variable per dot 
     ' </text></BalloonStyle>\n'...              
    ' <IconStyle>\n'...
    ' <scale>' num2str(OPT.scalehighlightState) '</scale>\n'...
    ' <color>ff00ff00</color>\n'...
    ' <Icon><href>'    OPT.iconhighlightState '</href></Icon>\n'...
    ' </IconStyle>\n'...
    ' <LabelStyle><scale>0.6</scale></LabelStyle>\n'... 
    ' </Style>\n'];

fprintf(OPT.fid,output); output = [];

% add HTML element for jarkus transects
    
    % html intro
    fid1 = fopen(OPT.templatepath); % open reference .html
    html1 = []; ii = 1;
    while ~feof(fid1)
        htmldummy = fgetl(fid1);
        if ii<37 && ii>2
           html1 = [html1 '\n' htmldummy];
        end
        ii = ii + 1;
    end
    fclose(fid1);

    % Coastline plots info
%     
%     
%     vol = Nour4CoastalStretch(char(area(m(k))));
%     dum = reshape(vol,1,[]);
%     volchar = '';
%     for iii = 1:length(dum)
%         dum2 = dum(iii);
%         volchar = [volchar num2str(dum2) ','];
%     end
    
%     html2 = ['\n'...
%             '$(''#btabs2'').ready(function(){\n'...
%             'drawVisualization('...
%              volchar... '1,2,3,4,5,6,7,8,9,11,NaN,12,'...
%             '"Nourishments along ' char(area(m(k))) ' coast");\n'...
%             '});\n'];
 
    
for jj = 1:length(n(k):m(k))
    j = jj+n(k)-1;
    
    t0    = datestr(timeIn,'yyyy');
    t1    = datestr(timeOut,'yyyy');
    name2 = num2str(id(j)-1e6*areaNumcode(j)); 
    
    html1;
    
    % Indicators info
        
    fid1 = fopen(OPT.templatepath); % open again reference .html
    html2 = []; ii = 1;
    while ~feof(fid1)
        htmldummy = fgetl(fid1);
        if ii>36 && ii<52 && ii ~=38 % superDummy!
           html2 = [html2 '\n' htmldummy];
        end
        if ii == 38
            htmldummy = ['<div id="header"><h1>' char(area(m(k))) ' - Transect ' num2str(id(j)) ' </h1></div>'];
           html2 = [html2 '\n' htmldummy];
        end
        ii = ii + 1;
    end
    fclose(fid1);
    
    % Table
    
   html1_T = ['\n'...
       '<thead>\n'...
       '<tr class="PriTableRow">\n'...
       '<th>General information</th>\n'...
       '<th> </th>\n'...	 
       '</tr>\n'...
       '</thead>'];
   
   html2_T = ['\n'...      
       '<tbody>\n'...
       '<tr>\n'...
       '<td><b> Transect Id</b></td><td>',num2str(id(j)),'</td></tr>\n',... 
       '<td><b> Area name   </b></td><td>',[char(area(m(k))), ' (' char(areacode(m(k))), ') '],'</td></tr>\n'...
       '<td><b> Transect code </b></td><td>',name2,'</td></tr>\n',...
       '<td><b> RSP coordinates </b></td>',...
       '<td>','lat = ',num2str(rsp_lat(j)),' decimal degrees</br>',...
       'lon = ',num2str(rsp_lon(j)),' decimal degrees</td></tr>\n',...
       '<td><b> Angle </b></td><td>',num2str(angle(j)),' degrees (+ clockwise, N)</td></tr>\n',...
       '<td><b> Mean High Water<br></b></td><td>',num2str(MHW(j)),' m (rel. to NAP)</td></tr>\n',...
       '<td><b> Mean Low Water<br></b></td><td>',num2str(MLW(j)),' m (rel. to NAP)</td></tr>\n',...
       '<tr>',...
       ];
   
   html3_T = ['\n'...
       '<td class="nopad" colspan="4" >\n'...
       '<table class="SecTable" border="0" rules="all" cellpadding="0" cellspacing="0" >'];
   
   html4_T = ['\n'...      
       '<thead>\n'...
       '<tr>\n'...
       '<th>Yearly information</th>\n'...
       '<th><b><center>min_cross<br> meas. [m]</center></b></th>\n',...
       '<th><b><center>max_cross<br> meas. [m]</center></b></th>\n',...
       '<th><b><center>time_topo</center></b></th>\n',...
       '<th><b><center>time_bathy</center></b></th>\n',...
       '</tr>\n',...
       '</thead>\n',...
       '<tbody>',...
       ];

  
html5_T = [];
         for i = 1:length(time)
         if ~isnan(min_real_cross(i,j))
             kml_max = num2str(xRSP(max_real_cross(i,j))); 
             kml_min = num2str(xRSP(min_real_cross(i,j)));
         else
             kml_max = '-'; kml_min = '-';
         end
         if ~isnan(time_topo(i,j))
             kml_topo = datestr(time_topo(i,j),'dd-mmm-yyyy');
         else
             kml_topo = '-';
         end
         if ~isnan(time_bathy(i,j))
             kml_bathy = datestr(time_bathy(i,j),'dd-mmm-yyyy');
         else
             kml_bathy = '-';
         end
        
         
         output = ['\n'...
             '<td><b>',datestr(time(i),'yyyy'),'</b></td>\n',...
             '<td><center>',kml_min,'</center></td>\n',...
             '<td><center>',kml_max,'</center></td>\n',...
             '<td><center>',kml_topo,'</center></td>\n',...
             '<td><center>',kml_bathy,'</center></td></tr>',...
             ];
         
         html5_T = [html5_T output];
         
         end
         output = [];
     
         html6_T = ['\n'...
             '</tbody>\n'...
             '</table>\n'...
             '</tbody>\n'...
             '</td>\n'...
             '</tr>\n'...
             '</tbody>\n'...
             '</table>'...
             ];
   
         % html outro
    fid1 = fopen(OPT.templatepath); % open reference .html
    html3a = []; html3b = []; html3c = []; ii = 1;
    while ~feof(fid1)
        htmldummy = fgetl(fid1);
        if ii>129 && ii < 139
           html3a = [html3a '\n' htmldummy];
        elseif ii == 139
           html4 = ['\n'...
               '<div>'...
               '<a href="https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/coastline_graphs/KL_Plots/' char(area(m(k))) '_' num2str(id(j)) '.png">\n'...
               '<img src="' KLpath char(area(m(k))) '_' num2str(id(j)) '.png" style="height: 300px;">'...
               '</a>'...
               '</div>'...
               ];
        end
        if ii>139 && ii < 144
            html3b = [html3b '\n' htmldummy];
        elseif ii == 144
           html5 = ['\n'...
               '<div>'...
               '<a href="https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/coastline_graphs/WL_Plots/' char(area(m(k))) '_' num2str(id(j)) '.png">\n'...
               '<img src="' WLpath char(area(m(k))) '_' num2str(id(j)) '.png" style="height: 300px;">'...
               '</a>'...
               '</div>'...
               ];
        end
        if ii>144 && ii < 149
            html3c = [html3c '\n' htmldummy];
        elseif ii == 149
           html6 = ['\n'...
               '<div>'...
               '<a href="https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/coastline_graphs/BW_Plots/' char(area(m(k))) '_' num2str(id(j)) '.png">\n'...
               '<img src="' BWpath char(area(m(k))) '_' num2str(id(j)) '.png" style="height: 300px;">'...
               '</a>'...
               '</div>'...
               ];
        end
        ii = ii + 1;
    end
    fclose(fid1);
    
    % html outro
    fid1 = fopen(OPT.templatepath); % open reference .html
    html7 = []; ii = 1;
    while ~feof(fid1)
        htmldummy = fgetl(fid1);
        if ii>149
           html7 = [html7 '\n' htmldummy];
        end
        ii = ii + 1;        
    end
    fclose(fid1);         
    
    output = [output ...
             ' \n<Placemark>'...
             ' <name>',name2,'</name>\n'...                      % name
             ' <description><![CDATA['...                        % start required wrapper for html
              html1,html2,...                  % description
              html1_T,html2_T,html3_T,html4_T,html5_T,html6_T... % description
              html3a,html4,html3b,html5,html3c,html6,html7...    % description
              ']]></description>\n'...                           % end   required wrapper for html
             ' <styleUrl>#pushpin</styleUrl>\n'...               % styleName
             ' <Point><coordinates>',num2str(rsp_lon(j)),',',num2str(rsp_lat(j)),',0</coordinates></Point>\n'...
             ' </Placemark>'];
    
    fprintf(OPT.fid,output); output = [];
    
end 

% FOOTER
output = KML_footer;
fprintf(OPT.fid,output);

% close KML
fclose(OPT.fid);

%% KMLmerge_files for Area kml
sourcearea = {[char(area(m(k),:)),'_point.kml'] [char(area(m(k),:)),'_line.kml']};

KMLmerge_files('fileName',['\\kml\kml\kml\rijkswaterstaat\jarkus\jarkus_coastlineGraphs\CoastLine_WaterLine_BeachWidth\', char(area(m(k),:)), '.kml'],...
        'sourceFiles',sourcearea,...
            'kmlName',char(area(m(k),:)),...
        'foldernames',[cellstr(name1) cellstr(namet)],...
  'deleteSourceFiles',true);

end

%% merge all regions together
% sourceregion = cell(1,length(m));
% for k = 1:length(m)
%     sourceregion(k) = {[char(area(m(k),:)), '.kml']}; 
% end
% 
% KMLmerge_files('fileName','Jarkus_info.kml',...
%             'sourceFiles',sourceregion,...
%                 'kmlName','Jarkus info',...
%      'deleteSourceFiles',false);
%  
% % TO ADJUST!
% zip    (['Jarkus_info_fig','.zip'],{'Jarkus_info_fig.kml','js','css'})
% copyfile(['Jarkus_info_fig','.zip'],['Jarkus_info_fig','.kmz'])
% delete (['Jarkus_info_fig','.zip'])
