% Project 1
% Andy Doran and Brent Hendricks
%
% function pict = comp(cname,name,xdim,dcmp)
%
% cname = 'compressed file name' (as in 'lenna.comp' )
% name = 'input image' (as in 'lenna.256')
% xdim = x dimension of input image (usually 256 or 512)
% dcmp = desired pre-gzip compression ratio
%      = 1, .75, .5, .375, .25, .125,  or .0625
%
% pict is the transform output
%
% This program loads in an image and the x dimension of the input image
% (generally 256 or 512).
% A Haar wavelet transform is called repetively on the entire image,
% the upper left quadrant of the image, and so on, until we reach the
% minimum box size.  The input image and transform are both plotted.
% Then the image is quantized based on the specified dcmp.  A bitmap
% is created and sent out to a file.

function pict = comp(cname,name,xdim,dcmp)

pict = freadbin(name,xdim,xdim);

% xmin = x dimension of minimum quadrant image (usually 16 or 32)
xmin = 16;
xmin = xmin*2; % Scale xmin because program automatically does transform
               % at least once.

% Plot input image
figure(1)
image(pict);
colormap(gray(xdim));
txt = [num2str(name) ' before compression'];
title(txt)

% Get image range
imax = round(log2(xdim));
imin = round(log2(xmin));

% Call transform application
for i = imax:-1:imin
  b = 2^i;                % Get number of pixels to work on
  pict(1:b,1:b) = trans(pict(1:b,1:b));    % Work on rows of image
  pict(1:b,1:b) = trans(pict(1:b,1:b)')';  % Work on cols of image
end

% Plot input image
figure(2)
image(pict);
colormap(gray(xmin));
txt = [num2str(name) ' after Haar wavelet transform'];
title(txt)

% Quantize transformed image
max_p = max(max(abs(pict)));   % Get maximum value of transformed pict
npict = pict*127/max_p;        % Scale to -127:1:127

% get bitmask quantizer for each region
[bits,hdcmp] = mask(dcmp);

tot = sum(sum(bits));
comp = tot/2048;

temp = xmin/2;

%
% Init to zero
%
qpict = zeros(256,256);
scaleMax=zeros(16,16);
scaleMin=zeros(16,16);

for i = 1:(xdim/temp)    % 1:16
  for j = 1:(xdim/temp)  % 1:16
    if (bits(i,j) ~= 0)
      i1 = (i-1)*temp+1;
      i2 = i*temp;
      j1 = (j-1)*temp+1;
      j2 = j*temp;
      [scaleMax(i,j),scaleMin(i,j),qpict(i1:i2,j1:j2)]=quant4(npict(i1:i2,j1:j2),bits(i,j));
    end
  end
end


%
% qpict is now quantized (indexed)
%

%
% Write out to file
%
fid = fopen(cname,'wb');
fwrite(fid,max_p,'double');
fwrite(fid,hdcmp,'uchar');
for i = 1:16    % 1:16
  for j = 1:16  % 1:16
    if (bits(i,j) ~= 0)
      i1 = (i-1)*temp+1;
      i2 = i*temp;
      j1 = (j-1)*temp+1;
      j2 = j*temp;
      bwrite(fid, -8, scaleMin(i,j) );
      bwrite(fid, -8, scaleMax(i,j) );
      bwrite(fid, bits(i,j), qpict(i1:i2,j1:j2) );
   end
  end
end
fclose(fid);

return 
