#include <stdint.h>
#include "pit.h"
#include "io.h"

#define PIT_COUNTER0      0x40
#define PIT_CMD           0x43
#define PIT_CMD_BINARY    0x00
#define PIT_CMD_BCD       0x01
#define PIT_CMD_MODE0     0x00
#define PIT_CMD_MODE1     0x02
#define PIT_CMD_MODE2     0x04
#define PIT_CMD_MODE3     0x06
#define PIT_CMD_MODE4     0x08
#define PIT_CMD_MODE5     0x0A
#define PIT_CMD_LATCH     0x00
#define PIT_CMD_RW_LOW    0x10
#define PIT_CMD_RW_HI     0x20
#define PIT_CMD_RW_BOTH   0x30
#define PIT_CMD_COUNTER0  0x00
#define PIT_CMD_COUNTER1  0x40
#define PIT_CMD_COUNTER2  0x80
#define PIT_CMD_READBACK  0xC0

#define PIT_FREQ 1193182

volatile uint32_t PIT_TICKS;

void pit_init(void) {
  uint32_t hz = 1000;
  uint32_t div = PIT_FREQ / hz;
  io_out8(PIT_CMD, PIT_CMD_BINARY | PIT_CMD_MODE3 | PIT_CMD_RW_BOTH | PIT_CMD_COUNTER0);
  io_out8(PIT_COUNTER0, div);
  io_out8(PIT_COUNTER0, div >> 8);
}

void pit_wait(uint32_t ms) {
  uint32_t now = PIT_TICKS;
  ++ms;
  while (PIT_TICKS - now < ms);
}
