#include "GLOBAL.H"
#include "USB.H"
#include "MOUSE.H"


//-----USB.C-----//
extern EP0INFO Ep0;

MOUSE Mouse;


void Initial_MS( void )
  { Mouse.Act = CLR;
    Mouse.ChangeFlag = CLR;
  }


void MS_Key_Send( void )
  { while( Mouse.Busy == SET );                  // Wait " USB Tx " complete
  
    EA = CLR;                                    // Disable all interrupt 
    USB[EPINDEX] = EP2;                          // Swap to EP2
    
    Mouse.Tmp = 0;
    while( Mouse.Tmp < 4 )
      { USB[TXDAT] = Mouse.Data[Mouse.Tmp];      // Fill the Mouse data to USB fifo
        Mouse.Tmp++;
      }
    Mouse.Busy = SET;                            // Set Busy flag and Clear by USB EP2 ISR
    USB[TXCNT] = Mouse.Tmp;
    
    USB[EPINDEX] = EP0;                          // Swap to EP1
    EA = SET;                                    // Enable all interrupt 
    
    while( Mouse.Busy == SET );                  // Wait " USB Tx " complete
  }


void MS_Key_Release( void )
  { while( Mouse.Busy == SET );                  // Wait " USB Tx " complete
  
    EA = CLR;                                    // Disable all interrupt 
    USB[EPINDEX] = EP2;                          // Swap to EP2
    
    Mouse.Tmp = 0;
    while( Mouse.Tmp < 4 )
      { USB[TXDAT] = 0x00;                       // Fill Release data to USB fifo
        Mouse.Tmp++;
      }
    Mouse.Busy = SET;                            // Set Busy flag and Clear by USB EP2 ISR
    USB[TXCNT] = Mouse.Tmp;
    
    USB[EPINDEX] = EP0;                          // Swap to EP1
    EA = SET;                                    // Enable all interrupt 
  }


void MS_Send_Key( void )
  { if ( Ep0.EmuOk == CLR )
      return;
    
    if ( Mouse.Act == CLR )
      return;    

// To do
// Mouse.Data[0],Bit0 = Left Button , Bit1 = Right Button , Bit2 = Middle Button , Others is Reserve                                                 
// Mouse.Data[1] = X Movement
// Mouse.Data[2] = Y Movement
// Mouse.Data[3] = Z Movement

    if ( Mouse.ChangeFlag )                      // This flag is set by user application
      { Mouse.ChangeFlag = CLR;
      	MS_Key_Send();                           // and Mouse.Data[x] should be fill too.
      	MS_Key_Release();
      }
  }