/* i2cLEDhandle.c -- i2c SAA1064 LED functions */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h> 
#include <exec/types.h>
#include <proto/exec.h>
#include <proto/dos.h>

#include <proto/i2c.h>
#include <libraries/i2c.h>

#include "LED.h"

#include "i2cLEDhandle.h"

#define SAA1064 0x70    /* may be jumpered as 0x72, 0x74, 0x76, too */

struct Library *I2C_Base;

/*
void LibClose( struct Library **ppLib )
{
  if( *ppLib )
  {
    CloseLibrary( *ppLib );
    *ppLib = NULL;
  }
}

void CleanUp()
{                                                   do NOT use: crashes the system!!!
  SendLed( "    " );
  LibClose( &I2C_Base );
  LibClose( (struct Library **)&DOSBase );
}
*/


void CleanUp()
{
  SendLed( "    " );
  CloseLibrary( I2C_Base );
  CloseLibrary( (struct Library *) DOSBase );
}




struct Library* LibOpen( STRPTR strName, LONG lVersion )
{
    struct Library* pLib;

    pLib = OpenLibrary( strName, lVersion );
    if( !pLib )
    {
        printf( "Can't open %s", strName );
        printf( lVersion ? " V%ld+\n" : "\n", lVersion );
        return(NULL);
    }
    else return pLib;
}


BOOL setup_i2cLED(void)
{
    DOSBase  = NULL;
    I2C_Base = NULL;

    if ((I2C_Base = LibOpen( "i2c.library", 39 ) ) == NULL)
    {
#ifdef DEBUG
        printf("i2cLEDhandle.c: Couldn't open i2c.library !\n");
#endif
        return(FALSE);
    }

    if ( (DOSBase  = (struct DosLibrary *)LibOpen( "dos.library", 0 )) == NULL)
    {
#ifdef DEBUG
        printf("i2cLEDhandle.c: Couldn't open dos.library !\n");
#endif
        CloseLibrary( I2C_Base );
        return(FALSE);
    }

    return(TRUE);
}


void cleanup_i2cLED(void)
{
    CleanUp();
}


void LED_echo(char * msg)
{
    LONG lResult;

    if (msg == NULL) return;

    lResult = SendLed( msg );
    if( lResult )
    {
        printf( "I²C bus: error 0x%06lx, %s\n", lResult, I2CErrText( lResult ) );
    }
}

#ifdef TAPE_SCROLL
void TapeScroll(void)
{
    static int i=0;
    BYTE baBuf[][] = { { 0, 0x17, 0x00, 0x12, 0x08, 0x24 },     /* tape   */
                       { 0, 0x17, 0x00, 0xa0, 0x00, 0x09 },     /* scroll */
                       { 0, 0x17, 0x00, 0x09, 0x80, 0x02 } };   /* bytes  */

    LONG lResult;

    lResult = SendI2C( SAA1064, 6, baBuf[i] );
    if( (lResult & 0xFF) == 0 )
        printf( "I²C bus: error 0x%06lx, %s\n", lResult, I2CErrText( lResult ) );

    i += 1;
    if (i>2) i=0;

    return;
}

void TapeSeek(void)
{
    static int i=0;
    BYTE baBuf[][] = { { 0, 0x17, 0x6c, 0x79, 0x79, 0x75 },     /* SEEK  */
                       { 0, 0x19, 0, 0, 0, 0}   };              /* blink */

    LONG lResult;

    lResult = SendI2C( SAA1064, 6, baBuf[i] );
    if( (lResult & 0xFF) == 0 )
        printf( "I²C bus: error 0x%06lx, %s\n", lResult, I2CErrText( lResult ) );

    i += 1;
    if (i>1) i=0;

    return;
}
#endif
