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.  For some types, should be 8 bit
%   type    -- three character file type specifier.  One of:
%               'jpg': transform encoded; good lossy compression
%               '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
%   display -- optionally allows supression of display (default: 1)
% 
% Output Parameters:
%   bits      -- Number of bits required per pixel
%   rms_error -- Value of the RMS error

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

fname = ['temp.' type];
levels = 255;

if strcmp(type,'jpg')
    imwrite(input/levels,fname,type,'Quality',quality);
else
    imwrite(input/levels,fname,type);
end
d = dir(fname);

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

delete(fname);

bits = d.bytes*8/prod(size(input));

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

if display
    
    %figure(1);
    %subplot(1,2,1);
    %imagesc(input); colorbar; colormap(gray); axis image
    %title('Input');
    subplot(1,2,1);
    imagesc(compressed); colorbar; colormap(gray); axis image
    title('Compressed');
    xlabel(char({[num2str(bits) ' bits per pixel'];['File size: ' num2str(round(d.bytes/1024)) 'kb']}));
    subplot(1,2,2);
    imagesc(sqrt(sq_error)); colorbar; colormap(gray); axis image
    title('Error');
    xlabel(['RMS Error: ', num2str(rms_error)]);
    
end
