%% File: hammingdecoder.m
infile='Nikolaus_Kopernikus_hamming74.bin';
outfile='Nikolaus_Kopernikus_hamming74_d.png';
reps=5;
%% Read Kopernikus portrait with Hamming (7,4) encoding.
f=fopen(infile,'rb');
% Recover magic number
magic=reshape(char(fread(f,4*reps,'char')),4,reps);
magic=mode(magic');
if any(magic~='_RTG') 
    disp(['Magic number did not match: ',magic]);
    return;
end
% Recover the shape of the image
sz=reshape(fread(f,3*reps,'uint16'),3,5);
sz=mode(sz');
disp(['Image size ', num2str(sz)]);
data=fread(f,inf,'ubit7');
fclose(f);
%% Recover code
code=gf(de2bi(data,[],2)');
%% Decode, correct single-bit errors
h=MyHamming;
recovered0=decode(h,code);
%% Discard parity bits
recovered1=recovered0(1:4,:);
recovered2=recovered1.x;
%% Convert message to nibbles 
recovered3=uint8(recovered2);                      % gf->integer
recovered4=bi2de(recovered3',2);
recovered5=reshape(recovered4,numel(recovered4)/2,2);
recovered6=bi2de(recovered5,2^4);
A=reshape(recovered6,sz);
%imshow(A);
%% Write the image
disp(['Writing decoded PNG file ', outfile]);
imwrite(A,outfile,'png');
