function ddb_ModelMakerToolbox_sfincs_mask(varargin)
%ddb_DrawingToolbox  One line description goes here.
%
%   More detailed description goes here.
%
%   Syntax:
%   ddb_DrawingToolbox(varargin)
%
%   Input:
%   varargin =
%
%
%
%
%   Example
%   ddb_DrawingToolbox
%
%   See also

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2017 Deltares
%       Maarten van Ormondt
%
%       Maarten.vanOrmondt@deltares.nl
%
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%   This library is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 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 General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this library.  If not, see <http://www.gnu.org/licenses/>.
%   --------------------------------------------------------------------

% This tool is part of <a href="http://www.OpenEarth.eu">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: 01 Dec 2011
% Created with Matlab version: 7.11.0.584 (R2010b)

% $Id: ddb_drawingToolbox_export.m 12926 2016-10-15 07:47:58Z ormondt $
% $Date: 2016-10-15 09:47:58 +0200 (Sat, 15 Oct 2016) $
% $Author: ormondt $
% $Revision: 12926 $
% $HeadURL: https://svn.oss.deltares.nl/repos/openearthtools/trunk/matlab/applications/DelftDashBoard/toolboxes/drawing/ddb_drawingToolbox_export.m $
% $Keywords: $

%%
if isempty(varargin)
    % New tab selected
    ddb_zoomOff;
    ddb_refreshScreen;
    ddb_plotModelMaker('deactivate');
    ddb_plotsfincs('update','active',1,'visible',1);
    
    bring_polygons_to_front;

%     h=findobj(gca,'Tag','sfincsincludepolygon');
%     if ~isempty(h)
%         set(h,'Visible','on');
%         uistack(h,'top');
%     end
%     h=findobj(gca,'Tag','sfincsexcludepolygon');
%     if ~isempty(h)
%         set(h,'Visible','on');
%         uistack(h,'top');
%     end
%     h=findobj(gca,'Tag','sfincswaterlevelboundarypolygon');
%     if ~isempty(h)
%         set(h,'Visible','on');
%         uistack(h,'top');
%     end
%     h=findobj(gca,'Tag','sfincsoutflowboundarypolygon');
%     if ~isempty(h)
%         set(h,'Visible','on');
%         uistack(h,'top');
%     end
    
    handles=getHandles;
    ddb_sfincs_plot_mask(handles, 'update','domain',ad,'visible',1);
    
else
    %Options selected
    opt=lower(varargin{1});
    switch opt
        case{'selectincludepolygon'}
            selectIncludePolygon;
        case{'drawincludepolygon'}
            drawIncludePolygon;
        case{'deleteincludepolygon'}
            deleteIncludePolygon;
        case{'loadincludepolygon'}
            loadIncludePolygon;
        case{'saveincludepolygon'}
            saveIncludePolygon;

        case{'selectexcludepolygon'}
            selectExcludePolygon;
        case{'drawexcludepolygon'}
            drawExcludePolygon;
        case{'deleteexcludepolygon'}
            deleteExcludePolygon;
        case{'loadexcludepolygon'}
            loadExcludePolygon;
        case{'saveexcludepolygon'}
            saveExcludePolygon;

%         case{'selectclosedboundarypolygon'}
%             selectClosedBoundaryPolygon;
%         case{'drawclosedboundarypolygon'}
%             drawClosedBoundaryPolygon;
%         case{'deleteclosedboundarypolygon'}
%             deleteClosedBoundaryPolygon;
%         case{'loadclosedboundarypolygon'}
%             loadClosedBoundaryPolygon;
%         case{'saveclosedboundarypolygon'}
%             saveClosedBoundaryPolygon;

        case{'selectoutflowboundarypolygon'}
            selectOutflowBoundaryPolygon;
        case{'drawoutflowboundarypolygon'}
            drawOutflowBoundaryPolygon;
        case{'deleteoutflowboundarypolygon'}
            deleteOutflowBoundaryPolygon;
        case{'loadoutflowboundarypolygon'}
            loadOutflowBoundaryPolygon;
        case{'saveoutflowboundarypolygon'}
            saveOutflowBoundaryPolygon;

        case{'selectwaterlevelboundarypolygon'}
            selectWaterlevelBoundaryPolygon;
        case{'drawwaterlevelboundarypolygon'}
            drawWaterlevelBoundaryPolygon;
        case{'deletewaterlevelboundarypolygon'}
            deleteWaterlevelBoundaryPolygon;
        case{'loadwaterlevelboundarypolygon'}
            loadWaterlevelBoundaryPolygon;
        case{'savewaterlevelboundarypolygon'}
            saveWaterlevelBoundaryPolygon;            
            
