// -*-C++-*-
// This file is part of the gmod package
// Copyright (C) 1997 by Andrew J. Robinson

#include <stdlib.h>

#include "defines.h"
#include "structs.h"
#include "globals.h"

void
periodToNote (int period, int *note, int *pitchbend)
{
  int low = 0, middle = 0, high = NUM_PERIODS - 1;
  int diff, diffHigh, diffLow;

  *pitchbend = 0;

  if (period > periodTable[0])
    period = periodTable[0];
  else if (period < periodTable[NUM_PERIODS - 1])
    period = periodTable[NUM_PERIODS - 1];

  while (high >= low)
    {
      middle = (high + low) / 2;
      if (period == periodTable[middle])
	break;
      else if (period < periodTable[middle])
	low = middle + 1;
      else
	high = middle - 1;
    }

  if (period != periodTable[middle])
    {
      diffHigh = abs (period - periodTable[high]);
      diffLow = abs (period - periodTable[low]);

      if (diffLow < diffHigh)
	middle = low;
      else
	middle = high;

      if (period < periodTable[middle])
	diff = periodTable[middle] - periodTable[middle + 1];
      else
	diff = periodTable[middle - 1] - periodTable[middle];

      *pitchbend = (periodTable[middle] - period) * 100 / diff;
    }

  *note = middle + NOTE_BASE;
}
