#include <stdlib.h>
#include <ncurses.h>
#include <unistd.h>

#define DELAY 30000

void quit();
void draw_borders(WINDOW *screen);

int main(int argc, char *argv[]){
	int x=0, y=0;
	int max_y = 0, max_x = 0;
	int next_x = 0;
	int direction = 1;
	int keypress = 0;

	initscr(); // Initialize window
	noecho(); // Don't echo keypresses
	curs_set(FALSE); // No cursor
	nodelay(stdscr,1); // Stop getch from waiting. 
	//Global var 'stdscr' is created by the call to 'initscr()'
	getmaxyx(stdscr, max_y, max_x); //Get the max x/y of the screen
  
	WINDOW *main = newwin(max_y - 3, max_x, 0, 0);
	WINDOW *sub = newwin(3, max_x, max_y - 3, 0);
	draw_borders(main);
	draw_borders(sub);
 	
	 
	
	while(1) {
		getmaxyx(stdscr, max_y, max_x);
		keypress = getch(); // Listen for exit command
		clear(); // Clear screen of all  previous chars
		mvprintw(y, x, "o"); // Print our "ball" at the current xy position
		refresh();

		usleep(DELAY); // Shorter delay between movements

		next_x = x + direction;

		if (keypress == 'q') {
			quit();
		}

		if (next_x >= max_x || next_x < 0) {
			direction*= -1;
		}
		else {
			x+= direction;
		}
		mvwin(sub, 50, 50);
		wrefresh(sub);

//		x++; // Advance the ball to the right
	}

//	mvprintw(0, 0, "Hello, world!"); //Print some words in the spot 0,0
//	refresh(); // refresh window so words appear
	
//	sleep(1); //derp
//	endwin(); // Restore normal terminal behavior
}

void draw_borders(WINDOW *screen) {
  int x, y, i;

  getmaxyx(screen, y, x);

  // 4 corners
  mvwprintw(screen, 0, 0, "+");
  mvwprintw(screen, y - 1, 0, "+");
  mvwprintw(screen, 0, x - 1, "+");
  mvwprintw(screen, y - 1, x - 1, "+");

  // sides
  for (i = 1; i < (y - 1); i++) {
    mvwprintw(screen, i, 0, "|");
    mvwprintw(screen, i, x - 1, "|");
  }

  // top and bottom
  for (i = 1; i < (x - 1); i++) {
    mvwprintw(screen, 0, i, "-");
    mvwprintw(screen, y - 1, i, "-");
  }
}

void quit(){
	endwin();
	exit(0);
}