#include <time.h>
#include <stralloc.h>

// round function because apparently C doesn't do this by itself?
static int _round(double n) {
  return (n >= 0) ? (int)(n+0.5) : (int)(n-0.5);
}

// calculate the fuzzy minute
static int _fuzzyMinute(int m, int s) {
  return 5 * _round((m + (s / 60.0)) / 5);
}

// return value => time string
static char* _textTime(int fM) {
  if (fM == 0)
    return " o'clock";
  if (fM <= 30)
    return " past ";
  return " to ";
}


int main() {
  time_t rawtime;
  struct tm* timeinfo;
  time(&rawtime);
  timeinfo = localtime(&rawtime);

  int h = timeinfo->tm_hour;
  int m = timeinfo->tm_min;
  int s = timeinfo->tm_sec;

  int hours = h;
  int fuzzyMinute = _fuzzyMinute(m,s);
  if (fuzzyMinute > 30)
    hours++;
  fuzzyMinute %= 60;
  hours = 1 + ((hours - 1) % 12);

  char* textTime = _textTime(fuzzyMinute);
  char* textMins[] = {"five", "ten", "quarter", "twenty", "twentyfive", "half", "twentyfive", "twenty", "quarter", "ten", "five", "nothing"};
  char* textMin = textMins[(int)(fuzzyMinute / 5 - 1)];
  char* textHours[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"};
  char* textHour = textHours[(int)(hours - 1)];

  stralloc out = {0};
  if (fuzzyMinute == 0) {
    stralloc_copys(&out, textHour);
    stralloc_cats(&out, textTime);
  } else {
    stralloc_copys(&out, textMin);
    stralloc_cats(&out, textTime);
    stralloc_cats(&out, textHour);
  }
  write(1, out.s, out.len);
}
