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(xx);
height = siz(1);
width = siz(2);
maxgray = 255;
header1 = [sprintf('%d %d\n%d\n',width, height,maxgray)];
%fprintf(fid,'%c',header1);
for i=1:height,
  for j=1:width,
   if xx(i,j)<16,
     fprintf(fid,'%0x',xx(i,j));
   else
    fprintf(fid,'%2x', xx(i,j));
   end;
   if j < width,
     fprintf(fid,' ');
   end;
  end;
  fprintf(fid,'\n');
  fprintf(fid,'\n');
end;
fclose(fid);
comment = ['Writep5 is Done.'];
disp(comment);
return
