function asciiwrite(S, name, fmt)
%SAXS/ASCIIWRITE Write ascii X,Y,I list for SAXS image.
%   ASCIIWRITE(S, 'name', FMT) writes X,Y,I triplets, one to a line, for each
%   pixel in SAXS image object S.  Numbers are written in ASCII, separated
%   by commas, to file 'name'.  X and Y are the x and y axis values for the
%   pixel, and I is the intensity (number of x-ray events) at that pixel.
%   FMT specifies a C-style numeric formatting string.  You may omit the
%   FMT argument, whereupon it defaults to '%g', a general numeric format.
%   Specify '%.1f' to print all numerals with one digit to the right of the
%   decimal point.  See HELP FPRINTF for more about formatting strings.

% Check arguments.
if ~ (nargin >= 2 ...
        & isa(S, 'saxs') ...
        & ischar(name) & size(name, 1) == 1)
    error('I need a SAXS argument and a file name argument.')
end

if nargin < 3  || ~ ischar(fmt)
    fmt = '%g';
end

file = fopen(name, 'w');
if file == -1
    error(['I can''t create the file ', name])
end

[X, Y] = meshgrid(xdata(S), ydata(S));
triplets = [X(:)'; Y(:)'; S.pixels(:)'];
fprintf(file, [fmt ',' fmt ',' fmt '\n'],triplets);
fclose(file);
