/*
 * Title: sort.c
 * Author: Jed Marti KI7NNP
 * Description: Insertion sort for result optimization. Used by both uni- and multi-process
 * Revision History: (Created Sat Jan 28 11:00:31 2023)
 *   Sun Feb 26 18:16:00 2023 - Add wire size back in.
 *   Sun Dec  3 11:55:17 2023 - Allow generic equations.
 */


#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "equations.h"
#include "indequ.h"


static uint8_t sameCoefficients(result *l, result *n)
{
#define X(nme) (l->nme != n->nme) ||
  if (
      VARS
       0) return 0;
#undef X
  return 1;
}



result *sortgen(result *l, result *n)
/*     An insertion sort of a result into a list with values in ascending order. Recursive version
 *   that reconstructs the list. If the generation size gets too big (100's), then the stack will
 *   overflow with dire results.
 * Parameters:
 *   l: Must already be a sorted list or NULL.
 *   n: The new result to add to the list.
 */
{
  ASSERT(n != NULL);

  // Degenerate case - empty list or new element goes at the end of the list.
  n->next = NULL;
  if (l == NULL) return n;

  // Our new one is less than the old one so put it on the head of the list.
  if (n->goodness < l->goodness)
  {
    n->next = l;
    return n;
  }

  // If the goodness is the same and the values the same, then punt. The library list keeps track
  // of the low resolution values. The best list might become saturated with a bunch of them
  // the same from different high resolution tests. So don't save them.
  else if (n->goodness == l->goodness && sameCoefficients(l, n)) return l;

  // Go farther down the list if those above fail.
  l->next = sortgen(l->next, n);
  return l;
}



// EOF
