/*------------------------------------------------------- 
 * PCMデータバッファ
 *   巡回バッファ法でデータ管理
 *------------------------------------------------------- */
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "io.h"
#include "i2c-24fc1025.h"
#include "buff.h"
#include "snd-eeprom.h"
#include "sw.h"

static volatile uint8_t  buff[BUFF_SIZE]; 
static volatile uint8_t  nitems;
static volatile uint8_t  head;
static volatile uint8_t  tail;

/* バッファを初期化 */
void buff_init(void)
{
  nitems = 0;
  head = 0;
  tail = 0;
}

/* バッファが空か否か検査 */
int8_t buff_is_empty(void)
{
  INTERRUPT_DISABLE();
  int8_t is_empty = (nitems == 0);
  INTERRUPT_ENABLE();
  return is_empty;
}

/* バッファが満杯か否か検査 */
int8_t buff_is_full(void)
{
  INTERRUPT_DISABLE();
  int8_t is_full = (nitems == BUFF_SIZE);
  INTERRUPT_ENABLE();
  return is_full;
}

/* バッファにデータを挿入 */
void buff_put(uint8_t code)
{
  /* バッファに空が出るのを待つ */
  for (;;) {
    INTERRUPT_DISABLE();
    int8_t is_full = (nitems == BUFF_SIZE);
    INTERRUPT_ENABLE();
    if (!is_full) { /* バッファに空あり */
      break;
    }
  }
  /* バッファに挿入 */
  buff[head++] = code;
  if (head == BUFF_SIZE) {
    head = 0;
  }
  INTERRUPT_DISABLE();
  nitems++;
  INTERRUPT_ENABLE();
}

/* バッファよりデータを削除
 * （呼び出しは割込みハンドラからに限定: 割り込み禁止状態で実行） */
uint8_t buff_get_isr(void)
{
  uint8_t d = 0x80;
  if (nitems != 0) { /* バッファにデータあり */
    nitems--;
    d = buff[tail++];
    if (tail == BUFF_SIZE) {
      tail = 0;
    }
  }
  return d;
}
