classdef MyHamming
% obj=MyHamming constructs the codec
% Documentation
    properties(Constant)
        parityMatrix = gf([0 1 1 1; 1 0 1 1; 1 1 0 1],1);
        % Syndrome decoding lookup table
        lut = gf([0,0,0,0,0,0,0;
                  0,0,0,0,1,0,0;
                  0,0,0,0,0,1,0;
                  0,0,1,0,0,0,0;
                  0,0,0,0,0,0,1;
                  0,1,0,0,0,0,0;
                  1,0,0,0,0,0,0;
                  0,0,0,1,0,0,0;
                 ]');
    end;

    properties
        generatorMatrix;
        checkMatrix;
    end;

    methods

        function obj = MyHamming(obj)
            obj.generatorMatrix = [eye(4); obj.parityMatrix];
            obj.checkMatrix = [obj.parityMatrix,eye(3)];
        end;

        function code=encode(obj,msg)
            [codeRank,blockCount] = size(msg);
            if codeRank ~= 4 
                error(['Message incompatible with rank 4.']);
            end
            code = obj.generatorMatrix * msg;
        end;

        function code=decode(obj,received)
            [codeLength,blockCount] = size(received);
            if codeLength ~=7 
                error(['Received message incompatible with code length 7']);
            end
            z = obj.checkMatrix * received;
            idx = bi2de(z.x');
            code=received+obj.lut(:,idx+1);
        end;
    end
end
