/*
# proc: read_basis - get basis vectors, typically eigenvectors, from file
# proc:              whose format is also used for covariance matrices.
# proc: write_basis - write basis vectors to a file.
# proc:
*/


#include <stdio.h>
#include <string.h>

/* xlen is the number of eigenvectors nEvect */
/* ylen is the length of the eigenvectors    */
/* ydim is the y dimension of the dap space  */
/*      that the eigenvectors are held in.   */

/* if ydim is given as zero no padding is performed */
/* positive ydim pads with zero out to the dap dimension */


read_basis(Evt_name, ylen, xlen, ydim, mean, stdv, base)
char	*Evt_name;
float   **base, **mean, **stdv;
int	*ylen, *xlen, ydim;
{
int	tdim, n, i;
FILE	*fp;
float	*ptr;

   if ((fp = fopen(Evt_name, "rb")) == NULL)
      fatalerr("read_basis", Evt_name, "fopen");

   if ((n = fread(xlen, sizeof(int  ),     1, fp)) != 1)
      fatalerr("read_basis", "num evects", "fread");
   if ((n = fread(ylen, sizeof(int  ),     1, fp)) != 1)
      fatalerr("read_basis", "len evects", "fread");


   if (((*mean) = (float *)calloc((*ylen), sizeof(float))) == NULL)
     syserr("read_basis", "space for mean", "calloc");
   if (((*stdv) = (float *)calloc((*ylen), sizeof(float))) == NULL)
     syserr("read_basis", "space for stdv", "calloc");

   if ((n = fread((*mean), sizeof(float), *ylen, fp)) != (*ylen))
      fatalerr("read_basis", "mean",       "fread");
   if ((n = fread((*stdv), sizeof(float), *ylen, fp)) != (*ylen))
      fatalerr("read_basis", "stdv",       "fread");


   tdim = (ydim == 0) ? (*ylen)  :  ( ydim);
   if (((*base) = (float *)calloc(tdim * (*xlen), sizeof(float))) == NULL)
     syserr("read_basis", "space for basis", "calloc");

   ptr = (*base);
   for (i = 0 ; i < *xlen; i++)
   {
      if ((n = fread(ptr, sizeof(float), (*ylen), fp)) != (*ylen))
         fatalerr("read_basis", "basis", "fread");
      ptr += tdim;
   }
   fclose(fp);
}

write_basis(Evt_name, ylen, xlen, ydim, mean, stdv, base)
char	*Evt_name;
float   *mean, *stdv, *base;
int	 ylen, xlen, ydim;
{
FILE	*fp;
int	 n, i;
float   *ptr;

  if ((fp = fopen(Evt_name, "wb")) == NULL)
    syserr("write_basis", Evt_name, "fopen");

  if ((n = fwrite(&xlen, sizeof(int  ),    1, fp)) != 1)
    syserr("write_basis", "num evects", "fwrite");
  if ((n = fwrite(&ylen, sizeof(int  ),    1, fp)) != 1)
    syserr("write_basis", "len evects", "fwrite");

  if ((n = fwrite(mean,  sizeof(float), ylen, fp)) != ylen)
    syserr("write_basis", "mean", "fwrite");
  if ((n = fwrite(stdv,  sizeof(float), ylen, fp)) != ylen)
    syserr("write_basis", "stdv", "fwrite");

  ptr = base;
  for (i = 0 ; i < xlen ; i++)
  {
     if ((n = fwrite(ptr, sizeof(float), ylen, fp)) != ylen)
        syserr("write_basis", "base", "fwrite");
     ptr += ydim;
  }
  fclose(fp);
}
