function varargout = satio_opengrid(varargin)
% function varargout = satio_opengrid(varargin)
%
% i/o function for loading grids in the SA toolbox
%
% Usage: 
% grid = satlib_opengrid('filename', filename);
% or 
% grid = satlib_opengrid;
%
% See also: satio_list
%
% Dr. A. I. Hanna (2007)
error(nargchk(0,inf,nargin));
grid_dir = ['Staged', filesep, 'Data', filesep, 'Grids', filesep];
grid = [];
filename = '';
if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(['Arguments to ', mfilename, ' must come param/value in pairs.'])
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'filename'
            filename = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to ', mfilename, '.  Name was ' varargin{i}])
    end
end
if isempty(filename)
    [filename, pathname] = uigetfile('*.mat', 'Open Grid...', grid_dir);
    if isequal(filename,0) || isequal(pathname,0)
        disp('User pressed cancel');
        varargout{1} = [];
        varargout{2} = filename;
        return;
    end
    filename = [pathname, filesep, filename];
end
grid = load(filename);
if ~isfield(grid, 'base_grid')
    fprintf('i/o error: invalid grid file, exiting\n');
    grid = [];
    return;
end
varargout{1} = grid;
varargout{2} = filename;
return