#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <curses.h>

int maxy, maxx;

#define pdebug(fmt...) //{ char out[256]; sprintf(out, fmt); fprintf(stderr, "%s\n", out); }

/*
 *
 * Main
 *
 */

int
main() {
//  srandom(time(NULL));
  
  initscr();
  cbreak();
  noecho();
  nonl();
  intrflush(stdscr, FALSE);
  keypad(stdscr, TRUE);
  nodelay(stdscr, TRUE);
  leaveok(stdscr, TRUE);
  curs_set(0);
  refresh();
  getmaxyx(stdscr, maxy, maxx);
 
  while (1) {
    static int inkey, oldinkey, sleep, beepch, bg = 1, fg = 2, force_redraw, freq;

    pdebug("-- main loop");

    sleep = 0;
    inkey = getch();
    oldinkey = inkey;
    beepch = force_redraw = 0;

    switch (inkey) {
      case KEY_F(1):	goto bye;
			
      case KEY_F(2):	printf("\33[11;10]\33[10;25]\7"); fflush(stdout);
			break;

      case KEY_F(3):	bg = ! bg;
			force_redraw = 1;
			break;
			
      case KEY_F(4):	fg = ! fg;
			force_redraw = 1;
			break;
			
      case ERR:		sleep = 1;
			break;
			
      default:		freq = beepch = inkey;
			break;
    }

    pdebug("checks");

    while (inkey != ERR && inkey == oldinkey) {
      pdebug("ink %d, old %d", inkey, oldinkey);
      oldinkey = inkey;
      inkey = getch();
    }
    if (oldinkey != inkey)
      ungetch(inkey);
    pdebug(" ink %d, old %d", inkey, oldinkey);
    
    pdebug("eoloop");

    if (beepch)
      printf("\33[11;1999]\33[10;%d]\7", freq * 5); fflush(stdout);

    if (beepch || force_redraw) {
      char status[80]; int y, x;
      
      for (y = 0; y < maxy; y++)
        for (x = 0; x < maxx; x++)
          mvaddch(y, x, bg? freq: ' ');
      
      if (fg) {
        sprintf(status, "-- Frequency %d --", freq * 5);
        attrset(A_BOLD);
        mvaddstr(maxy / 2, maxx / 2 - strlen(status) / 2, status);
        attrset(0);
      }
    }

    if (! beepch)
      usleep(10000);
    
    refresh();
  }

bye:
  pdebug("bye");
  refresh();
  endwin();
  printf("\33[11;100]\33[10;750]"); fflush(stdout);

  return 0;
}
