%% File: anvindecoder.m
%% Decode Kopernikus portrait protected with Anvin RAID 6 code
infile='Nikolaus_Kopernikus_anvin_c.bin';
outfile='Nikolaus_Kopernikus_anvin_d.png';
%% Read Kopernikus portrait with RAID6 encoding
disp(['Recovering image from file ',infile]);
f=fopen(infile,'rb');
% Recover magic number
reps=5;
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)]);
% Read RAID 6 code
data = fread(f,inf,'uint8');
fclose(f);
%% Create Anvin RAID 6 codec with GF(256) vectors
k=sz(3);   
obj = Anvin('m',8,'codeRank',k);
%% Form received vector
n=k+2;
received=gf(reshape(data,n,sz(1)*sz(2)),8);
%% Correct errors
code=decode(obj,received);
%% Recover image
% Discard parity
data=code(1:k,:);                       
data=data.x;
A=uint8(reshape(data', sz));
%% Write the image
disp(['Writing PNG file ',outfile]);
imwrite(A,outfile,'png');




