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

static char *read_datamatid = "$Id: read_datamat.c,v 1.4 1996/12/30 22:02:23 galway Exp $";

/******************************************************************/
/* 

    read_datamat.c

    Copyright (C) 2004  Lionel A. Galway

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    For a copy of the GNU General Public License write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


   Routine to read in data from a file, and then construct a block
   clustering data matrix.

   Data format
       nrows ncols
       column labels
       row1label row1data
       row2label row2data
       ....
       rowNlabel rowNdata

    This basically assembles the data into arrays, char strings,
    etc. and then passes it to another routine that actually sets up
    the data structure.

   L. Galway 1-DEC-1995 */
/******************************************************************/

extern struct datamat *make_datamat();

struct datamat *read_datamat(fp)
FILE *fp;
{
  int nr,nc,i,j, **data;char BUF [1000], **rlbs,**clbs;

  fscanf(fp,"%d %d",&nr,&nc); /* Get dimensions of data */

  /*  Allocate storage for row and column label arrays */
  rlbs = (char **)malloc(nr * sizeof (char *));
  clbs = (char **)malloc(nc * sizeof (char *));

  /*  Read column labels */
  for (i=0;i<nc;i++) {
    fscanf(fp,"%s",BUF);
    clbs[i] = (char *)malloc((1+strlen(BUF))*sizeof(char));
    strcpy(clbs[i],BUF);
  };

  /*  Allocate space for data */
  data=(int **)malloc(nr*sizeof(int *));
  /*  Read in row labels and data, row by row */
  for (i=0;i<nr;i++) {
    fscanf(fp,"%s",BUF);
    rlbs[i] = (char *)malloc((1+strlen(BUF))*sizeof(char));
    strcpy(rlbs[i],BUF);
    data[i]=(int *)malloc(nc*sizeof(int));
    for (j=0;j<nc;j++) {
      fscanf(fp,"%d",data[i]+j);
    };
  };

  /* Return a data structure with the information read in */
  return(make_datamat(data,nr,nc,rlbs,clbs));
}