%         case{'useoptionactivegrid'}
%             useOptionActiveGrid;
%         case{'removeoptionactivegrid'}
%             removeOptionActiveGrid;            
%         case{'upoptionactivegrid'}
%             upOptionActiveGrid;
%         case{'downoptionactivegrid'}
%             downOptionActiveGrid;            
            
%         case{'useoptionboundarycells'}
%             useOptionBoundaryCells;
%         case{'removeoptionboundarycells'}
%             removeOptionBoundaryCells;            
%         case{'upoptionboundarycells'}
%             upOptionBoundaryCells;
%         case{'downoptionboundarycells'}
%             downOptionBoundaryCells;        
            
        case{'generatemask'}
            generateMask;
        case{'bathymetry_changed'}
            bathymetry_changed;
    end
end




%%
function selectIncludePolygon
handles=getHandles;
setHandles(handles);

%%
function drawIncludePolygon

handles=getHandles;
ddb_zoomOff;

handles.toolbox.modelmaker.sfincs.mask.includepolygonhandle=gui_polyline('draw','tag','sfincsincludepolygon','color',[1 0.64 0],'marker','o', ...
    'createcallback',@createIncludePolygon,'changecallback',@changeIncludePolygon, ...
    'closed',1);

setHandles(handles);

%%
function createIncludePolygon(h,x,y)
handles=getHandles;
handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons=handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons+1;
iac=handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).handle=h;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.includepolygonnames{iac}=['polygon_' num2str(iac,'%0.3i')];
handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function deleteIncludePolygon

handles=getHandles;

iac=handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon;
if handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons>0
    h=handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).handle;
    if ~isempty(h)
        try
            delete(h);
        end
    end
end

handles.toolbox.modelmaker.sfincs.mask.includepolygon=removeFromStruc(handles.toolbox.modelmaker.sfincs.mask.includepolygon,iac);
handles.toolbox.modelmaker.sfincs.mask.includepolygonnames=removeFromCellArray(handles.toolbox.modelmaker.sfincs.mask.includepolygonnames,iac);

handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons=max(handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons-1,0);
handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon=min(handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon,handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons);

if handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons==0
    handles.toolbox.modelmaker.sfincs.mask.includepolygon=[];
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).x=[];
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).y=[];
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).length=0;
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).handle=[];
    handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons=0;
    handles.toolbox.modelmaker.sfincs.mask.includepolygonnames={''};
    handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon=1;
end

setHandles(handles);

%%
function changeIncludePolygon(h,x,y,varargin)
handles=getHandles;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons
    if handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).handle==h
        iac=ip;
        break
    end
end

handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function loadIncludePolygon

handles=getHandles;

% Clear all
handles.toolbox.modelmaker.sfincs.mask.includepolygon=[];
handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).x=[];
handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).y=[];
handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).length=0;
handles.toolbox.modelmaker.sfincs.mask.includepolygon(1).handle=[];
handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons=0;
handles.toolbox.modelmaker.sfincs.mask.includepolygonnames={''};

h=findobj(gca,'Tag','sfincsincludepolygon');
delete(h);

