/* 
  FILE...: ldpc_enc.c
  AUTHOR.: Bill Cowley, David Rowe
  CREATED: Sep 2016

  RA LDPC encoder program. Using the elegant back substitution of RA
  LDPC codes.

  building: gcc ldpc_enc.c -o ldpc_enc -Wall -g
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

/* generated by ldpc_fsk_lib.m:ldpc_decode() */

#include "H2064_516_sparse.h"

void encode(unsigned char ibits[], unsigned char pbits[]) {
    unsigned int p, i, tmp, par, prev=0;
    int ind;

    for (p=0; p<NUMBERPARITYBITS; p++) {
        par = 0; 

        for (i=0; i<MAX_ROW_WEIGHT; i++) {
            ind = (int)H_rows[p + i*NUMBERPARITYBITS];
            par = par + ibits[ind-1];
        }

        tmp = par + prev;

        tmp &= 1;    // only retain the lsb 
        prev = tmp; 
        pbits[p] = tmp; 
    }
}

int main(int argc, char *argv[])
{
    unsigned char ibits[NUMBERROWSHCOLS];
    unsigned char pbits[NUMBERPARITYBITS];
    FILE         *fin, *fout;
    int           sd, i;
    double        sdout[NUMBERROWSHCOLS+NUMBERPARITYBITS];

    if (argc < 3) {
        fprintf(stderr, "usage: %s InputOneBytePerBit OuputFile [--sd]\n", argv[0]);
        exit(0);
    }

    if (strcmp(argv[1], "-")  == 0) fin = stdin;
    else if ( (fin = fopen(argv[1],"rb")) == NULL ) {
        fprintf(stderr, "Error opening input bit file: %s: %s.\n",
                argv[1], strerror(errno));
        exit(1);
    }
        
    if (strcmp(argv[2], "-") == 0) fout = stdout;
    else if ( (fout = fopen(argv[2],"wb")) == NULL ) {
        fprintf(stderr, "Error opening output bit file: %s: %s.\n",
                argv[2], strerror(errno));
        exit(1);
    }
    
    sd = 0;
    if (argc == 4) 
        if (strcmp(argv[3], "--sd") == 0)
            sd = 1;

    while (fread(ibits, sizeof(char), NUMBERROWSHCOLS, fin) == NUMBERROWSHCOLS) {

        encode(ibits, pbits);  
        
        if (sd) {
            for (i=0; i<NUMBERROWSHCOLS; i++)
                sdout[i] = 1.0 - 2.0 * ibits[i];
            for (i=0; i<NUMBERPARITYBITS; i++)
                sdout[i+NUMBERROWSHCOLS] = 1.0 - 2.0 * pbits[i];
            fwrite(sdout, sizeof(double), NUMBERROWSHCOLS+NUMBERPARITYBITS, fout); 
        }
        else {
            fwrite(ibits, sizeof(char), NUMBERROWSHCOLS, fout); 
            fwrite(pbits, sizeof(char), NUMBERPARITYBITS, fout); 
        }
    }

    fclose(fin);  
    fclose(fout); 

    return 1;
}
