%% File: parityencoder.m
%% Read data from a file as bits
f=fopen('coriolan.txt','r');
%f=fopen('coriolan.bin','r');
A=fread(f,inf,'uint8');
fclose(f);
disp(['Read ',num2str(length(A)), ' bits']);
%% Make sure highest charater is < 127, i.e. high bit is 0.
if max(A) > 127
    disp(['High bit not free, cannot add parity']);
    return
else
    disp('High bit free, setting parity bit');
end
%% Construct parity-generating function
parityfun=@(x) bitor( bitshift( bitget(sum( de2bi(x) ), 1), 7), x);
%% Construct parity lookup table
lut=arrayfun(parityfun,0:127);
f=plot(lut,'.');
print('lut','-dpng');
%% Apply lookup table to data; the '+1' is because MATLAB arrays are 1-based
B=lut(A+1);
%% Write a parity-enhanced version of Coriolanus
f=fopen('coriolan.bin','wb+');
fwrite(f,B,'uint8');
fclose(f)


