#include <errors.h>
#include <graph.h>
#include <iostream.h>
#include <process.h>
#include <strings.h>
#include <zstrings.h>
#include <time.h>
#include <unix.h>

static int x = 20;
static int y = 20;

void erase(void)
{
	setcolor(0);
	circle(x, y, 20);
}

void draw(void)
{
	unsigned short pixels[1600];
	struct timespec ts;

	ts.tv_sec = 0;
	ts.tv_nsec = 10000000L;

	/* Draw circle in top left corner */
	setcolor(65535);
	circle(x, y, 20);

	/* Show initial image */
	doupdate();
	return;
	
	/* Use default background color to erase image */
	setcolor(0);

	while (x + 40 < getmaxx()) {
		/* Give the computer a break */
		nanosleep(&ts, NULL);

		/* Read image before overwritting */
		getimage(40, 40, y - 20, x - 20, pixels);

		/* Clear current location */
		rectangle(x - 20, y - 20, x + 40, y + 40);

		/* Calculate new location */
		x += 5;
		y += 1;

		/* Write image to new location */
		putimage(40, 40, y - 20, x - 20, pixels);
		doupdate();
		return;
	}
	return;
	ts.tv_nsec = 15000000L;
	while (y + 40 < getmaxy()) {
		/* Give the computer a break */
		nanosleep(&ts, NULL);

		/* Read image before overwritting */
		getimage(40, 40, y, x, pixels);
		
		/* Clear current location */
		rectangle(x, y, x + 40, y + 40);

		/* Calculate new location */
		x -= 5;
		y += 5;

		/* Write image to new location */
		putimage(40, 40, y, x, pixels);
		doupdate();
	}
	ts.tv_nsec = 20000000L;
	while (y > 0 && x > 4) {
		/* Give the computer a break */
		nanosleep(&ts, NULL);

		/* Read image before overwritting */
		getimage(40, 40, y, x, pixels);
		
		/* Clear current location */
		rectangle(x, y, x + 40, y + 40);

		/* Calculate new location */
		x -= 5;
		y -= 1;

		/* Write image to new location */
		putimage(40, 40, y, x, pixels);
		doupdate();
	}
}

int main(void)
{
	int pid;
	struct window *win;

	/* Spawn a watchdog incase a segmentation fault occurs */
	pid = fork();
	if (pid < 0) {
		putz(2, "fork: ");
		put_line(2, strerror(-pid));
		return 1;
	}
	if (pid != 0) {
		waitpid(pid, NULL, 0);
		closegraph();
		putz(1, "Exiting\n");
		return 0;
	}
	if (initgraph(NULL) != 0)
		return 1;
	win = initwindow(1);
	if (win == NULL)
		return 1;
	setcurrentwindow(win);
	draw();
	closewindow(win);
	return 0;
}
