m=512; n=512;
file = ["lenna.raw", "mandrill.raw", "scene.raw", "tiffany.raw", "jet.raw", "peppers.raw"];
file128 = ["891538.raw", "892539.raw"];
fin=fopen("codebook",'r');
X=fread(fin,8192,'uint8=>uint8'); fclose(fin);
codebook=reshape(X,16,512)';
for i=1:6
    ti = cputime;
    h=1;
    re=uint8(zeros(512, 512));
    img=zeros(16384, 16);
    imgtmp=zeros(16384, 16);
    fin=fopen(file(i),'r');
    X=fread(fin,m*n,'uint8=>uint8'); fclose(fin);
    Y=reshape(X,512,512)';
    for j=1:4:512
        for k=1:4:512
            block = Y(j:j+3, k:k+3)';
            img(h,:) = block(:)';
            h = h+1;
        end
    end
    for j=1:16384
        t = 1+4*floor((j-1)/128);
        u = 4*(mod(j-1,128))+1;
        min = 100000;
        for k=1:512
            V = double(codebook(k,:)) - double(img(j,:));
            tmp = sqrt(sum(V.*V));
            if(tmp<min)
                min = tmp;
                re(t:t+3, u: u+3) = reshape(codebook(k,:), 4, 4)';
            end
        end
%         re(t:t+3, u: u+3) = reshape(imgtmp(j,:), 4, 4)';
    end
    figure;
    imshow(re);
%     table
    peaksnr = psnr(Y,re);
    fprintf("PSNR: %f cputime: %d\n", peaksnr, cputime-ti);
end
for i=1:2
    ti = cputime;
    h=1;
    re=uint8(zeros(128, 128));
    img=zeros(1024, 16);
    fin=fopen(file128(i),'r');
    X=fread(fin,128*128,'uint8=>uint8'); fclose(fin);
    Y=reshape(X,128,128)';
    for j=1:4:128
        for k=1:4:128
            block = Y(j:j+3, k:k+3)';
            img(h,:) = block(:)';
            h = h+1;
        end
    end
    for j=1:1024
        t = 1+4*floor((j-1)/32);
        u = 4*(mod(j-1,32))+1;
        min = 100000;
        for k=1:512
            V = double(codebook(k,:)) - double(img(j,:));
            tmp = sqrt(sum(V.*V));
            if(tmp<min)
                min = tmp;
                re(t:t+3, u: u+3) = reshape(codebook(k,:), 4, 4)';
            end
        end
%         re(t:t+3, u: u+3) = reshape(imgtmp(j,:), 4, 4)';
    end
    figure;
    subplot(1, 2, i);
    imshow(re);
%     table
    peaksnr = psnr(Y,re);
    fprintf("PSNR: %f cputime: %d\n", peaksnr, cputime-ti);
end







