#include "datamat.h"

static char *find_valsid = "$Id";

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


    find_vals.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




   This subroutine takes a block clustering data matrix structure
   (defined in datamat.h) and computes a list of values in the specified
   column, returning to the calling routine a structure which includes
   the values and their number.

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

extern void bubsort();  /* Simple bubblesorting routine */

struct categval *find_vals(dat,icol)
struct datamat *dat;int icol;
{
  int i,j,*temp,*tempvals; struct categval *retval;

/*  Allocate temp space for the column, copy its contents and sort them*/
  temp = (int *)malloc(dat->nrows * sizeof(int));
  for (i=0;i<dat->nrows;i++) temp[i]=dat->data[i][icol];
  bubsort(temp,dat->nrows);

/*  Find the number of different values by scanning the sorted column */
  tempvals = (int *)malloc(dat->nrows * sizeof(int));
  tempvals[0] = temp[0];j=0;
  for (i=1;i<dat->nrows;i++)
    if (temp[i] != tempvals[j]) tempvals[++j]=temp[i];

/*  Allocate the structure for the return, and return an array with */
/*  length equal to the number of different values.                 */
    
  retval = (struct categval *)malloc(sizeof(struct categval));
  retval->vals = (int *)malloc((j+1) * sizeof(int));
  retval->nvals = j+1;
  for (i=0;i<=j;i++) retval->vals[i] = tempvals[i];

/*  Cleanup and return */
  realloc(temp); realloc(tempvals);
  return(retval);
}
