% function to read in sun binary format data from the mit model.
% data format is REAL *4 binary dumps of the arrays.
%
% there are several possible data formats:
% 1. the matrix is packed with the rows corresponding to the x-index,
%    and the column to the y-index, the first NY rows are from the top
%    (or bottom) layer of the model, and so on (this is the old style)
% 2. in the default new style, the matrix is packed with the rows
%    corresponding z-index, and the columns to the x-index with the
%    first NX columns corresponding to the southernmost latitude, etc.
%
% dummy = readmodel(pname, fname, pmask, flg)
%
% output variables
%       dummy     dummy fortran header and tail
%
% input variables
%       pname     path name
%       fname     file name
%       pmask     if it exists, it is the bathynmetry mask
%                 1 for water and nan for land
%       flg       if it is set (non zero), read old-style sun binary files
%
% required global variables
%   DATA     data matrix
%   NX       zonal model dimension
%   NY       meridional model dimension
%   NZ       vertical model dimension
%
% see savemodel getxy getxz getyy

% modifications
%
% menemenlis 10/16/96
%   changed to read new-style sun binary format
%   new: real*4 (k,i,j) with k=1 surface
%   old: real*4 (i,j,k) with k=1 bottom

function dummy = readmodel(pname, fname, pmask, flg)

global NX NY NZ DATA

if nargin < 2, fname=pname; pname=''; end
if ~isstr(fname)
  pmask=fname; fname=pname; pname='';
  if nargin < 3, flg=0; end
end
if nargin < 4, flg=0; end

[fid, message] = fopen([pname fname]);  % open file
if fid < 2, error(message); end
disp('reading ...');
disp([pname fname]);

% Currently data files have 2 extra entries, at the beginning and end, for some
% obscure reason. So Read over the 1st floating point value before reading the
% array.

[dummy,cnt] = fread(fid,1,'float32'); % read fortran header

% read in data

if flg                               % old style
  DATA=zeros(NX,NY*NZ);
  [DATA,cnt] = fread(fid,[NX,NY*NZ],'float32');

else                                 % new style
  DATA=zeros(NZ,NX*NY);
  [DATA,cnt] = fread(fid,[NZ,NX*NY],'float32');
end

if cnt == NX*NY*NZ
  disp('... done')
else
  error('problem reading file: file length is not NX,NY*NZ')
end, fclose(fid);

if nargin < 4           % zeros correspond to bathymetry
  ix = find(~DATA);
  DATA(ix) = nan*ones(size(ix));
else                    % use pmask for bathymetry
  DATA = DATA .* pmask;
end