data=tekal('read',handles.toolbox.modelmaker.sfincs.mask.includepolygonfile,'loaddata');
handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons=length(data.Field);
handles.toolbox.modelmaker.sfincs.mask.activeincludepolygon=1;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons
    x=data.Field(ip).Data(:,1);
    y=data.Field(ip).Data(:,2);
    if x(end)~=x(1) || y(end)~=y(1)
        x=[x;x(1)];
        y=[y;y(1)];
    end
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).x=x;
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).y=y;
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).length=length(x);
    handles.toolbox.modelmaker.sfincs.mask.includepolygonnames{ip}=deblank2(data.Field(ip).Name);
    h=gui_polyline('plot','x',x,'y',y,'tag','sfincsincludepolygon','color',[1 0.64 0],'marker','o', ...
        'changecallback',@changeIncludePolygon);
    handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).handle=h;
end

setHandles(handles);

%%
function saveIncludePolygon

handles=getHandles;

cs=handles.screenParameters.coordinateSystem.type;
if strcmpi(cs,'geographic')
    fmt='%12.7f %12.7f\n';
else
    fmt='%11.1f %11.1f\n';
end

fid=fopen(handles.toolbox.modelmaker.sfincs.mask.includepolygonfile,'wt');
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons
    fprintf(fid,'%s\n',handles.toolbox.modelmaker.sfincs.mask.includepolygonnames{ip});
    fprintf(fid,'%i %i\n',[handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).length 2]);
    for ix=1:handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).length
        fprintf(fid,fmt,[handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).x(ix) handles.toolbox.modelmaker.sfincs.mask.includepolygon(ip).y(ix)]);
    end
end
fclose(fid);



%%
function selectExcludePolygon
handles=getHandles;
setHandles(handles);


%%
function drawExcludePolygon

handles=getHandles;
ddb_zoomOff;

handles.toolbox.modelmaker.sfincs.mask.excludepolygonhandle=gui_polyline('draw','tag','sfincsexcludepolygon','color','b','marker','o', ...
    'createcallback',@createExcludePolygon,'changecallback',@changeExcludePolygon, ...
    'closed',1);

setHandles(handles);

%%
function createExcludePolygon(h,x,y)
handles=getHandles;
handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons=handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons+1;
iac=handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).handle=h;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames{iac}=['polygon_' num2str(iac,'%0.3i')];
handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function deleteExcludePolygon

handles=getHandles;

iac=handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon;
if handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons>0
    h=handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).handle;
    if ~isempty(h)
        try
            delete(h);
        end
    end
end

handles.toolbox.modelmaker.sfincs.mask.excludepolygon=removeFromStruc(handles.toolbox.modelmaker.sfincs.mask.excludepolygon,iac);
handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames=removeFromCellArray(handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames,iac);

handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons=max(handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons-1,0);
handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon=min(handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon,handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons);

if handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons==0
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon=[];
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).x=[];
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).y=[];
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).length=0;
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).handle=[];
    handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons=0;
    handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames={''};
    handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon=1;
end

setHandles(handles);

%%
function changeExcludePolygon(h,x,y,varargin)
handles=getHandles;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons
    if handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).handle==h
        iac=ip;
        break
    end
end

handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function loadExcludePolygon

handles=getHandles;

% Clear all
handles.toolbox.modelmaker.sfincs.mask.excludepolygon=[];
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).x=[];
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).y=[];
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).length=0;
handles.toolbox.modelmaker.sfincs.mask.excludepolygon(1).handle=[];
handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons=0;
handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames={''};

h=findobj(gca,'Tag','sfincsexcludepolygon');
delete(h);

data=tekal('read',handles.toolbox.modelmaker.sfincs.mask.excludepolygonfile,'loaddata');
handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons=length(data.Field);
handles.toolbox.modelmaker.sfincs.mask.activeexcludepolygon=1;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons
    x=data.Field(ip).Data(:,1);
    y=data.Field(ip).Data(:,2);
    if x(end)~=x(1) || y(end)~=y(1)
        x=[x;x(1)];
        y=[y;y(1)];
    end
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).x=x;
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).y=y;
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).length=length(x);
    handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames{ip}=deblank2(data.Field(ip).Name);
    h=gui_polyline('plot','x',x,'y',y,'tag','sfincsexcludepolygon','color','b','marker','o', ...
        'changecallback',@changeExcludePolygon);
    handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).handle=h;
