function varargout = nc_cf_gridset_overview(varargin)
%NC_CF_GRIDSET_OVERVIEW   make kml file with links to each tile in a netCDF gridset
%
%   nc_cf_gridset_overview(<keyword,value>)
%
% Example: generate files for on server from local cache on F:\
%
%  nc_cf_gridset_overview('fileName',['F:\KML\rijkswaterstaat\kustlidar\kustlidar_overview.kml'],...
%                         'load_kml',''F:\KML\rijkswaterstaat\kustlidar',...
%                       'kmlPathFcn',@(s) strrep(s,''F:\KML\rijkswaterstaat\kustlidar',''http://dtvirt5.deltares.nl/kml/''),...
%                          'datestr','YYYY-mm',...
%                          'load_nc','F:\opendap\thredds\rijkswaterstaat\kustlidar\',...
%                       'urlPathFcn',@(s) path2os(strrep(s,'F:\opendap\thredds\',['http://opendap.deltares.nl/thredds/','dodsC/opendap/'     ]),'http'),...
%                       'ftpPathFcn',@(s) path2os(strrep(s,'F:\opendap\thredds\',['http://opendap.deltares.nl/thredds/','fileServer/opendap/']),'http'),...
%                      'description','<a href="http://www.rijkswaterstaat.nl">Rijkswaterstaat</a> kusthoogte provided by <a href="http://www.openearth.nl"> OpenEarthTools</a>');
%
%See also: nc_cf_gridset2kml, snctools, nc_multibeam > nc_gridset

%% initialize

 %% set options

 OPT                  = KML_header;
 OPT.fileName         = '';

 OPT.EPSGcode         = 28992; % should be inside dataset

 OPT.link2opendap     = 1; % only THREDDS, not HYRAX
 OPT.load_nc          = '';
 OPT.urlPathFcn       = @(s)(path2os(s,'http')); % function to run on urlPath, as e.g. strrep
 OPT.ftpPathFcn       = @(s)(path2os(s,'http')); % function to run on urlPath, as e.g. strrep

 OPT.link2prerendered = 0; % only when nc_cf_gridset2kml.m is run first
 OPT.load_kml         = '';
 OPT.kmlPathFcn       = @(s)(path2os(s,'http')); % function to run on urlPath, as e.g. strrep
 OPT.datestr          = 'YYYY-mm'; % for 3D kml file names
 OPT.lineWidth        = 1;
 OPT.lineColor        = [0 0 0];
 OPT.lineAlpha        = 1;
 OPT.openInGE         = false;
 OPT.reversePoly      = false;
 OPT.disp             = 0;

 OPT.text             = '';

%% File keywords

if nargin==0;varargout = {OPT};return;end

OPT = setproperty(OPT,varargin,'onExtraField','silentIgnore');

%%

EPSG  = load('EPSG');
files = opendap_catalog(OPT.load_nc,'ignoreCatalogNc',1);

for ii = 1:length(files);
   [path, fname]         = fileparts(files{ii});
   x                     = nc_actual_range(files{ii},   'x'); % gets to xllcenter, and not xllcorner, except when nc is generated by ...
   y                     = nc_actual_range(files{ii},   'y'); % ... nc_multibeam_from_asc_test who puts xllcorner in the actual_range attribute
   x2                    = [x(1) x(end) x(end) x(1) x(1)];
   y2                    = [y(1) y(1) y(end) y(end) y(1)];
  [lon2(:,ii),lat2(:,ii)] = convertCoordinates(x2,y2,EPSG,'CS1.code',OPT.EPSGcode,'CS2.name','WGS 84','CS2.type','geo');

   markerNames{ii}       = fname;
   markerLat(ii)         = mean(lat2(1:4,ii));
   markerLon(ii)         = mean(lon2(1:4,ii));
   markerX(ii,:)         = [min(x(:)) max(x(:))];
   markerY(ii,:)         = [min(y(:)) max(y(:))];
end

%% start KML

OPT.fid=fopen(OPT.fileName,'w');

%% HEADER

output = KML_header(OPT);

%% STYLE

OPT_style = struct(...
    'name'     ,['style' num2str(1)],...
    'lineColor',OPT.lineColor(1,:) ,...
    'lineAlpha',OPT.lineAlpha(1),...
    'lineWidth',OPT.lineWidth(1));
output = [output KML_style(OPT_style)];

if length(OPT.lineColor(:,1))+length(OPT.lineWidth)+length(OPT.lineAlpha)>3
    for ii = 2:length(lat(1,:))
        OPT_style.name = ['style' num2str(ii)];
        if length(OPT.lineColor(:,1))>1;OPT_style.lineColor = OPT.lineColor(ii,:);end
        if length(OPT.lineWidth(:,1))>1;OPT_style.lineWidth = OPT.lineWidth(ii,:);end
        if length(OPT.lineAlpha(:,1))>1;OPT_style.lineAlpha = OPT.lineAlpha(ii,:);end
        output = [output KML_style(OPT_style)];
    end
end
%% marker BallonStyle

output = [output ...
    '<Style id="normalState">\n'...
    '<IconStyle><scale>0.7</scale><Icon><href>\n'...
    'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png\n'...
    '</href></Icon></IconStyle>\n'...
    '<LabelStyle><scale>0</scale></LabelStyle>\n'...
    '</Style>\n'...
    '<Style id="highlightState">\n'...
    '<IconStyle><Icon><href>\n'...
    'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png\n'...
    '</href></Icon></IconStyle>\n'...
    '<BalloonStyle>\n'...
    '<text><![CDATA[<h3>$[name]</h3>\n'...
    '$[description]<hr /><br />Provided by:\n'...
    '<img src="http://kml.deltares.nl/kml/logos/OpenEarth-logo-blurred-white-background.png" align="right" width="100"/>]]></text>\n'...
    '</BalloonStyle></Style>\n'...
    '<StyleMap id="MarkerBalloonStyle">\n'...
    '<Pair><key>normal</key><styleUrl>#normalState</styleUrl></Pair> \n'...
    '<Pair><key>highlight</key><styleUrl>#highlightState</styleUrl></Pair> \n'...
    '</StyleMap>\n'];

%% print output
output = [output, '<Folder>'];
output = [output, '<name>bounding boxes</name>'];
output = [output, '<Name>Outlines</Name>'];
fprintf(OPT.fid,output);

%% LINE
OPT_line = struct(...
    'name'      ,'',...
    'styleName' ,['style' num2str(1)],...
    'timeIn'    ,[],...
    'timeOut'   ,[],...
    'visibility',1,...
    'extrude'   ,0);
% preallocate output
output = repmat(char(1),1,1e5);
kk = 1;
for ii=1:length(lat2(1,:))
    if length(OPT.lineColor(:,1))+length(OPT.lineWidth)+length(OPT.lineAlpha)>3
        OPT_line.styleName = ['style' num2str(ii)];
    end
    OPT_line.name = markerNames{ii};
    newOutput     =  KML_line(lat2(:,ii),lon2(:,ii),'clampToGround',OPT_line);
    output(kk:kk+length(newOutput)-1) = newOutput;
    kk = kk+length(newOutput);
    if kk>1e5
        %then print and reset
        fprintf(OPT.fid,output(1:kk-1));
        kk     = 1;
        output = repmat(char(1),1,1e5);
    end
end
fprintf(OPT.fid,output(1:kk-1)); % print output

%% labels
output = '</Folder>';
output = [output, '<Folder>'];
output = [output, '<name>Links</name>'];
output = [output, '<Name>Outlines</Name>'];

%% generate markers

%% tableContents

for ii=1:length(lat2(1,:))
    
    if OPT.disp;disp(sprintf('writing coordinates: % 2d / %d',ii,length(files)));end
    
    table = '';

    % export this to external hmtl, stored with and generated with the actual kml's
    
    if OPT.link2prerendered
       tableContents = '<tr><td>date</td><td>full</td><td>triangulated</td><td>tiled</td></tr><hr>';
    else
       tableContents = '<tr><td>date</td></tr><hr>';
    end
    
    tempString    = OPT.kmlPathFcn([OPT.load_kml,filesep,'3D',filesep,markerNames{ii}]);
    timestr       = cellstr(datestr(nc_cf_time(files{ii},'time'),OPT.datestr));
    for jj = 1:length(timestr)
       tempStringt = path2os([tempString '_' timestr{jj}],'h');

        if OPT.link2prerendered
        % TO DO: ping kml
        str3D = [' <td><a href="' tempStringt '_3D_orth.kmz" >3D </a></td>'  ,...
                 ' <td><a href="' tempStringt '_3D_tri.kmz"  >3D </a></td>'  ,...
                 ' <td><a href="' tempStringt '_3D_tiled.kmz">3D </a></td>'];
        else
        str3D = '';
        end
        %end
        tableContents = [tableContents sprintf([...
            '<tr><td>%s</td>'...      % year
            '%s</tr>\n'],....% 3D
            timestr{jj},str3D)];
    end
    
    % generate table with data links
    table = [...
        '<h3>Available time instances</h3>\n'...
        '<table border="0" padding="0" width="200">'...
        tableContents...
        '</table>'];
    
    if OPT.link2opendap
    
      table = [table ...
         '<h3>Meta information</h3>'...
         '<table border="0" padding="0" width="200">'...
            sprintf([...
           '<tr><td>THREDDS server</td><td><a href="%s">meta-info:    </a></td></tr>'...      % link to OPeNDAP
           '<tr><td>THREDDS server</td><td><a href="%s">netCDF via ftp</a></td></tr>\n'],...  % link to ftp
           [path2os(OPT.urlPathFcn(files{ii}),'h') '.html'],...  % e.g. http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/kustlidar/65az1.nc.html
           [path2os(OPT.ftpPathFcn(files{ii}),'h')        ]),... % e.g. http://opendap.deltares.nl/thredds/fileServer/opendap/rijkswaterstaat/kustlidar/65az1.nc
         '</table>'];
         
    end

    % generate description
    output = [output, sprintf([...
        '<Placemark>\n'...
        '<name>%s</name>\n'...                                         % name
        '<snippet></snippet>\n'...
        '<description><![CDATA[RD coordinates:  <br>\n'...
        'x: % 7.0f -% 7.0f<br>\n'...                                   % [xmin xmax]
        'y: % 7.0f -% 7.0f<br>\n'...                                   % [ymin ymax]
        '<hr />\n'...
        ... % 'Time animation'... %'<a href="%s">Time animation</a>'...% link to timeseries
        '%s'...                                                        % table with links to pre-remj
        ']]></description>\n'...
        '<styleUrl>#MarkerBalloonStyle</styleUrl>\n'...
        '<Point><coordinates>%3.8f,%3.8f,0</coordinates></Point>\n'... % lat lon
        '</Placemark>\n'],...
        markerNames{ii},markerX(ii,:),markerY(ii,:),...
        ... % [tempString 'png.kml'],...
        table,markerLon(ii),markerLat(ii))];
end

%% FOOTER

output = [output '</Folder>' KML_footer];
fprintf(OPT.fid,output);
%% close KML
fclose(OPT.fid);
%% compress to kmz?
if strcmpi  ( OPT.fileName(end),'z')
    movefile( OPT.fileName,[OPT.fileName(1:end-3) 'kml'])
    zip     ( OPT.fileName,[OPT.fileName(1:end-3) 'kml']);
    movefile([OPT.fileName '.zip'],OPT.fileName)
    delete  ([OPT.fileName(1:end-3) 'kml'])
end

