/*
 Esempio di uso device console
*/

#include <exec/types.h>
#include <intuition/intuition.h>
#include <devices/console.h>

#ifdef AZTEC_C
#include <functions.h>
#endif

#define BUFLEN 80

extern struct MsgPort *CreatePort();
extern struct IOStdReq *CreateStdIO();
extern void DeletePort(), DeleteStdIO(), CloseWindow();

struct IntuitionBase *IntuitionBase;
struct Window *ConsoleWindow, *OpenWindow();
struct MsgPort *ConWrtPort, *ConReadPort;
struct IOStdReq *ConWrtReq, *ConReadReq;

BOOL ConsoleOpen;
UBYTE InpBuffer[ BUFLEN ];

UBYTE Convert[ 2*BUFLEN+1 ];
UBYTE HexChar[] = "0123456789ABCDEF";

struct NewWindow MyWindow = {
 200,30,
 200,85,
 -1, -1,
 0,
 WINDOWDEPTH + WINDOWDRAG + WINDOWSIZING \
 + SMART_REFRESH + ACTIVATE,
 NULL,
 NULL,
 "Window di consolle",
 NULL,
 NULL,
 120, 50,
 640, 256,
 WBENCHSCREEN
};

void cleanup()
{
 if ( ConsoleOpen ) CloseDevice( ConWrtReq );
 if ( ConReadReq )  DeleteStdIO( ConReadReq );
 if ( ConWrtReq )  DeleteStdIO( ConWrtReq );
 if ( ConReadPort ) DeletePort( ConReadPort );
 if ( ConWrtPort )  DeletePort( ConWrtPort );
 if ( ConsoleWindow ) CloseWindow( ConsoleWindow );
 if ( IntuitionBase ) CloseLibrary( IntuitionBase );
 Exit( TRUE );
}

void Init()
{
 if ( ! ( IntuitionBase = (struct Library *) \
         OpenLibrary( "intuition.library", 33L ) ) )
   cleanup();
 
 if ( ! ( ConsoleWindow = OpenWindow( &MyWindow ) ) )
   cleanup();
  
 if ( ! ( ConWrtPort = CreatePort( 0, 0 ) ) )
   cleanup();
  
 if ( ! ( ConReadPort = CreatePort( 0, 0 ) ) )
   cleanup();
  
 if ( ! ( ConWrtReq = CreateStdIO( ConWrtPort ) ) )
   cleanup();
 if ( ! ( ConReadReq = CreateStdIO( ConReadPort ) ) )
   cleanup();
  
 ConWrtReq -> io_Data = (APTR) ConsoleWindow;
 ConWrtReq -> io_Length = sizeof( struct Window );
 
 if ( OpenDevice( "console.device", 0, ConWrtReq, 0 ) != 0 )
   cleanup();
 else
   ConsoleOpen = TRUE;
  
 ConReadReq -> io_Device = ConWrtReq -> io_Device;
 ConReadReq -> io_Unit = ConWrtReq -> io_Unit;
 return;
}

ULONG ReadConsole( buffer, buflen )
STRPTR buffer;
ULONG buflen;
{
 ConReadReq -> io_Data = (APTR) buffer;
 ConReadReq -> io_Length = buflen;
 ConReadReq -> io_Command = CMD_READ;
 
 DoIO( ConReadReq );
 
 return( ConReadReq -> io_Actual );

}

void WrtConsole( string, length )
STRPTR string;
ULONG length;
{
 ConWrtReq -> io_Data = (APTR) string;
 ConWrtReq -> io_Length = length;
 ConWrtReq -> io_Command = CMD_WRITE;
 
 DoIO( ConWrtReq );
}

void main()
{
 ULONG n, i, j;
 UBYTE c;

 Init();
 
 do {
   n = ReadConsole( InpBuffer, BUFLEN );

  WrtConsole( InpBuffer, n );

  for ( i = 0, j = 0 ; i < n ; i++ )
  {
    c = InpBuffer[ i ];
    Convert[ j++ ] = HexChar[ c >> 4 ];
    Convert[ j++ ] = HexChar[ c & 0x0F ];
  }
  
  Convert[ j++ ] = NULL;
  printf( "%s ", Convert );
  
 } while ( c != '\003' ); /* CTRL-C */
 printf( "\n" );
 cleanup();
}
