function writeppm(im,map,file);
% WRITEPPM  Writes an Image and a Colormap as a PPM file
%
% Usage: writeppm(im,map,file);
%
% Inputs: im = image
%         map = image colormap
%         file = output PPM file
%
% Description:  Writes image in PPM format, a widely-used, simple, 
%      portable, but non-compressed format.  PPM images can be converted
%      to gif, jpg, tif, bmp, pict, and nearly every other image format
%      know to man (or nerd).   Look for the 'netpbm' distribution on 
%      the internet.
%
%
% Rich Signell
% U.S. Geological Survey
% rsignell@usgs.gov

[height,width]=size(im);
[ncols,nrgb]=size(map);

bad=find(im>ncols);
if(~isempty(bad)),
  im(bad)=ncols*ones(size(im(bad)));
end
map=map*255;
maxc=max(map(:));

fid=fopen(file,'w');
fprintf(fid,'P6\n');
fprintf(fid,'#Generated by Matlab routine WRITEPPM\n');
fprintf(fid,'%4d %4d\n',[width height]);
fprintf(fid,'%4d\n',maxc);
for i=1:height;
  row=im(i,:);
  rgb=[map(row,1) map(row,2) map(row,3)]';
  fwrite(fid,rgb,'uchar');
end
fclose(fid);