end

setHandles(handles);

%%
function saveExcludePolygon

handles=getHandles;

cs=handles.screenParameters.coordinateSystem.type;
if strcmpi(cs,'geographic')
    fmt='%12.7f %12.7f\n';
else
    fmt='%11.1f %11.1f\n';
end

fid=fopen(handles.toolbox.modelmaker.sfincs.mask.excludepolygonfile,'wt');
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons
    fprintf(fid,'%s\n',handles.toolbox.modelmaker.sfincs.mask.excludepolygonnames{ip});
    fprintf(fid,'%i %i\n',[handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).length 2]);
    for ix=1:handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).length
        fprintf(fid,fmt,[handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).x(ix) handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ip).y(ix)]);
    end
end
fclose(fid);


%%
function selectOutflowBoundaryPolygon
handles=getHandles;
setHandles(handles);


%%
function drawOutflowBoundaryPolygon

handles=getHandles;
ddb_zoomOff;

handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonhandle=gui_polyline('draw','tag','sfincsoutflowboundarypolygon','color','c','marker','o', ...
    'createcallback',@createOutflowBoundaryPolygon,'changecallback',@changeOutflowBoundaryPolygon, ...
    'closed',1);

setHandles(handles);

%%
function createOutflowBoundaryPolygon(h,x,y)
handles=getHandles;
handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons=handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons+1;
iac=handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).handle=h;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames{iac}=['polygon_' num2str(iac,'%0.3i')];
handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function deleteOutflowBoundaryPolygon

handles=getHandles;

iac=handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon;
if handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons>0
    h=handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).handle;
    if ~isempty(h)
        try
            delete(h);
        end
    end
end

handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon=removeFromStruc(handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon,iac);
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames=removeFromCellArray(handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames,iac);

handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons=max(handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons-1,0);
handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon=min(handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon,handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons);

if handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons==0
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon=[];
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).x=[];
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).y=[];
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).length=0;
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).handle=[];
    handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons=0;
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames={''};
    handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon=1;
end

setHandles(handles);

%%
function changeOutflowBoundaryPolygon(h,x,y,varargin)
handles=getHandles;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons
    if handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).handle==h
        iac=ip;
        break
    end
end

handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function loadOutflowBoundaryPolygon

handles=getHandles;

% Clear all
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon=[];
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).x=[];
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).y=[];
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).length=0;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(1).handle=[];
handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons=0;
handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames={''};

h=findobj(gca,'Tag','sfincsoutflowboundarypolygon');
delete(h);

data=tekal('read',handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonfile,'loaddata');
handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons=length(data.Field);
handles.toolbox.modelmaker.sfincs.mask.activeoutflowboundarypolygon=1;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons
    x=data.Field(ip).Data(:,1);
    y=data.Field(ip).Data(:,2);
    if x(end)~=x(1) || y(end)~=y(1)
        x=[x;x(1)];
        y=[y;y(1)];
    end
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).x=x;
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).y=y;
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).length=length(x);
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames{ip}=deblank2(data.Field(ip).Name);
    h=gui_polyline('plot','x',x,'y',y,'tag','sfincsoutflowboundarypolygon','color','c','marker','o', ...
        'changecallback',@changeIncludePolygon);
    handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).handle=h;
end

setHandles(handles);

%%
function saveOutflowBoundaryPolygon

handles=getHandles;

cs=handles.screenParameters.coordinateSystem.type;
if strcmpi(cs,'geographic')
    fmt='%12.7f %12.7f\n';
else
    fmt='%11.1f %11.1f\n';
end

fid=fopen(handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonfile,'wt');
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons
    fprintf(fid,'%s\n',handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonnames{ip});
    fprintf(fid,'%i %i\n',[handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).length 2]);
    for ix=1:handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).length
        fprintf(fid,fmt,[handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).x(ix) handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ip).y(ix)]);
    end
