/*
 *	TAPESTRY
 *		original idea from A.K.Dudeny's "Computer Recreation"
 *
 * 						(C) 1990 Waku Factory
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <egb.h>
#include <mos.h>

#define pset(x,y,col) putVRAMb( y*1024+x, col, 0x10c )
#define put(x,y,c) pset((x+w/2),(y+h/2),c ) 

#define fn( x,y ) ((x*x+y*y)*mag + pofs )
#define fp( x,y ) put((x),(y),fn((x),(y))%col)

static char name[] = "TAPESTRY  (C) 1990 Waku Factory" ;

char gwork[1540] ;
char mwork[4096] ;
short param[20] ;
int w, h, hw ;
int s ;

extern void putVRAMb() ;
extern int getopt() ;
extern char *optarg ;
extern void palette() ;

void main(ac,av)
int ac ;
char **av ;
{
	int mag,col,b,pal ;
	int pofs,dm ;
	
	col = 256 ;
	mag = 2 ;
	pal = 0 ;
	s = 0 ;
	pofs = clock() % 256 ;
	dm = 1 ;
	
	while( (b = getopt( ac,av, "c:b:ps:d:" ) ) != EOF ) 
	switch( b ) {
	case 'c':
		col = atoi( optarg ) ;
		break ;
	case 'b':
		mag = atoi( optarg ) ;
		break ;
	case 'p':
		pal = 1 ;
		break ;
	case 's':
		s = atoi( optarg ) ;
		break ;
	case 'd':
		dm = atoi( optarg ) ;
		break ;
	case '?':
		puts( "USAGE : tapest -c<colors> -b<dot> -s<speed> -d<divide> -p" ) ;
		exit( 0 ) ;
	}
	w = 640 / mag ;
	h = 480 / mag ;
	hw = h / 2 - 1 ;
	
	EGB_init( gwork, 1536 ) ;
	EGB_resolution( gwork , 0, 12 ) ;
	EGB_displayPage( gwork, 0, 3 ) ;
	EGB_displayStart(gwork, 2, mag, mag ) ;
	MOS_start( mwork, 4096 ) ;
	MOS_resolution( 0,12 ) ;
	MOS_disp( 0 ) ;
	if( pal ) 
		palette( 1, col-1, 0,360, 1.0,0.0, 1.0,0.0 );
	
	param[0] = 1;
	mag = dm ;
	for( ;;) {
		if( tap( mag, col, pofs ) < 0 )
			break ;
		if( (mag += dm ) >= 256 ) {
			mag = dm ;
			pofs++ ;
		}	
	}

	MOS_end() ;
}

void wait()
{
	int i, j ;
	
	for( i = 0 ; i < s ; i++ ) 
		for( j = 0 ; j < 50 ; j++ ) ;
}

int tap( mag, col,pofs ) 
int mag,col,pofs ;
{
	int x,y ;
	int i, c ;
	
	for( i = 1 ; i <= hw ; i++ ) {
		for( x = 0 ; x <= i ; x++ ) {
			fp( x, i ) ;
			fp( -x, i ) ;
			fp( x, -i ) ;
			fp( -x, -i ) ;
			wait() ;
		}
		for( y = i ; y >= 0 ; y-- ) {
			fp( i, y ) ;
			fp( -i, y ) ;
			fp( i, -y ) ;
			fp( -i, -y ) ;
			wait() ;
		}
		if( chkmos() ) return -1 ;
	}
	for( i = hw+1 ; i <= w/2-1 ; i++ ) {
		for( y = 0 ; y <= hw ; y++ ) {
			fp( i, y ) ;
			fp( -i, y ) ;
			fp( i, -y ) ;
			fp( -i, -y ) ;
			wait() ;
		}
		MOS_rdpos( &c,&x,&y ) ;
		if( chkmos() ) return -1 ;
	}
	return 0 ;
}

chkmos()
{
	int c,x,y ;
	MOS_rdpos( &c, &x, &y ) ;
	if( c == 0 ) return 0 ;
	if( c != 1 ) return 1 ;
	while( c == 1 ) {
		MOS_rdpos( &c, &x, &y ) ;
	}
	while( c != 1 ) {
		MOS_rdpos( &c, &x, &y ) ;
	}
	while( c == 1 ) {
		MOS_rdpos( &c, &x, &y ) ;
	}
	return 0 ;
}

