function yq = compress(x,p,cmode)
    % Modes: 'std' - standard compression, 'jpeg' - jpeg compression
    if strcmp(cmode,'std')
        Q = p*8./hilb(8);
    elseif strcmp(cmode,'jpeg')
        Q = p*[16 11 10 16 24 40 51 61; 12 12 14 19 26 58 60 55; ...
             14 13 16 24 40 57 69 56; 14 17 22 29 51 87 80 62; ...
             18 22 37 56 68 109 103 77; 24 35 55 64 81 104 113 92; ...
             49 64 78 87 103 121 120 101; 72 92 95 98 112 100 103 99];
    elseif strcmp(cmode,'jpegq')
        lenx = size(x,1); leny = size(x,2); 
        Q1 = p*[16 11 10 16 24 40 51 61; 12 12 14 19 26 58 60 55; ...
             14 13 16 24 40 57 69 56; 14 17 22 29 51 87 80 62; ...
             18 22 37 56 68 109 103 77; 24 35 55 64 81 104 113 92; ...
             49 64 78 87 103 121 120 101; 72 92 95 98 112 100 103 99];
        Q2 = p*[17 18 24 47 99 99 99 99; 18 21 26 66 99 99 99 99; ...
             24 26 56 99 99 99 99 99; 47 66 99 99 99 99 99 99; ...
             99 99 99 99 99 99 99 99; 99 99 99 99 99 99 99 99; ...
             99 99 99 99 99 99 99 99; 99 99 99 99 99 99 99 99];
         xd = double(x);
         R = xd(:,:,1); G = xd(:,:,2); B = xd(:,:,3);
         Y = 0.299*R + 0.587*G + 0.114*B;
         U = B - Y;
         V = R - Y;
         xr = [Y,U,V]; xr = reshape(xr,[lenx,leny,3]);
    end
    
    xe = zeros(length(x),size(x,3));
    for c = 1:size(x,3)
        for n = 0:(size(x)/8)-1
            for m = 0:(size(x)/8)-1
                if strcmp(cmode,'jpegq')
                    xs = xr(1+8*n:8+8*n,1+8*m:8+8*m,c);
                else
                    xs = x(1+8*n:8+8*n,1+8*m:8+8*m,c);
                end
                xd = double(xs);
                xc = xd - 128; %center
                C = dctm(xs);
                y = C*xc*C';
                if strcmp(cmode,'jpegq')
                    if c == 1
                        yq = round(y./Q1);
                        ydq = yq.*Q1;
                    else
                        yq = round(y./Q2);
                        ydq = yq.*Q2;
                    end
                else
                    yq = round(y./Q);
                    ydq = yq.*Q;
                end
                xdq = C'*ydq*C;
                xe(1+8*n:8+8*n,1+8*m:8+8*m,c) = xdq + 128;
            end
        end
    end
    
    if strcmp(cmode,'jpegq')
        Y = xe(:,:,1); U = xe(:,:,2); V = xe(:,:,3);
        R = V + Y;
        B = U + Y;
        G = (Y - 0.299*R - 0.114*B)/(0.587);
        xe = [R,G,B]; xe = reshape(xe,[lenx,leny,3]);
    end
    
    tstr1 = 'Uncompressed Image';
    tstr2 = sprintf('Compressed Image, p = %d',p);
    if size(x,3) == 1
        figure(1); imagesc(uint8(x)); colormap(gray)
        title(tstr1)
        figure(2); imagesc(uint8(xe)); colormap(gray)
        title(tstr2)
    else
        figure(1); image(uint8(x))
        title(tstr1)
        figure(2); image(uint8(xe))
        title(tstr2)
    end
end