void mma_calibrate_offset( int16_t x, int16_t y, int16_t z )
{
    int16_t offset_x = ( 0 - x ) << 1;
    int16_t offset_y = ( 0 - y ) << 1;
    int16_t offset_z = ( 64 - z ) << 1;
    mma_write( MMA_XOFFL, offset_x & 0x00ff );
    mma_write( MMA_XOFFL + 1, ( offset_x & 0xff00 ) >> 8 );
    mma_write( MMA_YOFFL, offset_y & 0x00ff );
    mma_write( MMA_YOFFL + 1, ( offset_y & 0xff00 ) >> 8 );
    mma_write( MMA_ZOFFL, offset_z & 0x00ff );
    mma_write( MMA_ZOFFL + 1, ( offset_z & 0xff00 ) >> 8 );
}
void main(void){  
	u8 i,cmd, param[9],c;
	u16 temp; // TODO to be removed later on
	long l;
	signed int x, y, z;
	signed char x8, y8, z8;
	static unsigned char ledtrig;

    initCDC(); // JTR this function has been highly modified It no longer sets up CDC endpoints.

    init();			//setup the crystal, pins
    mma_init();

    usb_init(cdc_device_descriptor, cdc_config_descriptor, cdc_str_descs, USB_NUM_STRINGS); // TODO: Remove magic with macro
    usb_start();
    usbbufflush(); //flush USB input buffer system



    i = mma_read( MMA_I2CAD );
	//if((i&~0b10000000)!=0x1d)while(1);
    mma_write( MMA_I2CAD, 0x1d | MMA_I2CDIS_bit ); // disable I2C

    i = mma_read( MMA_CTL1 );
    mma_write( MMA_CTL1, i |= MMA_DFBW_bit ); // high output data rate

    mma_write( MMA_MCTL, 0b00000101 ); // 2g range; measurement mode

    //mma_calibrate_offset( 0, 0, 0 );


	//LEDs
	//PWM on cathode
	TRISAbits.TRISA0=0;
	LATAbits.LATA0=1; //enable cathode

	//setup LEDs
	LATB=0;
	TRISB=0;


	ledtrig=1; //only shut LED off once
    //	Never ending loop services each task in small increments
    while (1) {
        do {
            if (!TestUsbInterruptEnabled()) //JTR3 added
                USBDeviceTasks(); ////service USB tasks Guaranteed one pass in polling mode even when usb_device_state == CONFIGURED_STATE
            if ((usb_device_state < DEFAULT_STATE)) { // JTR2 no suspendControl available yet || (USBSuspendControl==1) ){
                //LedOff();
            } else if (usb_device_state < CONFIGURED_STATE) {
                //LedOn();
            }else if((ledtrig==1) && (usb_device_state == CONFIGURED_STATE)){
				//LedOff();
				ledtrig=0;
			}
        } while (usb_device_state < CONFIGURED_STATE);

		usbbufservice();//load any USB data into byte buffer

		if(usbbufgetbyte(&inByte) == 1){

			switch(inByte){//switch on the command
				case 0x00:
					WaitInReady();  //it's always ready, but this could be done better
					param[0]='B';
					param[1]='B';
					param[2]='I';
					param[3]='O';
					param[4]='1';
					putUnsignedCharArrayUsbUsart(param,5);
					break;
				case 0x01:
			    	mma_get_average8( 4, &x8, &y8, &z8 );
					param[0]=x8;
					param[1]=y8;
					param[2]=z8;
					WaitInReady();  //it's always ready, but this could be done better
					putUnsignedCharArrayUsbUsart(param,3);
					break;
				default: //error
					break;
			}
	
		}//if data
	}//while
//#endif

}//end main