function [ok,info,varargout] = kmlCreateSectionCoastlineCharts(section,varargin)
%kmlCreateSectionCoastlineCharts   writes coastlines to a kml file
%
%   The charts for the section and its jarkus transects are gathered 
%   in a kml file. It is checked whether the charts are available.
%
%   Syntax:
%   plotSectionCharts(section)
%
%   Input: 
%     section  = the section number to plot the charts for
%     varargin = when given:
%                 'kml'      : information for the kml file
%                              a) when a positive number, it is the fid of the kml file;
%                              b) when a name it is the filedescriptor
%                              !! when not given an error must return
%                 'mfile'    : the calling function. When not found the
%                              function is called itself. The name of the
%                              calling fuction:
%                              "kmlCreateAllCoastlineCharts"
%                 'waittext' : the text during the writing to file;
%     load CoastLineInfo
%       a save must have been done of various data in "CoastLineInfo"
%         charts  : the coast line values for the transects and the years
%         years   : the years with possible data for the coast lines
%         secTrans: the id for the section and the transect = section*10^6 +
%                   transect
%         LonLat  : the Lon/lat coordinates for the given transects in secTrans
%         sections: the section numbers and the related section names
%
%   Output:
%      ok        = 0 no correct computation, the function stopped
%                 1 no problems
%      info      = info message
%      varargout = when ok==0, possible section numbers
%
%   Example
%   plotSectionCharts
%
%   See also 

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2010 <COMPANY>
%       Lou Verhage
%
%       <lou.verhage@deltares.nl>	
%
%       <ADDRESS>
%
%   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.

%% Version <http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html>
% Created: 22 Mar 2010
% Created with Matlab version: 7.8.0.347 (R2009a)

% $Id: kmlCreateSectionCoastlineCharts.m 4926 2011-04-18 13:00:40Z verhage $
% $Date: 2011-04-18 15:00:40 +0200 (Mon, 18 Apr 2011) $
% $Author: verhage $
% $Revision: 4926 $
% $HeadURL: https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/kustlijnkaartenboek/scripts/kmlCreateSectionCoastlineCharts.m $
% $Keywords: $

%% initialize

ok   = true;
info = '';
if nargout > 2
    m = 0;
    for n = 3:nargout
        m = m + 1;
        varargout{m} =[];
    end
end

OPT.kml      = '';
OPT.mfile    = '';
OPT.waittext = '';
OPT.icon     = '';
OPT.jpg      = '';

OPT = setProperty(OPT,varargin);
    
if strcmpi(OPT.mfile,'kmlCreateAllCoastlineCharts')
    called = true;
else
    called = false;
end

if called
    if isempty(OPT.kml)
        ok   = false;
        info = ['In the calling function "' OPT.mfile '" no kml-fid given'];
        return
    else
        if ~isnumeric(OPT.kml)
            ok = false;
            info = ['In the calling function "' OPT.mfile '" the kml-fid is not a number'];
        elseif OPT.kml <= 0
            ok = false;
            info = ['In the calling function "' OPT.mfile '" the kml-fid is < 0'];
        else
            fid = OPT.kml;
        end
        if ~ok, return, end
    end
else
    if ~isempty(OPT.kml)
        if isnumeric(OPT.kml)
            fid = OPT.kml;
        else
            fName = OPT.kml;
            [ok,info,fid] = kmlWriteHeader(fName,'icon',OPT.icon);
            if ~ok, return, end
            if nargout < 4 && called
                ok   = false;
                info = 'the file handlers for the kml files must be returned.';
                return
            else
                varargout{1} = fid;
            end
        end
    else
        ok   = false;
        info = 'No kml filedescriptor found';
        return
    end
end
filevariables = {'sections','secTrans','LonLat'};
load('CoastLineInfo.mat', filevariables{:});

% get the correct section number

[nrSec,indSections] = getSectionInfo(section,sections);

if ~isempty(nrSec)
    ok = false;
    m = 0;
    for n = 1 : length(secTrans)
        secNr = floor(secTrans(n) / 1.e6);
        if secNr == section
            m = m + 1;
        end
    end
    s = char(strcat('<Folder><name>',sections.name(indSections),'</name>\n'));
    fprintf(fid,s);
    fprintf(fid,'<Open>0</Open>\n');
%% Handle transects
    if called
        handle = waitbar(0, [mfilename ': get transect numbers, ' OPT.waittext]);
    else
        handle = waitbar(0, 'Get transect numbers');
    end
    fprintf(fid,'<Document>');
    fprintf(fid,'<visible>0</visible>');
    fprintf(fid,'<name>Jarkus transects</name>');
    telop = 0;
    for n = 1 : length(secTrans)
        secNr = floor(secTrans(n) / 1.e6);
        if secNr == section
            transNr = secTrans(n) - secNr * 1.e6;
            telop = telop + 1;
            waitbar(telop/m);
            nsecTrans = n;

            fidTransect = fopen('templateTransect.kml','r');
            while ~feof(fidTransect)
                line = fgetl(fidTransect);
                k = findstr(line, 'NRNR');
                if ~isempty(k)
                    s = strrep(line,'NRNR',num2str(transNr));
                else
                    s = line;
                end
                k = findstr(s, 'XSTART');
                if ~isempty(k)
                    s = strrep(s,'XSTART',num2str(LonLat.Lon(nsecTrans)));
                end
                k = findstr(s, 'YSTART');
                if ~isempty(k)
                    s = strrep(s,'YSTART',num2str(LonLat.Lat(nsecTrans)));
                end
                k = findstr(s, 'XEND');
                if ~isempty(k)
                    s = strrep(s,'XEND',num2str(LonLat.jarkus.Lon(nsecTrans)));
                end
                k = findstr(s, 'YEND');
                if ~isempty(k)
                    s = strrep(s,'YEND',num2str(LonLat.jarkus.Lat(nsecTrans)));
                end
                s = [strrep(s,'\','\\') ' \n'];
                fprintf(fid,s);
            end
            fclose(fidTransect);
        end
    end
    fprintf(fid,'</Document>\n');
    waitbar(1, handle, 'Done!');
    close(handle)

    
%% Handle graphs

    fprintf(fid,'<Document><name>Graphs</name> \n');
    fprintf(fid,'<visible>1</visible> \n');
    if called
        handle = waitbar(0, [mfilename ': get graphs, ' OPT.waittext]);
    else
        handle = waitbar(0, 'Get Graphs');
    end
    telop = 0;
    for n = 1 : length(secTrans)
        secNr = floor(secTrans(n) / 1.e6);
        if secNr == section
            transNr = secTrans(n) - secNr * 1.e6;
            telop = telop + 1;
            waitbar(telop/m);
            [ok,info,check] = kmlWriteCoastlineChart(section,transNr, ...
                          'kml',fid,'mfile',mfilename,'jpg',OPT.jpg);
            if nargout > 2, varargout{1} = check;, end
            if ~ok
                waitbar(1, handle, 'Done!');
                close(handle)
                return
            end
        end
    end
    waitbar(1, handle, 'Done!');
    close(handle)
    fprintf(fid,'</Document> \n');
    fprintf(fid,'</Folder> \n');
else
    ok = false;
    info = ['Section number "' num2str(section) '" is not found'];
    if nargout > 2
        gather = {};
        for n = 1 : length(sections.name)
            gather{n,1} = sections.name{n};
            gather{n,2} = num2str(sections.number{n});
        end
        varargout{1} = gather;
    end
end

clear filevariables{:}

if ~called
    kmlClose(fid);
end

