/*******************************************************************************
 *
 *  Monte Carlo simulation, iterative decoding, AWGN channel
 *  Copyright (C) 2006-2009 Misha Stepanov
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

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

#define LDPCC_RANDOM yes

#include "ldpcc-3.2/ldpcc.c"

#define N_ITER 16384

#define UPDATE_STATISTICS \
  out = fopen(filename_num, "w");\
  for (i = 0; i <= (N_ITER + 1); i++)\
    fprintf(out, "%5d %4Ld %Ld\n", i, ERR[i], NUM[i]);\
  fclose(out);

int main(int argc, char **argv)
 {
  channel C;
  code H;
  iterative_decoder D;
  long long int NUM[N_ITER + 2], ERR[N_ITER + 2];
  int n_iter_out;
  real *xi, SNR2;

  int i, counter = 0;
  char filename_num[256], filename_conf[256];
  FILE *out;

  C.type = Gaussian_channel;
  SNR2 = atof(argv[1]); C.SNR = sqrt(SNR2);
  C.RNG_grown = 0; grow_RNG(&C);

  H.HiHa_grown = 0; H.ID_grown = 0;
  read_H_matrix("matrix_H", &H, 0);
  grow_iterative_decoder(&H);

  D.n_iter = N_ITER + 1; D.WCC = 1; D.relaxed = 0;

  ALLOCATE(xi, H.bits, real, real *)

  sprintf(filename_num, "data_id_mc_awgn/num_%4.2f", SNR2);
  out = fopen(filename_num, "r");
  if (out != NULL)
   {
    for (i = 0; i <= (N_ITER + 1); i++)
      fscanf(out, "%d %Ld %Ld\n", &counter, &(ERR[i]), &(NUM[i]));
    fclose(out);
   }
   else
    for (i = 0; i <= (N_ITER + 1); i++)
      { NUM[i] = 0; ERR[i] = 0; }

  while (ERR[N_ITER + 1] < 1000)
   {
    toss_noise(&C, H.bits, xi, 0);
    n_iter_out = iterative_decoding(&H, &C, &D, xi, 0);
    NUM[n_iter_out]++;
    if (check_error(&H))
     {
      ERR[n_iter_out]++;
      if (n_iter_out == (N_ITER + 1)) { UPDATE_STATISTICS }

      sprintf(filename_conf, "data_id_mc_awgn/conf/conf_%4.2f", SNR2);
      out = fopen(filename_conf, "a");
      for (i = 0; i < H.bits; i++) fprintf(out, "%22.16e ", xi[i]);
      fprintf(out, "\n"); fclose(out);
     }

    counter++;
    if (counter == 10000)
     {
      UPDATE_STATISTICS
      counter = 0;
     }
   }

  kill_RNG(&C);
  kill_iterative_decoder(&H);
  kill_H_matrix(&H);

  return 0;
 }

