#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h> 


// ========================================================================================================
// ========================================================================================================
// See /home/research/research/FPGAs/HELP/VHDL_HELP/contrib/lfsr_randgen/trunk/lfsr_pkg.vhd Other possibilities 
// from stdint: int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t 

uint16_t LFSR_11_A_bits(int load_seed, uint16_t seed)
   {
   static uint16_t lfsr;
   uint16_t bit, nor_bit;

// Load the seed on the first iteration.
   if ( load_seed == 1 )
      lfsr = seed;
   else
      {

// Allow all zero state. See my BIST class notes in VLSI Testing. Note, we use low order bits
// here because bit is shifted onto the low side, not high side as in my lecture slides.
      if ( !( (((lfsr >> 9) & 1) == 1) || (((lfsr >> 8) & 1) == 1) ||
              (((lfsr >> 7) & 1) == 1) || (((lfsr >> 6) & 1) == 1) || (((lfsr >> 5) & 1) == 1) ||
              (((lfsr >> 4) & 1) == 1) || (((lfsr >> 3) & 1) == 1) || (((lfsr >> 2) & 1) == 1) ||
              (((lfsr >> 1) & 1) == 1) || (((lfsr >> 0) & 1) == 1) ) )
         nor_bit = 1;
      else
         nor_bit = 0;

// xor_out := rand(10) xor rand(8)
      bit  = ((lfsr >> 10) & 1) ^ ((lfsr >> 8) & 1) ^ nor_bit;

// printf("LFSR value %d\tNOR bit value %d\tlow order bit %d\n", lfsr, nor_bit, bit);

// Shift in the bit. Convert 16-bit to 11-bit quantity.
      lfsr = ((lfsr << 1) | bit) & 2047;
      }

   return lfsr;
   }
