function [cookie, m, n, nnzA, rowsnnz, cols, vals, A] = readPETScMatBinFile(infilename)
% function [cookie, m, n, nnzA, rowsnnz, cols, vals, A] = readPETScMatBinFile(infilename)
% read Petsc Binary format matrix (no support for imaginary numbers)

% MATRIX
%   int    MAT_FILE_COOKIE
%   int    number of rows
%   int    number of columns
%   int    total number of nonzeros
%   int    *number nonzeros in each row
%   int    *column indices of all nonzeros (starting index is zero)
%   PetscScalar *values of all nonzeros


MAT_FILE_COOKIE = 1211216;

fid = fopen(infilename,'r', 'ieee-be');

cookie = fread(fid, 1, 'int32');
if (cookie ~= MAT_FILE_COOKIE)
    error('Not a petsc matrix file.');
elseif (isempty(cookie))
    error('Empty file.');
end

m = fread(fid, 1, 'int32');
n = fread(fid, 1, 'int32');
nnzA = fread(fid, 1, 'int32');
rowsnnz = fread(fid, m, 'int32');
cols = fread(fid, nnzA, 'int32');
vals = fread(fid, nnzA, 'double');

fclose(fid);

ci = 1; 
rowInds = zeros(nnzA, 1);
h = waitbar(0, 'Constructing row indices');
for row = 1:m
    waitbar(row/m, h);
    if (rowsnnz(row) == 0), continue, end % no data in this row
    rowInds(ci:ci+rowsnnz(row)-1) = row*ones(rowsnnz(row), 1);
    ci = ci+rowsnnz(row); 
end
close(h);
A = sparse(rowInds, cols+1, vals); 

return
