/*
 * selector.c
 */

#include <wms.h>
#include "selector.h"


/**********************************************************************
 * Functions
 **********************************************************************/
void selector_read(Selector *sel, UInt8 *prev, UInt8 *data, UInt8 *next,
		   int dataW, Rnd *rnd) {
  int  i, choice;
  UInt8 val;

  sel->numEdge = sel->numTurb = sel->numLimit = 0;
  for (i = 1;  i < dataW - 1;  ++i) {
    val = data[i];
    if (val == base_limit) {
      ++sel->numLimit;
    } else {
      sel->numEdge += ((data[i-1] == base_limit) ||
		       (data[i+1] == base_limit) ||
		       (prev[i] == base_limit) ||
		       (next[i] == base_limit));
      sel->numTurb += ((((val - data[i+1] + 2) & (base_limit - 1)) > 4) ||
		       (((val - data[i-1] + 2) & (base_limit - 1)) > 4) ||
		       (((val - prev[i] + 2) & (base_limit - 1)) > 4) ||
		       (((val - next[i] + 2) & (base_limit - 1)) > 4));
    }
  }
  if (sel->numEdge > 0) {
    choice = rnd_int(rnd) % sel->numEdge;
    for (i = 1;  choice >= 0;  ++i) {
      choice -= ((data[i] != base_limit) && ((data[i-1] == base_limit) ||
					     (data[i+1] == base_limit) ||
					     (prev[i] == base_limit) ||
					     (next[i] == base_limit)));
    }
    sel->edgeSel = i - 1;
  }
  if (sel->numTurb > 0) {
    choice = rnd_int(rnd) % sel->numTurb;
    for (i = 1;  choice >= 0;  ++i) {
      val = data[i];
      choice -= ((val != base_limit) &&
		 ((((val - data[i+1] + 2) & (base_limit - 1)) > 4) ||
		  (((val - data[i-1] + 2) & (base_limit - 1)) > 4) ||
		  (((val - prev[i] + 2) & (base_limit - 1)) > 4) ||
		  (((val - next[i] + 2) & (base_limit - 1)) > 4)));
    }
    sel->turbSel = i - 1;
  }
}


void selector_pick(int *x, int *y, Selector *sels, int numSels, Rnd *rnd) {
  int totalTurbs = 0, totalEdges = 0, totalLimits = 0;
  int  i, choice;

  for (i = 0;  i < numSels;  ++i) {
    totalTurbs += sels[i].numTurb;
    totalEdges += sels[i].numEdge;
    totalLimits += sels[i].numLimit;
  }
  if (totalTurbs == 0) {
    printf("NO TURBS!\n");
    *x >>= 1;
    *y >>= 1;
    return;
  }
  if ((rnd_int(rnd) % ((*x - 2) * (*y - 2))) < totalLimits) {
    choice = rnd_int(rnd) % totalEdges;
    for (i = 0;  choice >= sels[i].numEdge;  ++i)
      choice -= sels[i].numEdge;
    *x = sels[i].edgeSel;
    *y = i + 1;
  } else {
    choice = rnd_int(rnd) % totalTurbs;
    for (i = 0;  choice >= sels[i].numTurb;  ++i)
      choice -= sels[i].numTurb;
    *x = sels[i].turbSel;
    *y = i + 1;
  }
}
