%% ws_rvaksas_shapefile2kml
% from shapefile 2 kml for the Western Scheldt macrocells shapefile

%% settings

OPT.directory_in      = 'P:\1202022-ltv-zandhuishouding\data\shapefiles';
OPT.directory_out     = 'P:\1202022-ltv-zandhuishouding\data\shapefiles';
OPT.filename          = 'rvaksas3\';
OPT.filename_dir      = 'rvaksas3'; % 'rvaksas3' or 'rvaksas3_vaknr' 
OPT.shpfile           = '*.shp';
OPT.epsg              = 28992;
OPT.description       = '';
OPT.color             = [1 1 0.5]; % [1 1 0]: rvaksas3; [1 1 1]: rvaksas3_vaknr 
OPT.cleanup           = 0;
OPT.pause             = 0;
OPT.plot              = 1;
OPT.fldname           = ''; % *.dbf fieldname entry to be used for name (default sequence number)
OPT.deleteSourceFiles = 1;
OPT.extrude           = 0; % 2D / 3D polygons
OPT.zScaleFun         = @(z) z.*100;

OPT.fname             = [OPT.filename, OPT.filename_dir, '.shp'];
   
%% read shape file

%R0    = shaperead(OPT.fname);  %% issues with reading metadata..shp.xlm (matlab mapping toolbox, )
[R,M]  = arc_shape_read(OPT.fname); %% still issues with reading chars (OpenEarth)
n  = length(R);

%% plot whole polygons
for i=1:n

   disp([num2str(i,'%0.3d'),' / ',num2str(n,'%0.3d')])

%% analyse

   x = R(i).X;
   y = R(i).Y;
      
   if isempty(x) % 'zuid holland\waterkeringen\Waterkeringen.shp' no 23
      warning(['shape with length 0: ',OPT.fname,' no ',num2str(i)])
   else
   
     [lon,lat]           = convertCoordinates(R(i).X,R(i).Y,'CS1.code',OPT.epsg,'CS2.code',4326);
      
      % for patch-holes remove the NaNs
      mask = isnan(R(i).X);
      lonp = lon;
      latp = lat;
      lonp(mask) = lonp(1);
      latp(mask) = latp(1);
   
   %% plot in matlab
   
      if OPT.plot
         h(i) = patch(lonp,latp,[0 1 0]);
         hold on
         p(i) = plot (lon,lat,'k');
         
         axislat(52)
        %axis equal
         hold on
         
         set(h(i),'edgecolor','none')
      end
      
   %% plot as google earth files
   
      if ~exist([OPT.directory_out,filesep,fileparts(OPT.fname)])
      mkpath([OPT.directory_out,filesep,fileparts(OPT.fname)])
      end
   
      fillnames{i} = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),num2str(i,'%0.3d'),'_fill.kml'];
      edgenames{i} = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),num2str(i,'%0.3d'),'_edge.kml'];
      textnames{i} = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),num2str(i,'%0.3d'),'_text.kml'];
      
      %% name
      if ~isempty(OPT.fldname)
         try
          namestr = R(i).(OPT.fldname);
         catch
             disp(char(fieldnames(R)))
             error(['unknown field:',OPT.fldname])
             break
         end
      else
         namestr = num2str(i);
      end

      %% thin back line
      KMLline (lat,lon,'fileName',edgenames{i},...
                        'kmlName',namestr,...
                      'lineColor',[1 1 1],...
                      'lineWidth',3);

      %% colored fill
      randcol = [rand rand rand];
      
      if     strcmpi(R(i).Geometry,'Point')
      elseif strcmpi(R(i).Geometry,'Line') 
      KMLline (lat,lon,'fileName',fillnames{i},...
           'kmlName',namestr,...
           'lineAlpha',0.6,...
           'lineColor',randcol,...
           'lineWidth',5);
      elseif strcmpi(R(i).Geometry,'Line')| ...
             strcmpi(R(i).Geometry,'Polygon')
      KMLpatch(latp'    ,lonp'    ,'fileName',fillnames{i},...
           'kmlName',namestr,...
         'lineAlpha',0,...
         'fillColor',randcol,...
         'fillAlpha',0.6);
      end

      fldnames = setxor(fieldnames(R),{'BoundingBox','X','Y','Geometry'});
         
      html = ['<table border="1"><tr>'];
      for j=1:length(fldnames)
         fldname = fldnames{j};
         value   = R(i).(fldname);
         if isnumeric(value)
         value = num2str(value);
         end
         html = [html '<td>' fldname '=</td><td>' value '</td><tr>'];
      end
      html = [html '</tr>'];
      

