function writejpg(data, map, filename, varargin)
%WRITEJPG Write a JPG file to disk.
%   WRITEJPG(I,[],FILENAME) writes the grayscale image I
%   to the file specified by the string FILENAME.
%
%   WRITEJPG(RGB,[],FILENAME) writes the truecolor image
%   represented by the M-by-N-by-3 array RGB.
%
%   WRITEJPG(X,MAP,FILENAME) writes the indexed image X with
%   colormap MAP.  The resulting file will contain the equivalent
%   truecolor image.
%
%   WRITEJPG(...,'quality',VAL) uses VAL as the quality
%   factor.  VAL should be a scalar in the range [0, 100];
%   its default is 75.

%   Steven L. Eddins, August 1996
%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.6 $  $Date: 1997/11/21 23:36:30 $

if (ndims(data) > 3)
    error(sprintf('%d-D data not supported for JPEG files', ndims(data)));
end

if (~isempty(map) & ndims(data)>2)
    error(sprintf('%d-D indexed image data not supported for JPEG files', ndims(data)));
end

if (~isempty(map)) % Convert to RGB
    colors = uint8(round(min(max(map,0),1)*255));
    if isa(data,'uint8'),
       data = reshape(colors(double(data)+1,:),[size(data) 3]);
    else
       data = reshape(colors(data,:),[size(data) 3]);
    end
end

% 1 component or 3 components?
ncomp = size(data,3);
if ((ncomp ~= 1) & (ncomp ~= 3))
    error(sprintf('Data with %d components not supported for JPEG files', ...
            ncomp));
end

% Set default parameters
quality = 75;

% Process param/value pairs
propStrings = ['quality'];
    
for k = 1:2:length(varargin)
    prop = lower(varargin{k});
    if (~isstr(prop))
        error('Parameter name must be a string');
    end
    idx = strmatch(prop, propStrings);
    if (isempty(idx))
        error(sprintf('Unrecognized parameter name "%s"', prop));
    elseif (length(idx) > 1)
        error(sprintf('Ambiguous parameter name "%s"', prop));
    end
    
    prop = deblank(propStrings(idx,:));
    
    switch prop
    case 'quality'
        quality = varargin{k+1};
        if ((quality < 0) | (quality > 100))
            error('Invalid value for ''Quality''');
        end
        
    end
end
        
if ~isa(data, 'uint8')
   data = uint8(round(255*double(data)));
elseif isa(data, 'uint8') & islogical(data)
   data(data) = 255;
end

wjpgc(data, filename, quality);
