package nxm.sys.lib;

/**
  A sorted list class (used in primitive peakpick)

  @author Ken Smith
 */
public class Sorter {

  /** size of sorted list */
  public int size;

  private float key_vector[];
  private float val_vector[];
  private static final float invalid = -1.E20f;

  /** Constructor
   *  @param size size of sorted list
   */
  public Sorter (int size) {
    this.size = size;
    key_vector = new float[size];
    val_vector = new float[size];
  }

  /** Initialize arrays (Java initialization values aren't appropriate).*/
  public void init() {
    for (int i = 0; i < size; i++) {
      key_vector[i] = invalid;
      val_vector[i] = invalid;
    }
  }

  /** Add an entry into the sorted list.
   *  @param key key for entry
   *  @param val vaklue of entry
   */
  public void add (float key, float val) {
    int i;

    // Find where to insert the value
    i = 0;
    while ( (key_vector[i] != invalid) && (key < key_vector[i]) ) {
      i++;
      if (i >= size) return;
    }

    // Move the array up to accommodate the new entry
    for (int j=size-1; j>i; j--) {
      key_vector[j] = key_vector[j-1];
      val_vector[j] = val_vector[j-1];
    }
    key_vector[i] = key;
    val_vector[i] = val;

    return;
  }

  /** Retrieve a specified entry, with default if not found.
      @param index index of entry
      @param defVal default value
      @return specified entry  */
  public float getKey (int index, float defVal) {
    if (key_vector[index] != invalid) {
      return key_vector[index];
    } else {
      return defVal;
    }
  }

  /** Retrieve a specified value, with default if not found.
  @param index index of value
  @param defVal default value
  @return specified value  */
  public float getVal (int index, float defVal) {
    if (val_vector[index] != invalid) {
      return val_vector[index];
    } else {
      return defVal;
    }
  }
}
