function [ok,R] = combineAscGrids(varargin)
%combineAscGrids  combine ArcGis ASCII grid files to a new asc file
%
%   The function combines ArcGIS ASCII grids to one grid file with
%   conditions
%       1 - the grid is the same
%       2 - when there are values in the same cel the mean is used
%       3 - when there are novalue values they are ignored unless all
%           values are nonvalue
%
%   Syntax:
%   ok = combineAscGrids(varargin)
%
%   Input:
%   varargin = input of asc names to be combined, there are two options 
%                 1 - one asc file name is given, various directory names
%                 2 - the asc file names are given, possibly with a path; no
%                     directory needed
%                     Option 1
%                         'asc'       the filename of the asc files to be used
%                         'directory' a cell with directory names
%                     Option 2
%                         'asc'       a cell with asc file names and its
%                                     paths
%              'name'     the name of the resulting file.
%                         Default there are two options:
%                         1 - when option 1 is used the 'asc' file name is
%                             used
%                         2 - when not given at input, the name result.asc
%                             is used
%              'store_at' store the resulting file in this directory.
%                         Default = current folder. 
%             
%
%   Output:
%   ok = "ok" not any problem
%        "..." any other message, something went wrong
%   R  = the struct with the resulting grid values
%
%   Example
%
%   See also 

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2011 Deltares
%       Lou Verhage
%
%       lou.verhage@deltares.nl	
%
%       Deltares
%       P.O. Box 177
%       2600MH Delft
%       Tel: +31 (0)88 335  8273
%       
%       Visiting adress:
%       Rotterdamseweg 185
%       2629 HD Delft
%       Tel: +31 (0)88 335  8276
%
%   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: 06 Jan 2011
% Created with Matlab version: 7.6.0.324 (R2008a)

% $Id$
% $Date$
% $Author$
% $Revision$
% $HeadURL$
% $Keywords: $

%% Initialize

ok = 'yes';
R  = [];
if nargin > 0
    OPT.asc       = '';
    OPT.directory = '';
    OPT.name      = '';
    OPT.store_at  = '';
    OPT           = setproperty(OPT,varargin{:});
else
    ok = 'not any input argument';
    return
end

% %     for n = 1 : nargin
% %         v      = varargin(n);
% %         v      = v{1};
% %         fileName{n} = v{1};
% %         cl{n}       = v{2};
% %     end

if iscell(OPT.asc) && isempty(OPT.directory)
    %just the asc filenames are given
    for nrSet = 1 : length(OPT.asc)
        fileName{nrSet} = OPT.asc{nrSet};
    end
elseif iscell(OPT.directory) && ~iscell(OPT.asc) && ~isempty(OPT.asc)
    %just one asc filename and a set of directories
    for nrSet = 1 : length(OPT.directory)
        fileName{nrSet} = fullfile(OPT.directory{nrSet},OPT.asc);
    end
else
    ok = 'the combination of keys ASC and DIRECTORY and their values is not correct';
    return
end
if nrSet < 1 
    ok = 'At least 2 files are needed';
    return
end
    
if isempty(OPT.name)
    if iscell(OPT.directory)
        resultFile = fullfile(OPT.store_at,OPT.asc);
    else
        resultFile = fullfile(OPT.store_at,'result.asc');
    end
else
    resultFile = fullfile(OPT.store_at,OPT.name);
end
        
%% preparation

%read the asc files
for nrSet = 1 : length(fileName)
   D{nrSet} = ArcGisRead(fileName(nrSet),'export',0,'mat',0,'plot',0); 
end

%check the asc files, they must have an identical grid
for nrSet = 2 : length(fileName)
   if ~(D{nrSet}.ncols     == D{1}.ncols || ...
        D{nrSet}.nrows     == D{1}.nrows || ... 
        D{nrSet}.xllcorner == D{1}.xllcorner || ...
        D{nrSet}.yllcorner == D{1}.yllcorner ||...
        D{nrSet}.cellsize  ==  D{1}.cellsize)
      ok = 'The asc files do not have identical grids';
      return
   end
end
%% computation

%combine all asc files to one new grid
R = D{1};
S = ones(D{1}.nrows,D{1}.ncols,1); %set the sum of values to 1
S(isnan(R.val)) = 0; % when NaN no value in a cell
X = D{1}.(D{1}.varname);
for nrSet = 2 : length(fileName)
    Y = D{nrSet}.(D{nrSet}.varname);
    [X,S,ok] = summatrices(X,Y,S);
    if ~(ok == 'yes')
        R = [];
        return
    end
end

R.(R.varname) = X ./ S;

writestruct2asc (R,resultFile);


