#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {

    char codeword[7+1]; //we index from 1
    char received[7+1];
    int i, count;

    srandom (time(NULL));

    // randomly fill the data
    codeword[3] = random()%2;
    codeword[5] = random()%2;
    codeword[6] = random()%2;
    codeword[7] = random()%2;

    // calculate parity bits
    codeword[1] = (codeword[3]+codeword[7]+codeword[5])%2;
    codeword[2] = (codeword[3]+codeword[7]+codeword[6])%2;
    codeword[4] = (codeword[6]+codeword[7]+codeword[5])%2;

    // print
    printf ("Codeword along with parity:\n");
    printf ("p1 p2 d3 p4 d5 d6 d7\n");
    for (i = 1; i <= 7; i++)
	printf (" %d ", codeword[i]);
    printf ("\n");

    // randomly generate an error
    i = (random()%7) + 1;
    codeword[i] = (codeword[i]+1)%2;
    printf ("Randomly inserted an error at bit %d\n", i);

    // now determine the error. make a copy first
    for (i = 1; i <= 7; i++)
	received[i] = codeword[i];

    // calculate parity bits
    received[1] = (received[3]+received[7]+received[5])%2;
    received[2] = (received[3]+received[7]+received[6])%2;
    received[4] = (received[6]+received[7]+received[5])%2;

    count = 0;
    if (received[1] != codeword[1])
	count += 1;
    if (received[2] != codeword[2])
	count += 2;
    if (received[4] != codeword[4])
	count += 4;

    printf ("Deteced an error in bit %d\n", count);


    return 0;
}

