function var_list = load_nc(nc_file, prefix)
% load_nc -- Load NetCDF variables and global attributes.
%
% load_nc('nc_file') loads all variables and global
%   attributes of 'nc_file' into the Matlab workspace of the 
%   caller of this routine. The names of the loaded variables
%   and attributes are listed on the screen, and returned or
%   assigned to "ans". If any variable has a "missing_value"
%   attribute then those values in the corresponding variable
%   are set to NaN.
%
% load_nc('nc_file', 'prefix') loads all variables and global
%   attributes, but prefixes the name of each with "prefix".
%   This is useful if you load radar and lidar data at the same
%   time as both have variables called time, range etc.
%
%   To use this function you need the NetCDF Toolbox for
%   Matlab-5. This can be downloaded free from:
%     http://crusty.er.usgs.gov/~cdenham/MexCDF/nc4ml5.html
 
if nargin < 1, help(mfilename), return, end

if nargin < 2, prefix=''; end

result = [];
if nargout > 0, var_list = result; end

f = netcdf(nc_file, 'nowrite');
if isempty(f), return, end
disp([name(f) ':']);

% Write variables to caller's workspace
names = ncnames(var(f));
for i = 1:length(names)
   missing_value = f{names{i}}.missing_value(:);
   if ~isempty(missing_value)
      var = f{names{i}}(:);
      var(find(var == missing_value)) = NaN;
      assignin('caller', [prefix names{i}], var);
      clear var      
   else
      assignin('caller', [prefix names{i}], f{names{i}}(:))
   end
   the_size = size(f{names{i}});
   long_name = num2str(f{names{i}}.long_name(:));
   if ~isempty(long_name)
      long_name = [' (' long_name ')'];
   end
   if the_size(1) == 1 & the_size(2) == 1
      disp([prefix names{i} ': ' num2str(f{names{i}}(1)) ' ' num2str(f{names{i}}.units(:)) long_name]);
   else
      disp([prefix names{i} ': [' num2str(the_size(1)) 'x' num2str(the_size(2)) '] ' num2str(f{names{i}}.units(:)) long_name]); 
   end
end

% Write global attributes to caller's workspace
names = ncnames(att(f));
for i = 1:length(names)
   eval(['attribute = f.' names{i} '(:);']);
   assignin('caller', [prefix names{i}], attribute);
   disp([prefix names{i} ': ' num2str(attribute)]);
end

result = names;

close(f)

if nargout > 0
   var_list = result;
else
   ncans(result)
end


