function [ok,info,varargout] = kmlWriteCoastlineChart(sec,trans,varargin)
%KMLWRITECOASTLINECHART  write the placemark for a position chart
%
%   write a Placemark section to a kml file. When the function is not
%   called from mfile = "kmlCreateSectionCoastlineCharts" the kml file must
%   be initialized
%
%   Syntax:
%   [ok,info,varargout] = kmlWriteCoastlineChart(sec,trans,varargin)
%
%   Input:
%     sec        = the section to be selected
%                  1 - a number
%                  2 - a section name
%     trans      = the number of a transection
%     varargin   = keyword/value pairs
%                 '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:
%                              "kmlCreateSectionCoastlineCharts"
%                 'jpg'      : the directory where to find the jpg files
%   Also: 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        = when true the chart could be created, otherwise it is false
%     info      = one line with text when ok is false
%     varargout = possible transsection numbers when the one given is not
%                 found. It is best to use this option because you can select
%                 a transect from this output again.
%
%   Example
%   plotChart
%
%   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: 03 Mar 2010
% Created with Matlab version: 7.8.0.347 (R2009a)

% $Id: kmlWriteCoastlineChart.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/kmlWriteCoastlineChart.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.icon     = '';
OPT.jpg      = '';

OPT = setProperty(OPT,varargin);

storedAt = '';
if ~isempty(OPT.jpg)
    [PATHSTR,NAME,EXT,VERSN] = fileparts(OPT.jpg);
    if ~isempty(PATHSTR)
        storedAt = [PATHSTR filesep];
    end
end

if strcmpi(OPT.mfile,'kmlCreateSectionCoastlineCharts')
    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)
        fName = OPT.kml;
        [ok,info,fid] = kmlWriteHeader(fName,'icon',OPT.icon);
        if ~ok, return, end
    else
        ok   = false;
        info = 'No kml filedescriptor found';
        return
    end
end

%% get chart name
filevariables = {'secTrans', 'sections', 'LonLat', 'charts'};
load('CoastLineInfo.mat', filevariables{:});

clear years;

% get the correct section number
[nrSec,indSections] = getSectionInfo(sec,sections);
if isempty(nrSec)
    %no correct number or name given
    ok   = false;
    disp '=======================================';
    disp '= possible section names and numbers: =';
    disp '=======================================';
    if nargout > 2
        gather = {};
    end
    for n = 1 : length(sections.name)
        %s = ['name=' sections.name{n} '; number =' num2str(sections.number{n})]
        disp (['name=' sections.name{n} '; number =' num2str(sections.number{n})]);
        if nargout > 2
            gather{n,1} = sections.name{n};
            gather{n,2} = num2str(sections.number{n});
        end
    end
    if nargout > 2
        varargout = gather;
    end
    return
else
    info = '';
    indSec = find(cell2mat(sections.number) == nrSec);
end

combi = nrSec * 1e6 + trans;
nsecTrans = find(secTrans == combi);
if isempty(nsecTrans)
    ok = false;
    info = 'No correct transsections found for the section';
    disp '===============================';
    disp '= possible transsect numbers: =';
    disp '===============================';
    if nargout > 2
        gather = [];
    end
    
    m = 0;
    for n = 1 : length(secTrans)
        secNr   = floor(secTrans(n) / 1.e6);
        if secNr == nrSec
           transNr = secTrans(n) - secNr * 1.e6;
           disp (num2str(transNr))
           m = m + 1;
           if nargout > 2
               gather(m) = transNr;
           end
        end
    end
    if m == 0
        disp 'No transects found for the given section';
    end
    if nargout > 2
        varargout{1} = gather';
    end
    return
else
    if nargout > 2
        gather = [];
        m = 0;
        for n = 1 : length(secTrans)
            secNr   = floor(secTrans(n) / 1.e6);
            if secNr == nrSec
               transNr = secTrans(n) - secNr * 1.e6;
               m = m + 1;
               gather(m) = transNr;
            end
        end
        varargout{1} = gather';
    end
end
%% Handle transect lines
% when not called the transect must be written here
if ~called
    fidTransect = fopen('templateTransect.kml','r');
    while ~feof(fidTransect)
        line = fgetl(fidTransect);
        k = findstr(line, 'NRNR');
        if ~isempty(k)
            s = strrep(line,'NRNR',num2str(trans));
        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

%% Handle graphs

fidGraph = fopen('templateGraphHref.kml','r');

png=[storedAt num2str(nrSec) '_' num2str(trans) '.png'];
if nrSec == 4 && trans == 3001
    st = 0;
end
combi = nrSec * 1e6 + trans;
nsecTrans = find(secTrans == combi);

nanTKL = find(~isnan(charts.TKL(nsecTrans,:)));
nanBKL = find(~isnan(charts.BKL(nsecTrans,:)));
nanMKL = find(~isnan(charts.MKL(nsecTrans,:)));

if isempty(nanTKL) && isempty(nanBKL) && isempty(nanMKL) 
    icontype = 'blank';
else
    icontype = 'square';
end

while ~feof(fidGraph)
   line = fgetl(fidGraph);
   k = findstr(line, 'ABCXYZ');
   if ~isempty(k)
       s = strrep(line,'ABCXYZ',png);
   else
       s = line;
   end
   k = findstr(s, 'ICONTYPE');
   if ~isempty(k)
       s = strrep(s,'ICONTYPE',icontype);
   end
   k = findstr(s, 'NNNS');
   if ~isempty(k)
       s = strrep(s,'NNNS',num2str(nrSec));
   end
   k = findstr(s, 'NNNT');
   if ~isempty(k)
       s = strrep(s,'NNNT',num2str(trans));
   end
   k = findstr(s, 'Lonx');
   if ~isempty(k)
       s = strrep(s,'Lonx',num2str(LonLat.Lon(nsecTrans)));
   end
   k = findstr(s, 'Laty');
   if ~isempty(k)
       s = strrep(s,'Laty',num2str(LonLat.Lat(nsecTrans)));
   end
   s = [strrep(s,'\','\\') ' \n'];
   fprintf(fid,s);
end
fclose(fidGraph);

clear filevariables{:}
if ~called
    kmlClose(fid);
end

