% f77read(filename,shape,options) returns an array of shape "shape"
%  filename - is a string containing the name of the file to be read
%  shape    - is a vector containing the dimensions of the data
%             eg. shape=[nx ny nz]
%  options  - (optional) specifies the data-type or the binary format
%
%  Default data-type and binary format are 'real*8' and 'native'.
%
% Other data types can be one of:
%       'real*4' - floating point, 32 bits.
%       'real*8' - floating point, 64 bits.
%
% Other binary formats can be one of:
%    'native'      or 'n' - local machine format - the default
%    'ieee-le'     or 'l' - IEEE floating point with little-endian
%                           byte ordering
%    'ieee-be'     or 'b' - IEEE floating point with big-endian
%                           byte ordering
%    'cray'        or 'c' - Cray floating point with big-endian
%                           byte ordering
%    'ieee-le.l64' or 'a' - IEEE floating point with little-endian
%                           byte ordering and 64 bit long data type
%    'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
%                           ordering and 64 bit long data type.
%
%
% eg.  Read a real*8 dataset of size 160 x 10 x 16
%        temp=f77read('T.bin',[160 10 16]);
%
% eg.  Read a real*4 dataset of size 120 x 45 in Little endian format
%        temp=f77read('T.bin',[120 45],'real*4','l');
%
% G. Gebbie, MIT-WHOI, 2000.

function [arr] = read3d(file,N,varargin)

% Defaults
rtype='real*8'; % This is the default type of data
ieee='n'; % This is the default binary representation

% Set arr to null incase we do an early "return"
arr=0;

% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
 if deblank(args(1,:)) == 'real*4'
  rtype='real*4';
 elseif deblank(args(1,:)) == 'real*8'
  rtype='real*8';
 elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
  ieee='n';
 elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
  ieee='l';
 elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
  ieee='b';
 elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
  ieee='c';
 elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
  ieee='a';
 elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
  ieee='s';
 else
  sprintf(['Optional argument ' args(1,:) ' is unknown'])
  return
 end
 args=args(2:end,:);
end

fid=fopen(file,'r',ieee);
% read the initial 4 bytes used in f77_unformatted

% My forcing fields do not have 4 unused initial bytes.
%q=fread(fid,1,'uint32');

% read the data
arr=fread(fid,prod(N),rtype);
% reshape the data
arr=reshape(arr,N);
% close the file
st=fclose(fid);
