% rdslice(filename,[nx ny ...],k) returns an array of shape [nx,ny,...]
% read from a direct access binary file (float or double precisision) named
% by the string 'filename'. The file may contain multi-dimensional
% data. Note that cumsum([nx ny ...]*k) <= length of file.
%
% eg.   temp=rdslice('t.xyt',[160 120],4);
%
% rdsclice(filename,[nx ny ...],k,type) returns an array of type 'type'.
% where type can be one of 'real*4' or 'real*8'. The default is 'real*8'.
function [arr] = rdslice(file,N,k,varargin)

% Default word-length
WORDLENGTH=8;

if size(varargin,2) == 1
 if varargin{:} == 'real*4'
  WORDLENGTH=4;
 elseif varargin{:} == 'real*8'
  WORDLENGTH=8;
 else
  sprintf('Optional argument: Unknown type?')
  return
 end
elseif size(varargin,2) >= 2
 sprintf('Optional arguments: too many?')
 return
end

if WORDLENGTH == 4
 rtype='real*4';
elseif WORDLENGTH == 8
 rtype='real*8';
else
 sprintf('Internal error: WORDLENGTH has illegal value')
 return
end

nnn=prod(N);

[fid mess]=fopen(file,'r','n');
if fid == -1
 sprintf('Error while opening file:\n%s',mess)
 arr=0;
 return
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
 mess=ferror(fid);
 sprintf('There was an error while positioning the file pointer:\n%s',mess)
 arr=0;
 return
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
 sprintf('Not enough data was available to be read: off EOF?')
 arr=0;
 return
end
st=fclose(fid);
arr=reshape(arr,N);
