/*
 * ball - balls bounce around
 */

#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#include <rtos.h>

#define MAXBALLS 400
#define SCALE 10
#define RANDOMNESS 2

#define MAXX ( 79 * SCALE )
#define MAXY ( 24 * SCALE )

typedef struct {
    BYTE color;
    WORD x, y;
    WORD deltax, deltay;
} ball_str;

ball_str balls[ MAXBALLS ];

void put_on_screen( int x, int y, WORD ch, WORD opt_attr )
{
    static WORD far *screen = 0xb8000000;
    WORD ofs;
    ofs = (y/SCALE) * 80 + (x/SCALE);
    screen[ ofs ] = (WORD)ch | ((WORD)opt_attr)<<8;
}


void ball( DWORD num )
{
    ball_str *b;
    int tempx, tempy;

    b = &balls[ num ];
    b->color = (num % 7) + 9;
    b->x = MAXX / 2;
    b->y = MAXY / 2;
    b->deltax = SCALE/2 - (rand() / ( RAND_MAX/SCALE/RANDOMNESS));
    b->deltay = SCALE/2 - (rand() / ( RAND_MAX/SCALE/RANDOMNESS));

    do {

        /* get new locaton */
        tempx = b->x + b->deltax;
        if ( (tempx < SCALE) || ( tempx > MAXX )) {
            tempx = b->x;
            b->deltax = -b->deltax;
        }

        tempy = b->y + b->deltay;
        if ( (tempy < SCALE) || ( tempy > MAXY )) {
            tempy = b->y;
            b->deltay = -b->deltay;
        }

        /* erase old and accept new */
        if ( (b->y != tempy ) || (b->x != tempx )) {
            put_on_screen( b->x, b->y, ' ', 0 );
            b->x = tempx;
            b->y = tempy;
        }

        /* draw the ball */
        put_on_screen( b->x, b->y, 9, b->color );
        rt_sleep( 10 );
    } while ( 1 );
}

void help( void )
{
    cprintf("BALL num    where num is in the range 1 to %u\r\n", MAXBALLS);
    cputs("Actual limit is based on how much memory is available\r\n");
    exit( 0 );
}
main(int argc, char **argv )
{
    int temp, max;
    DWORD dummy;
    char buf[128];

    rt_init( 100 );
    kdebug = 1;

    if ( argc < 2 ) help();

    max = atoi( argv[1] );
    if ( (max < 0) || (max >= MAXBALLS )) help();

    rt_timerfreq( 100 );
    for ( temp = 0 ; temp < max; ++temp )
        rt_newthread( &ball, temp, 1024, 0, "a ball");

    while ( 1 ) {
        rt_sleep( 1000 );
    }
}

