/* read a 'flat file' (matlab ascii format) matrix.
 * returns a pointer to a new matrix structure
 */

#include "mat.h"
#include "matops.h"

struct dmat * read_mat(s)
   char *s;
{
   extern void exit();
   extern double atof();
   struct dmat *A;
   char *p, a[64];
   int row, col, word, c;
   FILE * fp, *fopen();
   fp = fopen(s, "r");
   if (fp == NULL) {
      fprintf(stderr, "read_mat(): can't open %s\n", s);
      exit(127);
      }

   /* first, count rows and columns of matrix */
   row = word = 0;
   for (c=getc(fp); c != EOF; ) {

      while ( (c==' ' || c=='\t' || c=='\n') && c != EOF) {
	 if (c == '\n') row++;
	 c = getc(fp);
	 }
      while ( ! (c==' ' || c=='\t' || c=='\n') && c != EOF) {
	 c = getc(fp);
	 }
      if (c != EOF) word++;
      }

   col = word / row;
   if ( word != row * col ) {
      fprintf(stderr, "read_mat(): size error in file %s\n", s);
      printf("row=%d, col=%d, word=%d\n", row, col, word);
      exit(127);
      }

   fclose(fp);

   A = new_mat(row, col);

   fp = fopen(s, "r");
   if (fp == NULL) { printf("wierd error\n"); exit(127); }
   row = word = 0;
   for (c=getc(fp); c != EOF; ) {

      while ( (c==' ' || c=='\t' || c=='\n') && c != EOF) {
	 if (c == '\n') row++;
	 c = getc(fp);
	 }
      p = a;
      while ( ! (c==' ' || c=='\t' || c=='\n') && c != EOF) {
	 *p++ = c;
	 c = getc(fp);
	 }
      if (c != EOF) {
	 *p = 0;
	 set_mat_elem(A, row, word % col, (float) atof(a));
	 word++;
	 }
      }
   fclose(fp);

   return A;
   }

/* print a matrix as a 'flat file' (matlab ascii format).
 */
void print_mat(A, s)
   struct dmat * A; char *s;
{
   int row, col;
   extern void exit();
   FILE * fp, *fopen();
   fp = fopen(s, "w");
   if (fp == NULL) {
      fprintf(stderr, "print_mat(): can't open %s\n", s);
      exit(127);
      }

   for (row = 0; row < A->nrows; row++) {
      for (col = 0; col < A->ncols; col++)
	 fprintf(fp, "%g ", get_mat_elem(A, row, col));
      fprintf(fp, "\n");
      }		 

   fclose(fp);
   }

