function ldb2kml(varargin)
%LDB2KML Converts ldb to kml-file
%
% Reads a landboundary file and save it to a kml-file which can be opened
% in Google Earth.
%
% Syntax:
% ldb2kml(varargin)
%
% INPUT:
%    varargin = the names of the ldb and kml files. They are given as
%               key/value pairs
%               ldb:      the file descriptor of the landboundary file. When not given
%                         the name is asked via a UI (uigetfile)
%               kml:      the file descriptor of the kml file. When not given
%                         the name is set to the name of the ldb, unless the
%                         value is set to 'get'
%               color:    get the color to be used for the presentation. It
%                         is given. It is a cell with numbers for RGB: {R,G,B}. 
%                         When the value is 255 the full coloring part is used,
%                         with 0 nothing of the color is used.
%                         The default: {255,0,0}.
%                         It is also possible to use 'get', you will asked
%                         for the color parts via a UI.
%               opacity:  the percentage of non-transparency:
%                         100 = no transparency (default)
%                           0 = fully transparent
%
% See also: KML2LDB, LDBTOOL, LDB2SHAPE

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2010 Deltares
%       Arjan Mol
%
%       arjan.mol@deltares.nl
%
%       Deltares
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%   Revision 21-12-2010:
%        L. Verhage
%        changed to key/value input
%
%   This library is free software: you can redistribute it and/or
%   modify it under the terms of the GNU Lesser General Public
%   License as published by the Free Software Foundation, either
%   version 2.1 of the License, or (at your option) any later version.
%
%   This library is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%   Lesser General Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with this library. If not, see <http://www.gnu.org/licenses/>.
%   --------------------------------------------------------------------

% This tool is part of <a href="http://OpenEarth.nl">OpenEarthTools</a>.
% OpenEarthTools is an online collaboration to share and manage data and 
% programming tools in an open source, version controlled environment.
% Sign up to recieve regular updates of this function, and to contribute 
% your own tools.

%% INITIALIZE

OPT.ldb     = '';
OPT.kml     = '';
OPT.color   = {255,0,0};
OPT.opacity = 100;

OPT = setproperty(OPT,varargin{:});

if isempty(OPT.ldb)
    [nam pat]=uigetfile('*.ldb','Select landboundary file');
    if nam==0
        return
    end
    ldbName = [pat nam];
else
    ldbName = OPT.ldb;
end

if ~exist(ldbName)
    disp (['!!!! File "' ldbName '" not found.']);
    return
end

if isempty(OPT.kml)
    [PATHSTR,fName,EXT] = fileparts(ldbName);
    if ~isempty(PATHSTR)
        kmlName = [PATHSTR filesep fName '.kml'];
    else
        kmlName = [fName '.kml'];
    end
else
    if strcmpi(OPT.kml,'get');
        [fName fPat]=uiputfile('*.kml','Save kml-file to...');
        kmlName = [fPat fName];
    else
        kmlName = OPT.kml;
    end
end
[PATHSTR,fName,EXT] = fileparts(kmlName);

if isempty(OPT.color) 
    clr(1) = 255;
    clr(2) = 0;
    clr(3) = 0;
elseif strcmpi(OPT.color,'get')
    clr=str2num(char(inputdlg({'Red','Green','Blue'},'Specify RGB color',1,{'255','0','0'})));
    if isempty(clr)
%         clrString='ffff0000';
        clr(1) = 255;
        clr(2) = 0;
        clr(3) = 0;
    end
else
    clr(1) = OPT.color{1};
    clr(2) = OPT.color{2};
    clr(3) = OPT.color{3};
end
clr=[min(255,clr(1)); min(255,clr(2)); min(255,clr(3))];
clr=[max(0,clr(1)); max(0,clr(2)); max(0,clr(3))];

opacity = floor((OPT.opacity * 255) / 100);

%% Code

ldb=landboundary('read',ldbName);
ldb=ldb(:,1:2);

fid=fopen(kmlName,'w');

fprintf(fid,'%s \n','<?xml version="1.0" encoding="UTF-8"?>');
fprintf(fid,'%s \n','<!--x=x+                  -->');
fprintf(fid,'%s \n','<!--y=y+                  -->');
fprintf(fid,'%s \n','<kml xmlns="http://earth.google.com/kml/2.1">');
fprintf(fid,'%s \n', '<Document>');
fprintf(fid,'%s \n',['   <name>' fName '</name>']);
fprintf(fid,'%s \n', '   <Style id="style_1">');
fprintf(fid,'%s \n', '      <LineStyle>');
fprintf(fid,'%s \n',['         <color> FF' dec2hex(clr(3),2) dec2hex(clr(2),2) dec2hex(clr(1),2) '</color>']);
fprintf(fid,'%s \n',['         <width>5</width>']);
fprintf(fid,'%s \n', '      </LineStyle>');
fprintf(fid,'%s \n', '      <PolyStyle>');
% fprintf(fid,'%s \n', '			<fill>1</fill>');
fprintf(fid,'%s \n',['         <color>' dec2hex(opacity) dec2hex(clr(3),2) dec2hex(clr(2),2) dec2hex(clr(1),2) '</color>']);
fprintf(fid,'%s \n', '      </PolyStyle>');
fprintf(fid,'%s \n', '   </Style>');

if ~isnan(ldb(1,1))
    ldb=[nan nan;ldb];
end
if ~isnan(ldb(end,1))
    ldb=[ldb;nan nan];
end

did=find(isnan(ldb(:,1)));
if ~isempty(did)
    rid=abs(did(1:end-1)-did(2:end));
    remid=find(rid==1);
    ldb(did(remid),:)=[];
end

id=find(isnan(ldb(:,1)));

hW=waitbar(0,'Please wait while writing kml-file...');
for ii=1:length(id)-1
    data=ldb(id(ii)+1:id(ii+1)-1,:);
    fprintf(fid,'%s \n', '   <Placemark>');
    fprintf(fid,'%s \n',['   <name>' num2str(ii) '</name>']);
    fprintf(fid,'%s \n', '   <styleUrl>style_1</styleUrl>');
    fprintf(fid,'%s \n', '   <Polygon>');
    fprintf(fid,'%s \n', '      <tessellate>1</tessellate>');
    fprintf(fid,'%s \n', '      <outerBoundaryIs>');
    fprintf(fid,'%s \n', '         <LinearRing>');
    fprintf(fid,'%s \n', '            <coordinates>');
    for ij=1:size(data,1)
        fprintf(fid,'%s \n',['               ' num2str(data(ij,1),'%15.6f') ',' num2str(data(ij,2),'%15.6f') ', 0']);
    end
    fprintf(fid,'%s \n', '            </coordinates>');
    fprintf(fid,'%s \n', '        </LinearRing>');
    fprintf(fid,'%s \n','      </outerBoundaryIs>');
    fprintf(fid,'%s \n','   </Polygon>');
    fprintf(fid,'%s \n','   </Placemark>');
    waitbar(ii/(length(id)-1),hW);
end
close(hW);
fprintf(fid,'%s \n','</Document>');
fprintf(fid,'%s \n','</kml>');
fclose(fid);