end
fclose(fid);

%%
function selectWaterlevelBoundaryPolygon
handles=getHandles;
setHandles(handles);


%%
function drawWaterlevelBoundaryPolygon

handles=getHandles;
ddb_zoomOff;

handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonhandle=gui_polyline('draw','tag','sfincswaterlevelboundarypolygon','color','r','marker','o', ...
    'createcallback',@createWaterlevelBoundaryPolygon,'changecallback',@changeWaterlevelBoundaryPolygon, ...
    'closed',1);

setHandles(handles);

%%
function createWaterlevelBoundaryPolygon(h,x,y)
handles=getHandles;
handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons=handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons+1;
iac=handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).handle=h;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames{iac}=['polygon_' num2str(iac,'%0.3i')];
handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function deleteWaterlevelBoundaryPolygon

handles=getHandles;

iac=handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon;
if handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons>0
    h=handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).handle;
    if ~isempty(h)
        try
            delete(h);
        end
    end
end

handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon=removeFromStruc(handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon,iac);
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames=removeFromCellArray(handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames,iac);

handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons=max(handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons-1,0);
handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon=min(handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon,handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons);

if handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons==0
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon=[];
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).x=[];
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).y=[];
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).length=0;
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).handle=[];
    handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons=0;
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames={''};
    handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon=1;
end

setHandles(handles);

%%
function changeWaterlevelBoundaryPolygon(h,x,y,varargin)
handles=getHandles;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons
    if handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).handle==h
        iac=ip;
        break
    end
end

handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).x=x;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).y=y;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(iac).length=length(x);
handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon=iac;
setHandles(handles);
gui_updateActiveTab;

%%
function loadWaterlevelBoundaryPolygon

handles=getHandles;

% Clear all
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon=[];
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).x=[];
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).y=[];
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).length=0;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(1).handle=[];
handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons=0;
handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames={''};

h=findobj(gca,'Tag','sfincswaterlevelboundarypolygon');
delete(h);

data=tekal('read',handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonfile,'loaddata');
handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons=length(data.Field);
handles.toolbox.modelmaker.sfincs.mask.activewaterlevelboundarypolygon=1;
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons
    x=data.Field(ip).Data(:,1);
    y=data.Field(ip).Data(:,2);
    if x(end)~=x(1) || y(end)~=y(1)
        x=[x;x(1)];
        y=[y;y(1)];
    end
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).x=x;
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).y=y;
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).length=length(x);
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames{ip}=deblank2(data.Field(ip).Name);
    h=gui_polyline('plot','x',x,'y',y,'tag','sfincswaterlevelboundarypolygon','color','r','marker','o', ...
        'changecallback',@changeIncludePolygon);
    handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).handle=h;
end

setHandles(handles);

%%
function saveWaterlevelBoundaryPolygon

handles=getHandles;

cs=handles.screenParameters.coordinateSystem.type;
if strcmpi(cs,'geographic')
    fmt='%12.7f %12.7f\n';
else
    fmt='%11.1f %11.1f\n';
end

fid=fopen(handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonfile,'wt');
for ip=1:handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons
    fprintf(fid,'%s\n',handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonnames{ip});
    fprintf(fid,'%i %i\n',[handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).length 2]);
    for ix=1:handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).length
        fprintf(fid,fmt,[handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).x(ix) handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ip).y(ix)]);
    end
end
fclose(fid);


%%
function generateMask

handles=getHandles;

id=ad;

if isempty(handles.model.sfincs.domain(id).gridx)
    ddb_giveWarning('text','Please first generate a SFINCS grid in the QuickMode tab !');
    return
end

