% Usage: count=pgmwrite(image,outputFilename);
%
% linearly maps the values in the given matrix to [0 255], quantizes
% to integers, and stores the result in the specified file as a raw
% pgm image; returns the number of bytes written
%
% Modified by Philip Tsai

function count=pgmwrite(a,filename)

if isa(a, 'uint8'),
  a=double(a); 
end

fid=fopen(filename,'w');
mn=min(min(a));
mx=max(max(a));
if mx > mn,
  s=0;
  e=255;
  k=(e-s)/(mx-mn);
  c=s-k*mn;
  a=round(k*a+c)';
else
  a=zeros(size(a));
end
fprintf(fid,'P5\n%d %d\n%d\n', [size(a,1) size(a,2) 255]);
count=fwrite(fid,a,'uchar');
fclose(fid);
