function O = PetscOpenFile(filename,rw)
%
%   O = PetscOpenFile(filename,rw) - opens the binary file (generated by PETSc for reading) or for writing
%
%  This provides an object-oriented interface to the MATLAB routines fopen(), fread(), and fclose()
%  allowing PETSc  MATLAB utilities like PetscBinaryRead.m to work cleanly with either binary
%  files or sockets
%
if nargin == 1
  rw = 'r';
end
S = struct('fd', fopen(filename,rw,'ieee-be'));
O = class(S,'PetscOpenFile');
if S.fd == -1
  if rw == 'r'
    error(strcat('File ',filename,' opening for read does not exist'))
  else
    dir = fileparts(filename)
    if and(not(isempty(dir)),not(isfolder(dir)))
      error(strcat('Directory ',dir,' does not exist to write file ',filename,'into'))
    else
      error(strcat('Unable to create file ',filename))
    end
  end
end

