function [cnt] = writePETScBinFile(outfilename,A)
% function [cnt] = writePETScBinFile(outfilename,A)
% Write matrix Petsc's binary format

% all data is big-endian

% 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

% VECTOR: 
%   int    VEC_FILE_COOKIE
%   int    number of rows
%   PetscScalar *values of all nonzeros

MAT_FILE_COOKIE = 1211216;
VEC_FILE_COOKIE = 1211214;
cnt = 0;

fid = fopen(outfilename,'wb', 'ieee-be');

if (size(A, 2) == 1) 
    % a is a vector
    disp('Saving vector...');
    cnt = fwrite(fid, VEC_FILE_COOKIE, 'int32');
    cnt = cnt + fwrite(fid, size(A,1), 'int32');
    cnt = cnt + fwrite(fid, A, 'double');
else 
    % a is a matrix
    disp('Saving matrix...');
    [m,n] = size(A);
    % m2 = 1200;
    %m2 = 3;
    [rows,cols,vals] = find(A);
    [rows, ind] = sort(rows);
    cols = cols(ind);
    vals = vals(ind);
    nnzA = nnz(A);
    rowsnnz = zeros(m,1);
    for k = 1:m
        rowsnnz(k) = length(find(rows == k));
    end
    cols = cols - 1;

    cnt = fwrite(fid,MAT_FILE_COOKIE, 'int32');
    cnt = cnt + fwrite(fid,m, 'int32');
    cnt = cnt + fwrite(fid,n, 'int32');
    cnt = cnt + fwrite(fid,nnzA, 'int32');
    cnt = cnt + fwrite(fid,rowsnnz, 'int32');
    cnt = cnt + fwrite(fid,cols, 'int32');
    cnt = cnt + fwrite(fid,vals, 'double');
end

fclose(fid);

return
