/*  :ts=8
 * stars.c:  An attmept to fight boredom (yet again).
 * by Leo L. Schwab   8606.30
 */

#include <exec/types.h>
#include <intuition/intuition.h>

#define NSTARS		64

extern void *OpenLibrary(), *OpenScreen(), *OpenWindow(), *GetMsg();
extern short rnd();

long *IntuitionBase, *GfxBase;

struct NewScreen scrdef = {
	0, 0, 320, 200,
	4,		/*  # planes  */
	-1, -1,
	NULL,
	CUSTOMSCREEN,
	NULL, NULL, NULL, NULL
};

struct NewWindow windef = {
	0, 0, 320, 200,
	-1, -1,
	CLOSEWINDOW,
	WINDOWCLOSE,
	NULL, NULL, NULL, NULL, NULL,
	0, 0, 0, 0,
	CUSTOMSCREEN
};

struct Window *win;
struct Screen *scr;
struct RastPort *rp;
short x[NSTARS], y[NSTARS], z[NSTARS];
short xo[NSTARS], yo[NSTARS];


main (ac, av)
char *av[];
int ac;
{
	long xs, ys;
	long *msg;
	short magic;
	register short i, inc;

	if (ac > 1)
		magic = atoi (av[1]);
	else
		magic = 256;

	if (ac > 2)
		inc = atoi (av[2]);
	else
		inc = 3;

	openstuff ();
	rnd (-5286);
	SetRast (rp, 0L);
	for (xs=0; xs<16; xs++)
		SetRGB4 (&(scr -> ViewPort), xs, xs, xs, xs);

	for (i=0; i<NSTARS; i++)
		mkpoint (i);

	FOREVER {
		for (i=0; i<NSTARS; i++) {
			if ((z[i] -= inc) <= 0)
				mkpoint (i);
			xs = x[i] * magic / z[i] + 160;
			ys = y[i] * magic / z[i] + 100;
			SetAPen (rp, 0L);
			WritePixel (rp, (long) xo[i], (long) yo[i]);
			if (xs < 0 || xs > 319 || ys < 0 || ys > 199)
				mkpoint (i);
			else {
				SetAPen (rp, (long) (256-z[i] >> 4));
				WritePixel (rp, xs, ys);
				xo[i] = xs;  yo[i] = ys;
			}
		}
		if (msg = GetMsg (win -> UserPort)) {
			ReplyMsg (msg);
			break;
		}
	}

	closestuff ();
}

mkpoint (i)
register short i;
{
	x[i] = rnd (256) - 128;
	y[i] = rnd (150) - 75;
	z[i] = 255;
}

openstuff ()
{
	if (!(IntuitionBase = OpenLibrary ("intuition.library", 0L))) {
		printf ("Intuition open failed.\n");
		die ();
	}

	if (!(GfxBase = OpenLibrary ("graphics.library", 0L))) {
		printf ("graphics open failed.\n");
		die ();
	}

	if (!(scr = OpenScreen (&scrdef))) {
		printf ("Can't open screen.\n");
		die ();
	}

	windef.Screen = scr;
	if (!(win = OpenWindow (&windef))) {
		printf ("Window painted shut.\n");
		die ();
	}
	rp = &(scr -> RastPort);
}

closestuff ()
{
	if (win)		CloseWindow  (win);
	if (scr)		CloseScreen  (scr);
	if (GfxBase)		CloseLibrary (GfxBase);
	if (IntuitionBase)	CloseLibrary (IntuitionBase);
}

die ()
{
	closestuff ();
	exit (-1);
}
