#include <stdio.h>

#include "adltypes.h"
#include "adlprog.h"
#include "builtins.h"
#include "vstring.h"
#include "adlrun.h"


void setdemon( void )
{
    assertargs( "$sdem", 1 );
    if( (ARG( 1 ) < 0) || (ARG( 1 ) > NUMROUT) ) {
	error( ADLERR_SDEM );
    }
    demons[ numd++ ] = ARG( 1 );
}


void deldemon( void )
{
    int16
	i;	/* Loop counter */

    assertargs( "$ddem", 1 );
    for( i = 0; i < numd; i++ ) {
	if( demons[ i ] == ARG( 1 ) ) {
	    break;
	}
    }
    if( i < numd ) {
	numd--;
	for( ; i < numd; i++ ) {
	    demons[ i ] = demons[ i + 1 ];
	}
    }
}


void setfuse( void )
{
    assertargs( "$sfus", 3 );	/* ($sfus actor rout nturns) */
    if( (ARG( 1 ) < 0) || (ARG( 1 ) > NUMOBJ) ) {
	error( ADLERR_SFUS_ACTOR );
    }
    if( (ARG( 2 ) < 0) || (ARG( 2 ) > NUMROUT) ) {
	error( ADLERR_SFUS_ROUT );
    }
    if( !routspace[ ARG( 2 ) ] ) {
	return;				/* Don't bother with a null fuse */
    }
    f_actors[ numf ] = ARG( 1 );
    fuses[ numf ] = ARG( 2 );
    ftimes[ numf++ ] = currturn + ARG( 3 );
}


void delfuse( int16 act, int16 which )
{
    int16
	i;	/* Loop counter */

    for( i = 0; i < numf; i++ ) {
	if( (fuses[ i ] == which) && (f_actors[ i ] == act) ) {
	    break;
	}
    }
    if( i < numf ) {
	numf--;
	for( ; i < numf; i++ ) {
	    fuses[ i ] = fuses[ i + 1 ];
	    ftimes[ i ] = ftimes[ i + 1 ];
	    f_actors[ i ] = f_actors[ i + 1 ];
	}
    }
}


void incturn( void )
{
    if( ARG( 0 ) == 2 ) {
	/* The programmer specified an increment */
	currturn += ARG( 1 );
    }
    else {
	/* The default increment is 1 */
	currturn++;
    }
    execfuses();
}


void retturn( void )
{
    RETVAL = currturn;
}


void doprompt( void )
{
    assertargs( "$prompt", 1 );
    if( (ARG( 1 ) < 0) || (ARG( 1 ) > NUMROUT) ) {
	error( ADLERR_PROMPT );
    }
    prompter = ARG( 1 );
}


void setactor( void )
{
    assertargs( "$actor", 3 );
    if( (ARG( 1 ) < 2) || (ARG( 1 ) > NUMOBJ) ) {
	error( ADLERR_ACTOR );
    }
    if( numact < NUMACT ) {
	actlist[ numact ].actor = ARG( 1 );
	actlist[ numact ].linebuf = actlist[ numact ].savebuf;
	actlist[ numact ].interact = ARG( 3 );
	if( ARG( 2 ) ) {
	    strncpy( actlist[ numact ].linebuf, virtstr( ARG( 2 ) ), SLEN - 1 );
	    actlist[ numact ].savebuf[ 79 ] = '\0';
	}
	else {
	    *actlist[ numact ].linebuf = '\0';
	}
	numact++;
    }
    else {
	fprintf( stderr, "Too many actors in actlist, ip = %ld.\n", ip );
	head_term();
	exit( -1 );
    }
}


void delactor( int16 n )
{
    int16
	i;	/* Loop counter */

    for( i = 0; i < numact; i++ ) {
	if( actlist[ i ].actor == n ) {
	    numact--;
	    for( ; i < numact; i++ ) {
		actlist[ i ].actor = actlist[ i + 1 ].actor;
		strncpy( actlist[ i ].savebuf, actlist[ i + 1 ].linebuf, SLEN );
		actlist[ i ].linebuf = actlist[ i ].savebuf;
	    }
	    return;
	}
    }
}

/*** EOF adlintrn.c ***/
