%% Version <http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html>
% $Id$
% $Date$
% $Author$
% $Revision$
% $HeadURL$
% $Keywords: $

OPT.kmldir            = ['D:\PROJECTS\DIPOL\RDBMS\kml\'];
OPT.pngicon           = 'icon52.png';
OPT.pngcircle         = 'circle-white.png';
OPT.logo              = 'dipol_logo.png';
OPT.pnglogo           = 'dipol_logo4GE.png'; 
OPT.debug             = 0;

OPT.description       = ['<hr><table bgcolor="#333333" cellpadding="3" cellspacing="1"><tbody><tr><td colspan="1" bgcolor="#666666"><div style="color:#FFFFFF;">diPol</div></td></tr><tr><td bgcolor="#FFFFFF">Deliverable of the <a href="http://www.northsearegion.eu/ivb/home/">Interreg IVB North Sea Region Programme</a> diPol project. Impact of Climate Change on the Quality of Urban and Coastal Waters - Diffuse Pollution (diPol). For more information please refer to the official <a href="http://www.interreg-dipol.de">diPol</a> website www.interreg-dipol.de.</td></tr>. </table> <img src="eu_Logo.jpg"/>  <img src="interreg_logo.jpg"/>'];

OPT.descriptionpng = {'interreg_logo.jpg','eu_Logo.jpg'};
			 

OPT.snippet           = 'Data deliverable of the diPol project.';
OPT.database          = 'D:\PROJECTS\DIPOL\RDBMS\database_DiPol_Complete_V9a_June2012.xls';
OPT.base              = 'database_DiPol_Complete_V9a_June2012';
OPT.kmlName           = 'database_DiPol_Complete_V9a_June2012';
OPT.SamplesQuery      = 1; % integral parameters, calculated in sample base
OPT.ObservationsQuery = 0; % raw data, each observation

%% Load

   X  = database_DiPol_V2_load(OPT.database);
   X  = database_DiPol_V2_load2html(X,'Samples',OPT.SamplesQuery);

%% Make html per sample

   OPT.htmlfiles = {};

%% Plot SamplesQuery

if OPT.SamplesQuery
   disp(['... Please wait ', mfilename,' kml-ifying samples'])

   OPT.samples    = {};
   OPT.samplespng = {};
   
   multiWaitbar('Plot Samples', 0 );

         fldnames = {'Chemical_Quality',...
                     'Chemical_msPAF',...
                     'Chemical_msPAF_Metals',...
                     'Chemical_msPAF_PAHs',...
                     'Chemical_msPAF_other',...
                     'Chemical_MaxValueVsWFD_EQS',...
                     'Chemical_TUmax_Algae',...
                     'Chemical_TUmax_Invertebrates',...
                     'Chemical_TUmax_Fish',...
                     'Toxicity',...
                     'EcologicalQuality',...
                     'Pathogens_WaterQuality',...
                     'Pathogens_Bathing'}; % only selection with with some data
                     
         
         for ifld=1:length(fldnames)
         fldname = fldnames{ifld};
         if ~all(isnan(X.SamplesQuery.(fldname)))

            multiWaitbar('Plot Samples', ifld/length(fldnames));
            X1.fileName     = [OPT.kmldir,filesep,X.LCS.LCSName{1},'_',fldname,'.kml'];
            X1.CBcolorTitle = [mktex(fldname), '   -   www.OpenEarth.eu'];
           %X1.datenumStart = datenum(X.SamplesQuery.SamplingStart,'DD-MM-YYYY');
           %X1.datenumEnd   = datenum(X.SamplesQuery.SamplingSEnd ,'DD-MM-YYYY') + 1;
            
            for is = 1:length(X.SamplesQuery.SampleId)
              %X.Name{is} = [X.SamplesQuery.SamplingStart{is} ': ' X.SamplesQuery.Station{is}];
               X.Name{is} = [X.SamplesQuery.Station{is} ': ' X.SamplesQuery.SampleOriginSubType{is}];
               X.Name{is} = strrep(X.Name{is},'>',' over  ');
               X.Name{is} = strrep(X.Name{is},'<',' below ');
            end
            
            ind  = strcmpi(mkvar(X.Indices.Name),fldname);
            clim = [X.Indices.LowerLimit(ind) X.Indices.UpperLimit(ind)];
            
            [pngNames]=KMLscatter(X.SamplesQuery.Lat,...
                                  X.SamplesQuery.Lon,...
                                  X.SamplesQuery.(fldname),... 
                         'name',X.Name,...
                         'html',X.SamplesQuery.Html,...
                     'snippets','',... 
                      'kmlName',X.Indices.Name{ind},...
                  'description',X.Indices.Html{ind},...
                         'open',ifld==length(fldnames),... % last integral parameter
                      'visible',ifld==length(fldnames),... % last integral parameter
                     'fileName',X1.fileName,...            % differs per  integral parameter
                 'CBcolorTitle',X1.CBcolorTitle,...        % differs per  integral parameter
                       'CBcLim',clim,...
                  'markerAlpha',1.0,...
                  ... %'timeIn',X1.datenumStart   ,...
                 ... %'timeOut',X1.datenumEnd,... % TO DO: dt
            ... %'dateStrStyle','yyyy-mm-dd',...
              'iconnormalState',OPT.pngcircle,...
           'iconhighlightState',OPT.pngcircle,...
             'scalenormalState',.5,...
          'scalehighlightState',2,...
                'CBtemplateHor',[],'CBtemplateVer',[],...
                  'CBthickness',.05,'CBalignmargin',0.02,...
                    'CBfontrgb',[1 1 1],'CBbgcolor',[0 0 0],'CBtitlergb',[1 1 1],'CBframergb',[1 1 1]);
         
            OPT.samples{end+1}    = X1.fileName;
            OPT.samplespng{end+1} = pngNames{:};
         end
         end
         %%
         
   OPT.kmlintegral = [OPT.kmldir,filesep,'Integral parameters.kml'];

   KMLmerge_files('sourceFiles',{OPT.samples{:}},...
                      'kmlName','Integral parameters',...
                  'description','',...
                     'fileName',OPT.kmlintegral,...
                         'open',1,...
            'deleteSourceFiles',~OPT.debug)         

else

   OPT.kmlintegral = '';

end

%% Plot ObservationsQuery

   OPT.scatterpng = {};

if OPT.ObservationsQuery

   disp(['... Please wait ', mfilename,' kml-ifying observations'])

   OPT.scatter    = {};
   
   multiWaitbar('Plot Parameters', 0 );

   for ip = 1:length(X.Parameters.ParameterId)
   
      multiWaitbar('Plot Parameters', ip/length(X.Parameters.ParameterId));

      X1.ParameterId    = X.Parameters.ParameterId   (ip);
      X1.ParameterLong  = X.Parameters.ParameterLong {ip};
      X1.ParameterShort = X.Parameters.ParameterShort{ip};
      X1.ParameterUnit  = X.Parameters.ParameterUnit {ip};
      X1.Html           = X.Parameters.Html          {ip};
      X1.CBcolorTitle   = [mktex(X1.ParameterLong),' [',mktex(X1.ParameterUnit),']   -   www.OpenEarth.eu'];

   %%
      ind = find(X.ObservationsQuery.ParameterId==X1.ParameterId);

      if ~isempty(ind)
      
         clear X2
         
         X2.Lat     =         X.ObservationsQuery.Lat        (ind);
         X2.Lon     =         X.ObservationsQuery.Lon        (ind);
         X2.Value   =         X.ObservationsQuery.Value      (ind);
         X2.datenum = datenum(X.ObservationsQuery.SampleStart(ind),'DD-MM-YYYY');
         X2.Station =         X.ObservationsQuery.Station    (ind);
         
         for i=1:length(ind)
         X2.Name{i} = [datestr(X2.datenum(i),'  yyyy-mmm-dd') ': ' X1.ParameterShort ': ' X2.Station{i}];
         end
         
         X1.fileName = [OPT.kmldir,filesep,X.LCS.LCSName{1},'_',X1.ParameterShort,'.kml'];
         
         [pngNames]=KMLscatter( X2.Lat,...
                                X2.Lon,...
                                X2.Value,... 
                         'name',X2.Name,...
                         'html',[],...
                      'visible',0,...
                  'markerAlpha',1.0,...
                     'fileName',X1.fileName,...
                      'kmlName',[X1.ParameterShort],...
                      'snippet','',...
                  'description',X1.Html,...
                  ... %'timeIn',X2.datenum   ,...
                 ... %'timeOut',X2.datenum+75,... % TO DO: dt
            ... %'dateStrStyle','yyyy-mm-dd',...
              'iconnormalState',OPT.pngcircle,...
           'iconhighlightState',OPT.pngcircle,...
             'scalenormalState',.5,...
          'scalehighlightState',2,...
                 'CBcolorTitle',X1.CBcolorTitle,...
                'CBtemplateHor',[],'CBtemplateVer',[],...
                  'CBthickness',.05,'CBalignmargin',0.02,...
                    'CBfontrgb',[1 1 1],'CBbgcolor',[0 0 0],'CBtitlergb',[1 1 1],'CBframergb',[1 1 1]);
         
            OPT.scatter   {end+1} = X1.fileName;
            OPT.scatterpng{end+1}   = pngNames{:};
      end % isempty
   end % ip
   
   OPT.kmlraw = [OPT.kmldir,filesep,'Raw data.kml'];

   KMLmerge_files('sourceFiles',{OPT.scatter{:}},...
                      'kmlName','Raw data',...
                  'description','',...
                     'fileName',OPT.kmlraw,...
                         'open',0,...
            'deleteSourceFiles',~OPT.debug)
            
else

   OPT.kmlraw = '';

end

%% locations crosshair (sorted per LCS)

   disp(['... Please wait ', mfilename,' kml-ifying croshairs'])
   
   OPT.locations = {};

   for iloc = 1:length(X.LCS.LCSId)
   
      LCS     = X.LCS.LCSId(iloc);
      locmask = find(X.Stations.LCSId==LCS);
      locname = X.LCS.LCSName{iloc};
      OPT.locations{iloc} = [locname,'.kml'];
      
      description = ['<hr><table bgcolor="#333333" cellpadding="3" cellspacing="1"><tbody><tr><td colspan="4" bgcolor="#666666"><div style="color:#FFFFFF;">Stations</div></td></tr>'];
      description = strvcat(description,['<tr><td bgcolor="#BBBBBB"> </td><td bgcolor="#BBBBBB">',...
                                                      'Name</td><td bgcolor="#BBBBBB">',...
                                                      'Lat (°N)</td><td bgcolor="#BBBBBB">',...
                                                      'Lon (°E)</td></tr>']);
      for i=1:length(locmask)
      if isnan(X.Stations.Lat(locmask(i)))
      description = strvcat(description,['<tr><td bgcolor="#FFFFFF">',num2str(i),'</td><td bgcolor="#FFFFFF">',...
                                                       X.Stations.StationName{locmask(i)} ,'</td><td bgcolor="#FFFFFF">',...
                                                       ' </td><td bgcolor="#FFFFFF">',...
                                                       ' </td></tr>']);
      else
      description = strvcat(description,['<tr><td bgcolor="#FFFFFF">',num2str(i),'</td><td bgcolor="#FFFFFF">',...
                                                       X.Stations.StationName{locmask(i)} ,'</td><td bgcolor="#FFFFFF">',...
                                                       num2str(X.Stations.Lat(locmask(i))),'</td><td bgcolor="#FFFFFF">',...
                                                       num2str(X.Stations.Lon(locmask(i))),'</td></tr>']);
      end
      end   
      description = strvcat(description,'</table>');

      KMLmarker(X.Stations.Lat(locmask),...
                X.Stations.Lon(locmask),...
                         'name',{X.Stations.StationName{locmask}},...
                         'html',{X.Stations.Html{locmask}},...
                         'open',0,...
                  'markerAlpha',1.0,...
                     'fileName',OPT.locations{iloc},...
                      'kmlName',locname,...
                  'description',description,... % X.Stations.Html_overview,...
              'iconnormalState',OPT.pngicon,...
           'iconhighlightState',OPT.pngicon,...
             'scalenormalState',.5,...
          'scalehighlightState',.5);
       
   end

   OPT.kmllocations = [OPT.kmldir,filesep,OPT.base,'_crosshair','.kml'];

   KMLmerge_files('sourceFiles',{OPT.locations{:}},...
                      'kmlName','Location marks',...
                  'description','',...
                     'fileName',OPT.kmllocations,...
                         'open',0,...
            'deleteSourceFiles',~OPT.debug);

%% logo

   OPT.kmllogo = [OPT.kmldir,filesep,'dipol_logo.kml'];

   KMLlogo('fileName',OPT.kmllogo,...
             'imName',[OPT.kmldir,filesep,OPT.logo],...
            'kmlName','diPol logo',...
           'logoName',OPT.pnglogo,...
          'overlayXY',[0 0],...
           'screenXY',[0.05 0.05]); % lower right, above Google

%% merge

   sourceFiles = {OPT.kmllocations,OPT.kmlintegral      ,OPT.kmllogo,OPT.kmlraw};
   foldernames = {'locations'     ,'Integral parameters','logo'     ,'Raw data'};
   
   KMLmerge_files('sourceFiles',sourceFiles,...
                      'snippet',OPT.snippet,...
                  'description',OPT.description,...
                  ... %'timeIn','2009-11-18',...
                 ... %'timeOut','2010-06-29',... % TO DO: dt
                     'fileName',[OPT.kmldir,filesep,OPT.base,'.kml'],...
                      'kmlName',OPT.kmlName,...
                         'open',1,...
            'deleteSourceFiles',~OPT.debug,...
                    'cameralon',5,... % hamburg appears between image credits and google logo
                    'cameralat',56.67,... % oslo (northest) and hamburg (southest) in FOV
                      'cameraz',1000e3)
                     
%% make kmz

   KML2kmz([OPT.kmldir,filesep,OPT.base,'.kml'],...
            OPT.pngcircle,OPT.pnglogo,...
           [OPT.kmldir,filesep,OPT.pngicon],...
            OPT.descriptionpng,...
            OPT.scatterpng,...
            OPT.samplespng,...
            OPT.htmlfiles); 
   if ~OPT.debug
   deletefile(OPT.samplespng,OPT.scatterpng)
   end
