#include <stdio.h>
#include <ctype.h>
#include <typedefs.h>
#include <tiga.h>
#include <extend.h>

CONFIG far     config;
FONTINFO far   fontinfo;
AUX_CONFIG far *aux_config;
HOST_INIT far  hinit;

void *malloc();

void (*hcmds[4])() = { fopen,fread,fwrite,fclose };

#define copy(a,b) cp_ret(USER_CP(module | 0), 2, _STRING(a), _STRING(b) )

#define BUFFER 5000

main(argc,argv)
int argc;
char *argv[];
{
    int handle,tmp,module;
    unsigned long gptr;
    char *hptr;

    if (argc != 3)
    {
       printf("\nUsage: copyfile [source] [destination]\n");
       exit(1);
    }

    /*--------------------------------------------------------------*/
    /* Attempt to open the CD                                       */
    /*--------------------------------------------------------------*/
    if( tiga_set( CD_OPEN ) )
    {
        printf("Tiga CD is not installed\n");
        exit(1);
    }

    /*--------------------------------------------------------------*/
    /* Check to see that graphical interface is installed.          */
    /*--------------------------------------------------------------*/
    if( !set_videomode(TIGA,INIT) )
        error_cd_open("Set Videomode error",0);

    printf("\nTiGA System Responding...\n\n");

    /* attempt to install module */
    printf("Installing Rlm\n");
    if ((module = install_rlm("copy")) < 0 )
        error_cd_open("Couldn't install RLM",module);

    if( !(handle = gsph_alloc(BUFFER)) ) serror(1);
    gptr = gsph_deref( handle );

    if( !(hptr = (char *) malloc(BUFFER)) ) serror(1);

    hinit.host_buffer   = hptr;
    hinit.gsp_buffer    = gptr;
    hinit.buffer_size   = BUFFER;
    hinit.host_commands = &hcmds[0];
    hinit.command_count = 4;

    setup_hostcmd( &hinit );
    printf("Initialized!\n");

    copy( argv[1], argv[2] );

    gsph_free( handle );
    set_videomode(PREVIOUS,0);
    /*--------------------------------------------------------------*/
    /* Close the CD                                                 */
    /*--------------------------------------------------------------*/
    if( tiga_set( CD_CLOSE ) )
        printf("Error on CD close\n");
}

/*------------------------------------------------------------------*/
/* Routine to Abort with Error Message, and Closes the Tiga CD      */
/*------------------------------------------------------------------*/
error_cd_open(message,err)
char *message;
int err;
{
    printf("%s, Number < %05d >\n",message,err);
    set_videomode(PREVIOUS,0);
    tiga_set( CD_CLOSE );
    exit(1);
}

serror(err)
int err;
{
    switch(err)
    {
      case 1:
        error_cd_open("Initial block MemAlloc Error",0);
        break;
    }
}
