function decoded = result(l,m,b,d)
%This function decodes the encoded UNIX file and calculates the MSE and
%PSNR.  It also outputs the compressed file.

[r,c] = size(l);
n = zeros(r,c);
sizer=r/b;
sizec=c/d;

% Read in encoded image from file
fid = fopen( 'temp.bin', 'rb' );
for i=1:sizer,
  for j=1:sizec,
    if( m(i,j) > 0 ), 
      n(i*b-(b-1):i*b,j*d-(d-1):j*d)=reshape(bread(fid, m(i,j), b*d ),b,d);
    end
  end
end
fclose(fid);

% Decode image 
decoded = idct2( 250*sign(n).*( exp(abs(n)/40) - 1 ));

% Calculate metrics
scaled = decoded - (min(min(decoded)));
scaled=round(scaled);
l2 = l - (min(min(l)));
l2 = l2*255/(max(max(l2)));

MSE=sum(sum(abs(l-scaled).^2))/r^2;
PSNR=10*log10(255^2/MSE);
bits=sum(sum(m))/(b*d);
sprintf('MSE = %f\nPSNR = %f\nBPP = %f\n',MSE,PSNR,bits)

% Display original and decoded
figure;
colormap(gray);
imagesc(l);
title('Original');

figure;
colormap(gray);
imagesc(decoded);
title('Decoded');    

