function y = total(l,m,b,d)

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

if or(rem(r,b)~=0,rem(c,d)~=0)
   y=[];
else
  
   % Shift image to be zero-centered
   l=l-(mean(mean(l)));
  
   % Perform DCT and scaling (to range of -128 to 128 ) then round to int
   y = round( scale( dct2(l) ) );
   SIZ=[r,c];  
   for i=1:sizer,
      for j=1:sizec,
         if (m(i,j) == 0),
            y(i,j)=0;
         else
            y(i,j)=y(i,j);
         end
      end
   end
  
   %write to binary output file
  
   fid = fopen('temp.bin', 'wb');
   for i=1:sizer,
      for j=1:sizec,
         if (m(i,j)~=0),
            wtype=(strcat('bit',int2str(bits+1)));
            for ii = 1:b
               for jj = 1:d         
                  fwrite(fid,y(b*(i-1)+ii,d*(j-1)+jj),wtype);
               end
            end
         end
      end
   end
   fclose(fid);
  
   % Decode image
   decoded = idct2( 250*sign(y).*( exp(abs(y)/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-decoded).^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');   
end