/* Nessus
 * Copyright (C) 1998, 1999, 2000, 2001 Renaud Deraison
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * In addition, as a special exception, Renaud Deraison
 * gives permission to link the code of this program with any
 * version of the OpenSSL library which is distributed under a
 * license identical to that listed in the included COPYING.OpenSSL
 * file, and distribute linked combinations including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * this file, you may extend this exception to your version of the
 * file, but you are not obligated to do so.  If you do not wish to
 * do so, delete this exception statement from your version.
 *
 * Modified by Axel Nennker axel@nennker.de 20020306
 * Removed unused variables and format string errors.
 */

/** @file
 *
 * Functions that deal with subset.
 * Subsets are the result- structures of queries against the Backend (written
 * in Pseudo-SQL, in the @ref data_mining.c module).
 *
 * @section subsetmanagement Subset Management Interface
 *
 * A subset contains the result of a query. It is made up of rows
 * and fields (that we call values).
 * To go from the current row to the next one, use the function
 * subset_next(). To extract value of the values (fields),
 * use subset_nth_value(). subset_value() is an alias for
 * subset_nth_value(subset, 0), ie: it returns the first field
 * (the only one which can not be NULL).
 */

#include <includes.h>
#include <stdarg.h>
#include "subset.h"

#ifndef MIN
#define MIN(x,y) ((x<y)?(x):(y))
#endif


struct subset *
subset_next (struct subset * subset)
{
 return subset->next;
}

char *
subset_nth_value (struct subset * subset, int n)
{
  if (n >= subset->num_fields)
      return NULL;
  return subset->data[n];
}

char *
subset_value (struct subset * subset)
{
  return subset_nth_value (subset, 0);
}


/**
 * @brief Prepends a new subset to a given one and adds the value \<value\>
 * @brief to it (to the new one).
 * 
 * @return New subset (whose next is the given subset).
 */
struct subset *
subset_add (struct subset * subset, char * value)
{
  struct subset * ret;

  ret = emalloc (sizeof(*ret));
  ret->next = subset;
  ret->data = emalloc (sizeof(char*)*2);
  ret->num_fields = 1;
  ret->data[0] = rmslashes (value);
  ret->data[1] = NULL;
  return ret;
}


/**
 * @brief Add another value (field) in the same row.
 * 
 * In contrast to subset_add, does not add a new row (if subset != NULL).
 * 
 * @param[in,out] subset The subset to add a value to (will be returned). Can be
 *                        NULL, then a new subset will be created.
 * 
 * @return Param subset with value added, or new one if subset == NULL.
 */
struct subset *
subset_add_again (struct subset * subset, char * value)
{
  struct subset * ret = subset;
  if (!subset)
    return subset_add (subset, value);
  ret->data = realloc (ret->data, (ret->num_fields+1)*sizeof(char*));
  ret->data[ret->num_fields] = rmslashes(value);
  ret->num_fields++;
  return ret;
}


/*-------------------------------------------------------------------------*
				Subset sorting
 --------------------------------------------------------------------------*/

/**
 * @brief (Merge-)Sort a subset list.
 *
 * @param list      The subset we want to sort.
 * @param n         Starting number of fields to sort.
 * @param m         Last number of the fields of the subset to sort.
 * @param cmp       Array of comparison functions. Each field can have its
 *                  own comparison function.
 *
 * @return Sorted subset.
 */
