/* basic.c
 * Daniel S. Roche, January 2009
 * http://www.cs.uwaterloo.ca/~droche/
 *
 * Basic arithmetic and utility functions for polynomial computation
 *
 * See LICENSE.txt for copyright and permissions.
 */

#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include "lsmul.h"

const lsmul_ele LSMUL_MAX_P = 1 << 29;

long read_poly_prealloc (FILE *stream, lsmul_ele *a) {
   int c;
   long i = 0;

   do { c = getc(stream); } while (isspace(c));
   assert (c == '[');
   do { c = getc(stream); } while (isspace(c));
   while (c != ']') {
      assert (isdigit(c));
      a[i] = (lsmul_ele)(c - '0');
      while (isdigit(c = getc(stream))) {
         a[i] *= 10;
         a[i] += (lsmul_ele)(c - '0');
      }
      ++i;
      while (isspace(c)) c = getc(stream);
   }
   return i;
}

lsmul_ele* read_poly (FILE *stream, long *sa) {
   lsmul_ele *a;
   int c;
   long i = 0, len = 8;

   a = malloc (len * sizeof(lsmul_ele));
   assert (a);

   do { c = getc(stream); } while (isspace(c));
   assert (c == '[');
   do { c = getc(stream); } while (isspace(c));

   while (c != ']') {

      if (i == len) {
         len <<= 1;
         a = realloc (a, len * sizeof(lsmul_ele));
         assert (a);
      }

      assert (isdigit(c));
      a[i] = (lsmul_ele)(c - '0');
      while (isdigit(c = getc(stream))) {
         a[i] *= 10;
         a[i] += (lsmul_ele)(c - '0');
      }
      ++i;
      while (isspace(c)) c = getc(stream);
   }

   *sa = i;
   return a;
}

void write_poly (FILE *stream, const lsmul_ele *a, long sa) {
   long i = 0;
   
   if (sa == 0) {
      fputs ("[ ]", stream);
      return;
   }

   fprintf (stream, "[" LSMUL_WRITE_ELE, a[0]);
   while (++i < sa)
      fprintf (stream, " " LSMUL_WRITE_ELE, a[i]);

   fputc(']',stream);
}