% Check if gridz is empty or bathymetry settings have changed
% If so, generate bathymetry
if isempty(handles.model.sfincs.domain(id).gridz) || handles.toolbox.modelmaker.sfincs.bathymetry_changed==1
    
    if handles.toolbox.modelmaker.sfincs.bathymetry.nrSelectedDatasets==0
        ddb_giveWarning('text','Please first select one or more bathymetry datasets!');
        return
    end
    
    for ii=1:handles.toolbox.modelmaker.sfincs.bathymetry.nrSelectedDatasets
        nr=handles.toolbox.modelmaker.sfincs.bathymetry.selectedDatasets(ii).number;
        datasets(ii).name=handles.bathymetry.datasets{nr};
        datasets(ii).zmin=handles.toolbox.modelmaker.sfincs.bathymetry.selectedDatasets(ii).zMin;
        datasets(ii).zmax=handles.toolbox.modelmaker.sfincs.bathymetry.selectedDatasets(ii).zMax;
        datasets(ii).verticaloffset=handles.toolbox.modelmaker.sfincs.bathymetry.selectedDatasets(ii).verticalLevel;
    end
    handles=ddb_ModelMakerToolbox_sfincs_generateBathymetry(handles,ad,datasets,'modeloffset',handles.toolbox.modelmaker.bathymetry.verticalDatum,'check',0);        
end

save_roughness=0;
% In case of no subgrid, and the roughness map has changed and the number
% of roughness datasets is greater than 0
if handles.model.sfincs.domain(id).use_subgrid==0 && handles.toolbox.modelmaker.sfincs.roughness.nrSelectedDatasets>0 && handles.toolbox.modelmaker.sfincs.roughness_changed==1
    datasets=[];
    for ii=1:handles.toolbox.modelmaker.sfincs.roughness.nrSelectedDatasets
        nr=handles.toolbox.modelmaker.sfincs.roughness.selectedDatasets(ii).number;
        datasets(ii).name=handles.bathymetry.datasets{nr};
    end
    handles=ddb_ModelMakerToolbox_sfincs_generateBathymetry(handles,id,datasets,'check',0,'roughness',1);
    handles.model.sfincs.domain(id).roughness_type='file';
    handles.model.sfincs.domain(id).input.manningfile='sfincs.rgh';
    save_roughness=1;
end

% Now make the mask

zlev = [handles.toolbox.modelmaker.sfincs.zmin handles.toolbox.modelmaker.sfincs.zmax];

xy_in=[];
xy_ex=[];
xy_bnd_wl=[];
xy_bnd_out=[];

for ii=1:handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons
    xy_in(ii).x    = handles.toolbox.modelmaker.sfincs.mask.includepolygon(ii).x;
    xy_in(ii).y    = handles.toolbox.modelmaker.sfincs.mask.includepolygon(ii).y;
    % Using constant zmin and zmax for now
    xy_in(ii).zmin = handles.toolbox.modelmaker.sfincs.mask.includepolygon_zmin;
    xy_in(ii).zmax = handles.toolbox.modelmaker.sfincs.mask.includepolygon_zmax;
end

for ii=1:handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons
    xy_ex(ii).x    = handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ii).x;
    xy_ex(ii).y    = handles.toolbox.modelmaker.sfincs.mask.excludepolygon(ii).y;
    % Using constant zmin and zmax for now
    xy_ex(ii).zmin = handles.toolbox.modelmaker.sfincs.mask.excludepolygon_zmin;
    xy_ex(ii).zmax = handles.toolbox.modelmaker.sfincs.mask.excludepolygon_zmax;
end

for ii=1:handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons
    xy_bnd_wl(ii).x    = handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ii).x;
    xy_bnd_wl(ii).y    = handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon(ii).y;
    % Using constant zmin and zmax for now
    xy_bnd_wl(ii).zmin = handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon_zmin;
    xy_bnd_wl(ii).zmax = handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon_zmax;
end

for ii=1:handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons
    xy_bnd_out(ii).x    = handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ii).x;
    xy_bnd_out(ii).y    = handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon(ii).y;
    % Using constant zmin and zmax for now
    xy_bnd_out(ii).zmin = handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon_zmin;
    xy_bnd_out(ii).zmax = handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon_zmax;
end

