#include <stdio.h>
#include "lfsr.h"

void LFSR_Reverse(const t_POLY polynom, t_POLY* reverse) {
  t_POLY forward = polynom;

  reverse->polynom = 0;
  reverse->width = forward.width;

  for(int i = 0; i <= forward.width; i++){
    reverse->polynom <<= 1;
    reverse->polynom |= ((forward.polynom % 2) & 1);
    forward.polynom >>= 1;
  }
  
  printf("Reverse LFSR from ");
  LFSR_PrintPoly(polynom);
  printf(" to ");
  LFSR_PrintPoly(*reverse);
  putchar('\n');
}

unsigned long LFSR_Next(const t_POLY polynom, const unsigned long d) {
 /* unsigned int lsb = d & 1;
  if(lsb)
    return (d >> 1) ^ polynom;
  else
    return (d >> 1);
  */
/*  unsigned long msb = (d & polynom) ^ polynom;
  if(msb) msb = 1UL;
  msb <<= LFSR_GetWidth(polynom);
  return (d >> 1) | msb;
  */
}

void LFSR_PrintPoly(const t_POLY polynom) {
  t_POLY p = polynom;

  p.polynom <<= (sizeof(p.polynom)*8)-p.width-1;

  for(int i = p.width; i >= 0; i--){
    if(p.polynom & POLY_INT_MAX) {
      if(i != p.width)
        printf(" + ");
      if(i != 0)
        printf("x^%d", i);
      else
        putchar('1');
    }
    p.polynom <<= 1;
  }
}

int LFSR_ReadPoly(FILE* f, t_POLY* dst){

  enum state{
    X,
    RAISEDTO,
    POWER,
    WHITESPACE,
    DONE
  }
  if(fscanf(f, "x^%d", &dst->width) != 1) {
    printf("Bad first element");
  }
  
}
