
FileName='Nourishements_test.kml';

%% start .kml file

OPT.fid                 = fopen(FileName,'w');
OPT.icon                = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';
OPT.iconnormalState     = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';%'http://svn.openlaszlo.org/sandbox/ben/smush/circle-white.png';
OPT.iconhighlightState  = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';%'http://svn.openlaszlo.org/sandbox/ben/smush/circle-white.png';
OPT.scalenormalState    = 0.5;
OPT.scalehighlightState = 1.0;

%% HEADER
OPT_header = struct(...
    'name'       ,'Nourishments',...
    'open'       ,0,...
    'description','Nourishments');
    
output = KML_header(OPT_header);
output = [output '<open>1</open>'];

%% STYLE for patches

output = [output KML_stylePoly('name','patch_strandsuppletie'           ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',[1 0 0])];
output = [output KML_stylePoly('name','patch_onderwatersuppletie'       ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',[0 1 0])];
output = [output KML_stylePoly('name','patch_zeewaartse_duinverzwaring' ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',[1 0 1])];
output = [output KML_stylePoly('name','patch_landwaartse_duinverzwaring','lineAlpha',0.,'fillAlpha',.3,'fillColor',[1 1 0])];
output = [output KML_stylePoly('name','patch_otherwise'                 ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',[0 1 1])];

output = [output KML_stylePoly('name','line_strandsuppletie'            ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',[1 0 0])];
output = [output KML_stylePoly('name','line_onderwatersuppletie'        ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',[0 1 0])];
output = [output KML_stylePoly('name','line_zeewaartse_duinverzwaring'  ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',[1 0 1])];
output = [output KML_stylePoly('name','line_landwaartse_duinverzwaring' ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',[1 1 0])];
output = [output KML_stylePoly('name','line_otherwise'                  ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',[0 1 1])];

%% STYLE for pushpin

output = [output ...
    '<StyleMap id="pushpin">\n'...
    ' <Pair><key>normal</key><styleUrl>#pushpin_normal</styleUrl></Pair>\n'...
    ' <Pair><key>highlight</key><styleUrl>#pushpin_highlight</styleUrl></Pair>\n'...
    '</StyleMap>\n'...
    '<Style id="pushpin_normal">\n'...
    ' <IconStyle>\n'...
    ' <scale>' num2str(OPT.scalenormalState) '</scale>\n'...
    ' <Icon><href>'    OPT.iconnormalState '</href></Icon>\n'...
    ' </IconStyle>\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'...
    ' <Icon><href>'    OPT.iconhighlightState '</href></Icon>\n'...
    ' </IconStyle>\n'...
    ' <LabelStyle></LabelStyle>\n'...
    ' </Style>\n'];

%output = [output, '<Folder>'];
%output = [output, '<name>patches</name>'];

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


%% get and write nourishement data

[data,text]=xlsread(which('supp-holland-metnourishtypes_new.xls'),'intervention data');
data = data(8:end,1:13);
text = text(8:end,1:14);

text(      data( :,8)==0 ,:)=[]; % delete zero nourishements
data(      data( :,8)==0 ,:)=[];
text(isnan(data( :,6)   ),:)=[]; % delete unknown location
data(isnan(data( :,6)   ),:)=[];
%          data(48,1)=8;         % correct mistake in data

%% indices of faults in nourishment data


if 0 %%%%%   

   % get transect IDs

   TransectIDs = DBGetTableEntryRaw('transect','datatypeinfo','JARKUS data','year','2007');
   for i=1:length(TransectIDs) % convert to usable array
       TransectIDs2(i,1) = str2double(TransectIDs(i).areacode);
       TransectIDs2(i,2) = str2double(TransectIDs(i).transectID);
       TransectIDs2(i,3) =            TransectIDs(i).xRD;
       TransectIDs2(i,4) =            TransectIDs(i).yRD;
   end

   % repair faults

   temp=find(data(:,6)==data(:,7)|...  % begin raai = eind raai
                  isnan(data(:,7))|... % geen eindraai
           (data(:,11)==data(:,9)));   % x_begin = x_eind
   
   for j=1:length(temp)
       i=temp(j);
       %find transect closest to value in data
       [ignore, ind]=min(abs(TransectIDs2(TransectIDs2(:,1)==data(i,1),2)-100*data(i,6)));
       ind=ind+find(TransectIDs2(:,1)==data(i,1),1,'first')-1;
       
       %use the coordinates of the next and previous transect, provided they
       %are in the same area
       if data(i,1)==TransectIDs2(ind-1,1)
           data(i,[6 9:10])=TransectIDs2(ind-1,[2 3:4]);
       else
           data(i,[6 9:10])=TransectIDs2(ind,[2 3:4]);
       end
       if data(i,1)==TransectIDs2(ind+1,1)
           data(i,[7 11:12])=TransectIDs2(ind+1,[2 3:4]);
       else
           data(i,[7 11:12])=TransectIDs2(ind,[2 3:4]);
       end
       data(i,13)=data(i,8)/(data(i,7)-data(i,6))/10;
       data(i,6:7)=data(i,6:7)/100;
   end
   
   temp=find(isnan(data(:,9))); % geen x_begin
   for j=1:length(temp)
       i=temp(j);
       
       %find transect closest to value in data (only look northward)
       ind=find(TransectIDs2(:,1)==data(i,1)&TransectIDs2(:,2)<100*data(i,6),1,'last');
       if isempty(ind)
           ind=find(TransectIDs2(:,1)==data(i,1),1,'first');
       end
       
       %use the coordinates of the next and previous transect
       data(i,9:10)=TransectIDs2(ind,3:4);
   end
   
   temp=find(isnan(data(:,11))); % geen x_end
   for j=1:length(temp)
       i=temp(j);
       
       %find transect closest to value in data (only look southward)
       ind=find(TransectIDs2(:,1)==data(i,1)&TransectIDs2(:,2)>100*data(i,7),1,'first');
       
       %use the coordinates of the next and previous transect
       data(i,11:12)=TransectIDs2(ind,3:4);
   end
   
end %%%%%   

text(any(isnan(data),2),:)=[];
data(any(isnan(data),2),:)=[];
for i=1:length(data);

disp(['processing ',num2str(i,'%0.4d'),'/',num2str(length(data),'%0.4d')])

    x=[data(i, 9);data(i,11)]; % x_begin x_end
    y=[data(i,10);data(i,12)]; % y_begin y_end 
    switch text{i,14}          % type
        case 'strandsuppletie'
        offset1=0;
        offset2=data(i,13);
        PolyStyleName='strandsuppletie';
        case 'onderwatersuppletie'
        offset1=400;
        offset2=data(i,13)+400;
        PolyStyleName='onderwatersuppletie';
        case 'zeewaartse duinverzwaring'
        offset1=-data(i,13)-30;
        offset2=-30;
        PolyStyleName='zeewaartse_duinverzwaring';
        case 'landwaartse duinverzwaring'
        offset1=-data(i,13)-100;
        offset2=-100;
        PolyStyleName='landwaartse_duinverzwaring';
        otherwise
        offset1=0;
        offset2=data(i,13);
        PolyStyleName='otherwise';
    end
    
    %% change signs for wadden island (joost may know why)
    
    if data(i,1)<7
        ofsset1=-offset1;
        offset2=-offset2;
    end
    x(3:4)=     x+(y(2)-y(1))*offset2/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    y(3:4)=     y-(x(2)-x(1))*offset2/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    x(1:2)=x(1:2)+(y(2)-y(1))*offset1/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    y(1:2)=y(1:2)-(x(2)-x(1))*offset1/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    x=x([1, 2, 4, 3, 1]);
    y=y([1, 2, 4, 3, 1]);
    [lon, lat]=convertCoordinates(x,y,'CS1.code',28992,'CS2.code',4326);
    
    %% add KML element for suppletie
    
    t0    =  num2str(data(i,3)  );
    t1    =  num2str(data(i,3)+1);
    name1 = [num2str(data(i,2)  ),'/',num2str(data(i,3)),'-',num2str(data(i,4)),'/',num2str(data(i,5))];
    name2 = [text{i,14}];
    name3 = [num2str(data(i,8)),' m^3'];
    html  = ['<hr>'...
             '<br><A href = "http://www.rijkswaterstaat.nl">Rijkswaterstaat</A> suppletie data.'...
             '<br><br> '...
             '<table border="1"> <tr>\n',...
             '<td>type   </td><td>',text{i,14},'</td></tr>\n',...
             '<td>tijdvak</td><td>(',num2str(data(i,2)),'/',num2str(data(i,3)),'-',num2str(data(i,4)),'/',num2str(data(i,5)),')','</td></tr>\n',...
             '<td>volume </td><td>',num2str(data(i,8)),' m^3','</td></tr>\n',...
             '<td>volume per strekende meter</td><td>',num2str(data(i,13)),' m^3/m','</td></tr>\n',...
             '<td>kustvak</td><td>',num2str(data(i,1)),' = ',getKustvak(data(i,1)),' </td></tr>\n',...
             '<td>x</td><td>',num2str(data(i, 9)),' - ',num2str(data(i,11)),' m</td></tr>\n',...
             '<td>y</td><td>',num2str(data(i,10)),' - ',num2str(data(i,12)),' m</td></tr>\n',...
             '</table>',...
             '<br>Provided by:',...
             '<img src="https://public.deltares.nl/download/attachments/16876019/OET?version=1" align="right" width="100"/>'];
    
    output = [output '<Folder>'];
    output = [output '<name>' name1 '</name>'];
    output = [output '<open>1</open>'];
    output = [output   KML_poly(lat,lon,'clampToGround','name',name2,'styleName',['patch_',PolyStyleName],'timeIn',t0,'timeOut',t1)];
    output = [output '<Folder>'];
    output = [output '<name>' name3 '</name>'];
    output = [output '<open>0</open>'];
    output = [output   KML_line(lat,lon,'clampToGround','name','outline','styleName',['line_' ,PolyStyleName],'timeIn',t0,'timeOut',t1)];
    output = [output ...
             ' <Placemark>'...
             ' <TimeSpan>\n'...
             ' <begin>',t0,'</begin>\n'...          % t0
             ' <end>',t1,'</end>\n'...              % t1
             ' </TimeSpan>\n'...
             ' <name>',name2,'</name>\n'...          % name
             ' <description><![CDATA['...           % start required wrapper for html
              html,...                              % description
              ']]></description>\n'...              % end   required wrapper for html
             ' <styleUrl>#pushpin</styleUrl>\n'...  % styleName
             ' <Point><coordinates>',num2str(lon(3)),',',num2str(lat(3)),',0</coordinates></Point>\n'...
             ' </Placemark>'];
    output = [output '</Folder>'];
    output = [output '</Folder>'];
    
end

    fprintf(OPT.fid,output);

%% FOOTER

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

%% close KML

fclose(OPT.fid);
