function [bits,rms_error] = file_code(input,type,quality,display)
%function [bits,rms_error] = file_code(input,type,quality,display)
%
% FILE_CODE -- writes an image to a file, reads it in, and
%              determines RMS error, filesize, and bits-per-pixel 
%
% Input Parameters:
%   input   -- the image to be compressed.  Should be 8 bits per channel
%   type    -- three character file type specifier.  One of:
%               'jpg': transform encoded; good lossy compression (default)
%               'tif': "packbits" compression; weak, lossless
%               'png': LZ compression; good, lossless
%               'bmp': No compression; terrible, lossless
%   quality -- quality factor from 0 to 100 for jpg ONLY (default: 75)
%   display -- optionally allows supression of display (default: 1)
% 
% Output Parameters:
%   bits      -- Number of bits required per pixel
%   rms_error -- Value of the RMS error
%

% Written by Mark Bartsch, Winter 2002
% Modification History:
%    8/16/02  --  Added modification history (MB)


if ~exist('display','var') | isempty(display)
    display = 1;
end

if ~exist('quality','var') | isempty(quality)
    quality = 75;
end

if ~exist('type','var') | isempty(type)
    type = 'jpg';
elseif ~ischar(type)
    quality = type;
    type = 'jpg';
end

fname = ['_temp.' type];
levels = 255;
input = double(input)/levels;

if strcmp(lower(type),'jpg')
    imwrite(input,fname,type,'Quality',quality);
    str = ['JPEG, Quality = ' num2str(quality)];
else
    imwrite(input,fname,type);
    str = upper(type);
end
d = dir(fname);

compressed = double(imread(fname,type))/levels;

delete(fname);

bits = d.bytes*8/size(input,1)/size(input,2);

sq_error = (input*levels - compressed*levels).^2; 
rms_error = sqrt(mean(sq_error(:)));


if display
    
    subplot(1,2,1);
    imagesc(input); axis image
    if size(input,3) == 1
        colorbar;
        colormap(gray);
    end
    title('Original');
    xlabel(char({ [ num2str(8*size(input,3)) ' bits per pixel'];['File size: ' num2str(round(prod(size(input))/1024)) 'kb']}));
    subplot(1,2,2);
    imagesc(compressed); axis image
    if size(input,3) == 1
        colorbar;
        colormap(gray);
    end
    title(['Compressed: ' str]);
    xlabel(char({[num2str(bits) ' bits per pixel'];['File size: ' num2str(round(d.bytes/1024)) 'kb']; ...
            ['RMS Error: ' num2str(rms_error)] }));    
end
