#include <malloc.h>
#include <stdio.h>


void read_sal_input_file(), read_sal_file_content();


/*   read a saliency input file.
 *   input:
 *     i_file - input file name.
 *   output:
 *     &xs, &ys, &ks, &sals, &neighs - the arrays of x,y,k,sal,neigh values.
 *         (the area for these arrays is allocated inside.)
 *     &n - number of elements in the arrays.
 */
void
read_sal_input_file(i_file, xs, ys, ks, sals, neighs, n)
char *i_file;
int **xs, **ys, **ks, **neighs, *n;
double **sals;
{
  FILE *f_in;
  char line[100];
  int m_line = 100;
  int dim;

  printf(" Read file %s\n",i_file);

  f_in = fopen(i_file,"r");
  if (!f_in) {
    fprintf(stderr, "\n Couldn't open %s... aborting.\n", i_file);
    exit(3);
  }

  fgets(line, m_line, f_in);
  sscanf(line, "%*s %d %*s %*s %d", n, &dim);
  printf(" File contains %d points and %d columns\n", *n, dim);

  *xs = (int *) malloc(*n * sizeof(int));
  *ys = (int *) malloc(*n * sizeof(int));
  *ks = (int *) malloc(*n * sizeof(int));
  *sals = (double *) malloc(*n * sizeof(double));
  if (dim >= 5)
    *neighs = (int *) malloc(*n * sizeof(int));
  else
    *neighs = NULL;

  read_sal_file_content (f_in, *xs, *ys, *ks, *sals, *neighs, *n);

  fclose(f_in);
}

void
read_sal_file_content(f_in, xs, ys, ks, sals, neighs, n)
FILE *f_in;
int xs[], ys[], ks[], neighs[], n;
double sals[];
{
  char line[100];
  int m_line = 100;
  int x, y, k, neigh;
  double sal;
  int i, n_read;

  for (i=0; i<n; i++) {
    fgets(line, m_line, f_in);
    n_read = sscanf(line, "%d %d %d %lf %d", &x, &y, &k, &sal, &neigh);
    xs[i] = x;
    ys[i] = y;
    ks[i] = k;
    sals[i] = sal;
    if (neighs != NULL) {
      if (n_read >= 5)
	neighs[i] = neigh;
      else
	neighs[i] = -1;
    }
  }
}
