function [var, data_lon, data_lat] = readmat ( filename, variable, depth );
% READMAT:  reads in matlab *.m file, retrieves variable and locations.
%
% USAGE:  [var, lat, lon] = readmat ( matlab_filename, depth, variable_name )
% 
% Input:
%   matlab_filename:  String value.  File must be in matlab format.
%   variable_name:  String containing the variable name.
%   depth:  Float value, depth at which the variable is to be evaluated.
%
% Output:
%   var:  Contains data from 'variable_name' at depth 'depth'.
%   lat, lon:  Locations of datums.
%
% In case of an error, var will be set to [].
%
% John Evans, 12-15-95.
% joevans@usgs.gov
%

if ( nargin < 3 )
  help readmat;
  var = [];
  return;
end

eval ( sprintf ('load %s', filename) );

if ( ~exist('lat') | ~exist('lon') | ~exist(variable) )
  fprintf (1, 'readmat:  Necessary varibles do not exist in %s.\n', filename );
  var = [];
  return;
end



% Find out index of closest depth, from z variable.
dist = abs ( z - depth );
z_depth_ind = find ( min(dist) == dist );


% retrieve the variable at the given depth
command_str = sprintf ( 'var = %s(z_depth_ind,:);', variable );
eval ( command_str );

% if there were any nans, set them to Infs instead.
ifind = find(isnan(var));
var(ifind) = Inf * ones(size(ifind));


data_lon = lon;
data_lat = lat;

return;
