% PGMWRITE Writes an image into a binary PGM (Portable GrayMap) file.
%
%          PGMREAD('filename.pgm',data) takes the image as a 2D array of
%          values, in the orientation suitable for calls to IMAGE and IMAGESC,
%          and writes it into the named file.
%          Each value corresponds to the intensity of one pixel.


function [] = pgmwrite(name, data)

[fd,msg] = fopen(name,'w');

if (fd < 0)
  fprintf(2,'pgmwrite: ERROR in fopen\n -- %s\n',msg);
  pnm=[];
  return;
end

count = fwrite(fd, ['P5', 10], 'char');
if ~(count == 3)
  fprintf(2,'pgmwrite: ERROR writing magic number\n -- %s\n',msg);
  return;
end

hw = size(data);

user = getenv('USER');
if (user == [])
	fprintf(fd, '# CREATOR: Matlab (pgmwrite.m) on %s\n', date);
else
	fprintf(fd, '# CREATOR: Matlab (pgmwrite.m) for %s on %s\n',user,date);
end

fprintf(fd, '%d %d\n', hw(2), hw(1));
fprintf(fd, '255\n');

count = fwrite(fd,data','uchar');
if ~(count == (hw(1)*hw(2)))
  fprintf(2,'pgmwrite: ERROR writing data\n -- %s\n',msg);
  return;
end
