/*******************************************************\
* 							*
*              @(#)read_matrix.c	1/2/89		*
*	Author:       Tony Plate			*
*	Copyright (C) 1989 Tony Plate			*
*	This program may be freely distributed,		*
*	provided that this copyright notice is		*
*	retained intact.  There is no warranty		*
*	with this software.				*
* 							*
\*******************************************************/

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

/* * one function that will read in a matrix, (and allocate space for it) */
float *read_matrix(int *x_dim ,
                      int *y_dim )

{
  float v,*matrix;
  int x,y,r,stop;
  int long_matrix = 0;	/* true if we don't know the # of y lines */
  if (scanf(" %d",x_dim)!=1) {
    fprintf(stderr,"read_matrix: couldn't read x dimensions\n");
    return NULL;
  }
  if (scanf(" *%c",&x)==1) {
    long_matrix = 1;
  } else if (scanf(" %d",y_dim)!=1) {
    fprintf(stderr,"read_matrix: couldn't read y dimension\n");
    return NULL;
  }
  if (!long_matrix) {
    if (*x_dim<=0 || *y_dim<=0) {
      fprintf(stderr,"read_matrix: bad dimensions %d %d\n",*x_dim,*y_dim);
      return NULL;
    }
    matrix = (float *) calloc(*x_dim * *y_dim , sizeof(float));
    if (matrix==NULL) {
      fprintf(stderr,"read_matrix: can't allocate space\n");
      return NULL;
    }  
    for (y=0;y<*y_dim;y++)
      for (x=0;x<*x_dim;x++)
	if (scanf(" %f",&v)!=1) {
	  fprintf(stderr,"read_matrix: can't read value row=%d,col=%d\n",y,x);
	  return NULL;
	} else matrix[y*(*x_dim) + x] = v;
  } else {
    if (*x_dim<=0) {
      fprintf(stderr,"read_matrix: bad x dimensions %d\n",*x_dim);
      return NULL;
    }
    *y_dim = 1;
    matrix = (float *) calloc(*x_dim * *y_dim , sizeof(float));
    if (matrix==NULL) {
      fprintf(stderr,"read_matrix: can't allocate space\n");
      return NULL;
    }
    stop = 0;
    for (y=0;!stop;y++) {
      for (x=0;x<*x_dim;x++) {
	if (scanf(" %f",&v)!=1) {
	  if (x!=0) {
	    fprintf(stderr,"read_matrix: can't read value row=%d,col=%d\n",y,x);
	    return NULL;
	  } else {
	    stop = 1;
	    break;
	  }
	} else {
	  if (y==*y_dim) {
	    (*y_dim)++;
	    matrix = (float *) realloc(matrix,*x_dim * *y_dim * sizeof(float));
	    if (matrix==NULL) {
	      fprintf(stderr,"read_matrix: can't reallocate space\n");
	      return NULL;
	    }  
	  }
	  matrix[y*(*x_dim) + x] = v;
	}
      }
    }
  }
  return matrix;
}