msk=sfincs_make_mask(handles.model.sfincs.domain(ad).gridx,handles.model.sfincs.domain(ad).gridy,handles.model.sfincs.domain(ad).gridz,zlev,'includepolygon',xy_in,'excludepolygon',xy_ex,'waterlevelboundarypolygon',xy_bnd_wl,'outflowboundarypolygon',xy_bnd_out);

handles.model.sfincs.domain(id).mask=msk;

handles = ddb_sfincs_plot_mask(handles, 'plot');
bring_polygons_to_front;

% And save the files
handles.model.sfincs.domain(id).input.indexfile = 'sfincs.ind';
handles.model.sfincs.domain(id).input.depfile   = 'sfincs.dep';
handles.model.sfincs.domain(id).input.mskfile   = 'sfincs.msk';

indexfile=handles.model.sfincs.domain(id).input.indexfile;
bindepfile=handles.model.sfincs.domain(id).input.depfile;
binmskfile=handles.model.sfincs.domain(id).input.mskfile;

if strcmpi(handles.model.sfincs.domain(id).input.inputformat,'bin')
    if handles.model.sfincs.domain(ad).use_subgrid==1
        bindepfile=[];
    end
    sfincs_write_binary_inputs(handles.model.sfincs.domain(id).gridz,msk,indexfile,bindepfile,binmskfile);

    % Save roughness file
    if save_roughness
        sfincs_write_binary_roughness(handles.model.sfincs.domain(id).gridz,msk,handles.model.sfincs.domain(id).input.manningfile);
    end

else
    sfincs_write_ascii_inputs(handles.model.sfincs.domain(id).gridz,msk,bindepfile,binmskfile);
end

handles.toolbox.modelmaker.sfincs.bathymetry_changed = 0;
handles.toolbox.modelmaker.sfincs.roughness_changed = 0;


% Now save polygon files
if handles.toolbox.modelmaker.sfincs.mask.nrincludepolygons>0
    save_polygon(handles.toolbox.modelmaker.sfincs.mask.includepolygon,handles.toolbox.modelmaker.sfincs.mask.includepolygonfile);
end
if handles.toolbox.modelmaker.sfincs.mask.nrexcludepolygons>0
    save_polygon(handles.toolbox.modelmaker.sfincs.mask.excludepolygon,handles.toolbox.modelmaker.sfincs.mask.excludepolygonfile);
end
if handles.toolbox.modelmaker.sfincs.mask.nrwaterlevelboundarypolygons>0
    save_polygon(handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygon,handles.toolbox.modelmaker.sfincs.mask.waterlevelboundarypolygonfile);
end
if handles.toolbox.modelmaker.sfincs.mask.nroutflowboundarypolygons>0
    save_polygon(handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygon,handles.toolbox.modelmaker.sfincs.mask.outflowboundarypolygonfile);
end

setHandles(handles);

%%
function bring_polygons_to_front

h=findobj(gca,'Tag','sfincsincludepolygon');
if ~isempty(h)
    set(h,'Visible','on');
    uistack(h,'top');
end
h=findobj(gca,'Tag','sfincsexcludepolygon');
if ~isempty(h)
    set(h,'Visible','on');
    uistack(h,'top');
end
h=findobj(gca,'Tag','sfincswaterlevelboundarypolygon');
if ~isempty(h)
    set(h,'Visible','on');
    uistack(h,'top');
end
h=findobj(gca,'Tag','sfincsoutflowboundarypolygon');
if ~isempty(h)
    set(h,'Visible','on');
    uistack(h,'top');
end

%%
function save_polygon(p,file_name)

handles=getHandles;

cs=handles.screenParameters.coordinateSystem.type;
if strcmpi(cs,'geographic')
    fmt='%12.7f %12.7f\n';
else
    fmt='%11.1f %11.1f\n';
end

fid=fopen(file_name,'wt');
for ip=1:length(p)
    fprintf(fid,'%s\n',['BL' num2str(ip,'%0.4i')]);
    fprintf(fid,'%i %i\n',[p(ip).length 2]);
    for ix=1:p(ip).length
        fprintf(fid,fmt,[p(ip).x(ix) p(ip).y(ix)]);
    end
end
fclose(fid);