%% trying to create the marker kml from scratch
%% start KML
OPT.fid=fopen(textnames{i},'w');
%% HEADER
OPT_header = struct(...
    'name',namestr,...
    'open',0,...
    'description',OPT.description);
output = KML_header(OPT_header);

output = [output '<!--############################-->\n'];
fprintf(OPT.fid,output);

output = repmat(char(1),1,1e5);
kk = 1;

%% Plot the points

for ii=1:1 % :nn

    %% preprocess html
html = '';
  
    %% preprocess name

name = sprintf(' <name>%s</name>\n',num2str(i));

    OPT_poly.styleName = ['cmarker_map'];
    
coordinates = sprintf(' <Point><coordinates>% 2.8f,% 2.8f, 0</coordinates></Point>\n',lon(ii),lat(ii));
       
    newOutput= sprintf([...
        '<Placemark>\n'...
        '%s',...                          % no names so we see just the scatter points
        ' <visibility>1</visibility>\n'...
        '%s',... html
        ' <styleUrl>#%s</styleUrl>\n'...               % styleName
        '%s'...
        ' </Placemark>\n'],...
        name,...
        html,...
        OPT_poly.styleName,...
        coordinates);
    
    % add newOutput to output
    output(kk:kk+length(newOutput)-1) = newOutput;
    kk = kk+length(newOutput);
    
    % write output to file if output is full, and reset
    if kk>1e5
        fprintf(OPT.fid,'%s',output(1:kk-1));
        kk = 1;
        output = repmat(char(1),1,1e5);
    end
    
end

%% print and clear output

% print output

fprintf(OPT.fid,'%s',output(1:kk-1));

%% FOOTER

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

%% close KML

fclose(OPT.fid);
%%

end

   if OPT.pause
   pausedisp
   end
   
end

   if OPT.plot
      tickmap('ll')
   end
   
%% merge files

   edgename = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),'_edge.kml'];
   KMLmerge_files('fileName',edgename,'sourceFiles',edgenames,...
                   'kmlName','edge',...
         'deleteSourceFiles',OPT.deleteSourceFiles);

   fillname = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),'_fill.kml'];
   KMLmerge_files('fileName',fillname,'sourceFiles',fillnames,...
                   'kmlName','fill',...
         'deleteSourceFiles',OPT.deleteSourceFiles);
   
   textname = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),'_text.kml'];
   KMLmerge_files('fileName',textname,'sourceFiles',textnames,...
                   'kmlName','text',...
         'deleteSourceFiles',OPT.deleteSourceFiles);
       
   try % the XML meta-data files are generally a mess: they change per arcGIS version and per user.
   if ~isfield(M.dataset_description.identification,'dataset_title')
   M.dataset_description.identification.dataset_title = M.dataset_description.identification.alternative_title;
   end

   if ~isfield(M.dataset_description,'overview')
   M.dataset_description.overview.summary = '';
   else
      if ~isfield(M.dataset_description.overview,'summary')
      M.dataset_description.overview.summary = '';
      end
   end
   catch
      M.dataset_description                              = struct();
      M.dataset_description.identification.dataset_title = '';
      M.dataset_description.overview.summary             = '';
   end

   fullname = [OPT.directory_out,filesep,fileparts(OPT.fname),filesep,filename(OPT.fname),'.kml'];
   KMLmerge_files('fileName',fullname,...
                  'sourceFiles',{fillname edgename textname},...
                  'foldernames',{'areas','edges','texts'},...
       'kmlName',M.dataset_description.identification.dataset_title,...
   'description',M.dataset_description.overview.summary,...
   'deleteSourceFiles',OPT.deleteSourceFiles);
   
%% clean-up   
   
   if OPT.cleanup
    for i=1:n
     delete(edgenames{i})   
     delete(fillnames{i})   
     delete(textnames{i})   
    end
    delete(edgename)   
    delete(fillname)   
    delete(textname)   
   end

