#include <stdio.h>

#include "header.h"


float egy(float *x, int d)
{
  int kk;
  float e;
  
  e = 0;
  for (kk = 0; kk < d; kk++)
    e += x[kk];
  return (e);
}


int store_distribution(char *file,int Nmodes,int Ndim,float *c, float **mean, float **var)
{
  int i, j;
  float min, chk, tmp;
  int idx;
  FILE *outputfile;

  /* First reorganize to have the lowest energy gaussian first */
  min = 1.0e+30f;
  idx = 0;
  for (i = 0; i < Nmodes; i++) 
    {
      chk = egy(mean[i], Ndim);
      if (chk < min) 
	{
	  min = chk;
	  idx = i;
	}
    }
  tmp = c[idx];
  c[idx] = c[0];
  c[0] = tmp;
  for (i = 0; i < Ndim; i++) 
    {
      tmp = mean[idx][i];
      mean[idx][i] = mean[0][i];
      mean[0][i] = tmp;
      tmp = var[idx][i];
      var[idx][i] = var[0][i];
      var[0][i] = tmp;
    }

  if ((outputfile = fopen(file, "w")) == NULL)
    return (-1);

  fprintf(outputfile, "%d %d\n", Nmodes, Ndim);
  for (i = 0; i < Nmodes; ++i) 
    {
      fprintf(outputfile, "%e\n", c[i]);
      for (j = 0; j < Ndim; ++j)
	fprintf(outputfile, "%e ", mean[i][j]);
      fprintf(outputfile, "\n");
      for (j = 0; j < Ndim; ++j)
	fprintf(outputfile, "%e ", var[i][j]);
      fprintf(outputfile, "\n");
    }
  fclose(outputfile);
  return (0);
}


