/*
 * crossers_world.c - Auxillary routines for the river-crossing problem
 */

#include <stdio.h>
#include <unistd.h>
#include "crossers_world.h"

#define WEST_COLUMN	10
#define EAST_COLUMN	70
#define STEPS_ACROSS	15
#define STEP_COLUMNS	( ( EAST_COLUMN - WEST_COLUMN ) / STEPS_ACROSS )
#define STEP_TIME	100000L
#define MIN_WANDER	4
#define MAX_WANDER	10

static void position( int row, int col )
{
    printf( "\033[%d;%dH", row, col ); 
}

static void draw_self( int n, char direction )
{
    printf( ( direction == 'E' ) ? "%d>\n" : "<%d\n", n );
}

void create_world( void )
{ 
    int i;
     
    position( 1, 1 );
    printf( "\033[J" );
    
    for ( i = 0; i <= NUM_CROSSERS; i ++ )
    {
	position( i + 1, WEST_COLUMN + 4 );
	printf( "*" );
	position( i + 1, EAST_COLUMN - 2 );
	printf( "*\n" );
    }
    position( NUM_CROSSERS + 2, WEST_COLUMN + 4 );
    printf( "*" );
    for ( i = WEST_COLUMN + 5; i <= EAST_COLUMN - 2; i ++ )
    {
	printf( "*" );
    }
    printf( "\n" );
}


void arrive_at_bank( int n, char direction )
{ 
    position( n + 1, ( direction == 'E' ) ? WEST_COLUMN : EAST_COLUMN );
    draw_self( n, direction );
}

void cross_river( int n, char direction )
{ 
    int current_column;
    int i;
    
    current_column = ( direction == 'E' ) ? WEST_COLUMN : EAST_COLUMN;
    position( n + 1, current_column );
    printf( "   " );
    position( NUM_CROSSERS + 1, current_column );
    draw_self( n, direction );
    for ( i = 1; i <= STEPS_ACROSS; i ++ )
    {
        usleep( STEP_TIME );
	position( NUM_CROSSERS + 1, current_column );
	printf( "   " );
	current_column += ( direction == 'E' ) ? STEP_COLUMNS : -STEP_COLUMNS;
	position( NUM_CROSSERS + 1, current_column );
	draw_self( n, direction );
    }
    usleep( STEP_TIME );
    position( NUM_CROSSERS + 1, current_column );
    printf( "   \n" );
}
	 

void enjoy_scenery( int n, char direction )
{
    sleep( MIN_WANDER + random() % ( MAX_WANDER - MIN_WANDER + 1 ) );
}
