%saves matrix data across rows into a pnm array, across rows       Steve Mann
%
%Examples:
% savepnm('/mas/vision/bigu/steve/pork.pgm',A)
% savepnm('/mas/vision/bigu/steve/pork.pgm',A,'int') % future suport diff. types
%
%Types: char, schar,  short,  int,  long,  float, double,
%       uchar,        ushort, uint, ulong,
%       float32, float64, int8, int16, int32,
%       intN, uintN                               where 1 <= N <= 32
%
% savepnm('/mas/vision/bigu/steve/pork.pgm',R,G,B)      % saves a color image
%
%overwrites file if already exists

function mycountmaybereturned = savepnm(myfilename,R,G_or_mytype,B,mytype);
if nargin==3
  disp('savepnm.m: doesn''t yet support types other than uchar')
  error('           hopefully will add this support later')
end%if
if nargin==2
  mytype='uchar';
  iscolor=0;
end%if
if nargin==4  %  (filename,R,G,B)
  mytype='uchar';
  iscolor=1;
  [Mr,Nr]=size(R); [Mg,Ng]=size(G_or_mytype); [Mb,Nb]=size(B);
  if ~((Mr==Mg)&(Mr==Mb)&(Nr==Ng)&(Nr==Nb))
    error('savepnm: error: the 3 images are different sizes')
  end%if
end%if
if nargin==5  %  (filename,R,G,B,datatype)
  disp('savepnm.m: doesn''t yet support types other than uchar')
  error('           hopefully will add this support later')
end%if

myint=fopen(myfilename,'w');
if myint<0
  error('savepnm: fopen returned a negative integer meaning file write failed')
end%if

if iscolor
  fprintf(myint,'P6\n');
else%if
  fprintf(myint,'P5\n');
end%if
time=fix(clock); timestring=sprintf('%02dh%02d, %02d',time(4),time(5),time(6));
fprintf(myint,'#generated by Matlab savepnm.m; Steve Mann; %s, %s\n',...
        date,timestring);
directorystring=pwd;
fprintf(myint,'#from directory %s\n',directorystring);
[M,N]=size(R); MN=M*N;  % greyscale only, image in matrix `R'
fprintf(myint,'%d\n',N);
fprintf(myint,'%d\n',M);
fprintf(myint,'%d\n',255);

if ~iscolor % grey only
  mycount=fwrite(myint,R.',mytype);  % transpose for TV order
  if mycount ~= M*N
    error(sprintf('savepnm: file end?? only %g of %g*%g=%g elements written',...
                  mycount,M,N,M*N))
  end%if
else%if color   % interleave data pixels by putting in 3 by MN matrix
  data=[reshape(R.',1,MN); reshape(G_or_mytype.',1,MN); reshape(B.',1,MN)];
  mycount=fwrite(myint,data,mytype);
  if mycount ~= M*N*3
    error(sprintf('savepnm: end??? only %g of %g*%g*3=%g elements written',...
                  mycount,M,N,M*N*3))
  end%if
end%if grey only

if nargout==1
  mycountmaybereturned=mycount;
end%if
if nargout==0
  if ~iscolor
    disp(sprintf(['savepnm: %g of %g*%g=%g elements written to ' myfilename],...
                  mycount,M,N,M*N))
  else%if
    disp(sprintf(['savepnm: %g of %g*%g*3 = %g elements written to ' myfilename],...
                  mycount*3,M,N,M*N*3))
  end%if
end%if
fclose_return=fclose(myint);   % returns zero if ok, -1 if not
if fclose_return ~= 0
  disp('savepnm: fclose returned nonzero value, so problem closing file');
end%if

