%saves matrix data across rows into a pnm array, across rows       Steve Mann
%
%Examples:
% savepnm('/mas/garden/flakes/steve/perspectivepics/red/data',A)
% savepnm('/mas/garden/flakes/steve/perspectivepics/red/data',A,'uchar')
%
%Types: char, schar,  short,  int,  long,  float, double,
%       uchar,        ushort, uint, ulong,
%       float32, float64, int8, int16, int32,
%       intN, uintN                               where 1 <= N <= 32
%
%right now only supports greyscale byte images
%
%overwrites file if already exists

function mycountmaybereturned = fprint_and_fwrite(myfilename,A,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';
end%if

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

fprintf(myint,'P5\n');
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(A);
fprintf(myint,'%d\n',N);
fprintf(myint,'%d\n',M);
fprintf(myint,'%d\n',255);

mycount=fwrite(myint,A.',mytype);  % transpose for TV order
[M N]=size(A);
if mycount ~= M*N
  error(sprintf('savepnm: end of file reached; only %g of %g*%g=%g elements written',...
                mycount,M,N,M*N))
end%if

if nargout==1
  mycountmaybereturned=mycount;
end%if
if nargout==0
  disp(sprintf(['savepnm: %g of %g*%g=%g elements written to ' myfilename],...
                mycount,M,N,M*N))
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