static struct subset *
merge_sort (struct subset * list, int n, int m, cmp_func_t* cmp)
{
 struct subset * p, * q, * e, *tail;
 int insize = 1, nmerges, i;
 register int psize = 0, qsize = 0;

 for(;;)
 {
  p = list;
  list = tail = NULL;
  nmerges = 0;

  while  (p)
  {
   nmerges++; 
   q = p;
   for(i=0;i<insize;i++)
    {
      psize++;
      q = q->next;
      if(!q)break;
    }

   qsize = insize;
   while((psize > 0) || ((qsize > 0) && q))
    {
      if(psize == 0)
        {
          e = q;
          q = q->next;
          qsize--;
        }
      else if(qsize == 0 || !q)
        {
          e = p;
          p = p->next;
          psize--;
        }
      else
        {
          int k;
          int p_smaller = 0;

          for (k=n; (k<=m) && (p_smaller==0); k++)
            {
              char * a = subset_nth_value (p, k);
              char * b = subset_nth_value (q, k);
              p_smaller = cmp[k-n] (a, b);
            }

          if (p_smaller >= 0)
            {
              e = p; p = p->next;psize--;
            }
          else
            {
              e = q; q = q->next;
              qsize --;
            }
        }

      if(tail)
        {
          tail->next = e;
        }
      else
        {
          list = e;
        }
      tail = e;
    } /* while((psize > 0) || ((qsize > 0) && q)) */
   p = q;
  }

   if (tail) tail->next = NULL;
   if (nmerges <= 1)
    {
      return list;
    }
   insize *= 2;
  }
}


/**
 * @brief (Merge-)Sort a subset list.
 *
 * @param subset      The subset we want to sort.
 * @param field_start Starting number of fields to sort.
 * @param field_end   Last number of the fields of the subset to sort.
 * @param cmp         Array of comparison functions. Each field can have its
 *                    own comparison function.
 *
 * @return Sorted subset.
 */
struct subset*
subset_sort (struct subset * subset, int field_start, int field_end,
             cmp_func_t* cmp)
{
  return merge_sort (subset, field_start, field_end, cmp);
}


/*------------------------------------------------------------------------*
 * Other subset-related utilities					  *
 *------------------------------------------------------------------------*/

/**
 * @brief Act as the uniq(1) unix utility -> two entries with the same
 * @brief fields are removed.
 *
 * This function compares the \<n\> first fields.
 * (hence, subset_uniq(s, 0) will remove all duplicates in a list).
 */
struct subset *
subset_uniq (struct subset * subset, int n)
{
  struct subset * s = subset;
  if (!s)
    return NULL;

  while(subset->next)
    {
      int i;
      int removed = 0;
      for (i=0;i<=n;i++)
        {
          if (subset->data[i]       &&
            subset->next->data[i] &&
            !strcmp(subset->data[i], subset->next->data[i])
            )
            {
              struct subset * old = subset->next;
              subset->next = subset->next->next;
              old->next = NULL;
              subset_free(old);
              removed++;
              break;
            }
        }

      if (!removed)
        subset = subset->next;
    }
  return s;
}



/**
 * @brief Tells us if the value \<value\> is already in the \<nth\> field of
 * @brief the current row.
 * 
 * @brief Returns the value if found, NULL otherwise.
 */
static char *
subset_in_nth (struct subset * subset, char * value, int n)
{
  while (subset)
    {
      if  (subset->data[n] && !strcmp(subset->data[n], value))
        return subset->data[n];
      subset = subset->next;
  }
  return NULL;
}


/**
 * @brief An alias for the above function, for subset_in_nth (0).
 */
char *
subset_in (struct subset * subset, char * value)
{
  return subset_in_nth(subset, value, 0);
}


/**
 * @brief Frees a subset and associate fields from memory.
 */
void
subset_free (struct subset * subset)
{
  while (subset)
    {
      struct subset * next = subset->next;
      while (subset->num_fields > 0)
        {
          efree(&subset->data[subset->num_fields-1]);
          subset->num_fields --;
        }
      efree (&subset->data);
      efree (&subset);
      subset = next;
    }
}


/**
 * @brief Dumps the content of a subset on screen (for debugging purposes only).
 */
int
subset_dump (struct subset * subset)
{
  int i;
  if (!subset)
    return(0);

  for (i=0;i<subset->num_fields;i++)
    {
      printf ("%s,", subset->data[i]);
    }
  printf ("\n");
  return subset_dump (subset->next);
}


/**
 * @brief Returns the number of items ("rows") in a subset.
 */
int
subset_size (struct subset * subset)
{
  int sz = 0;
  while (subset)
    {
      sz++;
      subset = subset->next;
    }
  return sz;
}
