function [img] = writep5(xx,fname)
% [img, size]: image matrix and size vector(width,height, max_gray)
fid = fopen(fname, 'wb');
comment = ['Writing ' fname ' Please wait ...'];
disp(comment);
magic = [sprintf('P5\n')];
fprintf(fid,'%c',magic); %Write P5
img = xx';
siz = size(img);
height = siz(2);
width = siz(1);
for i=1:siz(1),
  for j=1:siz(2),
    if img(i,j)<0.5, 
      img(i,j)=0;
    end;
    if img(i,j)>255,
      img(i,j)=255;
    end;
  end;
end; 
maxgray = 255;
header1 = [sprintf('%d %d\n%d\n',width, height,maxgray)];
fprintf(fid,'%c',header1);
fwrite(fid,img,'uchar');
fclose(fid);
comment = ['Writep5 is Done.'];
disp(comment);
return
