#include "NXCDefs.h"
#define BT_CONN 1
#define OUTBOX 5
#define INBOX 1
#define MAXSPEED 100

sub BTCheck(int conn){
  if (!BluetoothStatus(conn)==NO_ERR)
  {
    TextOut(5,LCD_LINE2,"Error");
    Wait(1000);
    Stop(true);
  }
}

task main()
{
  int ack, i, j, lf, rg, n;
  string s;
  BTCheck(BT_CONN);
  TextOut(10,LCD_LINE1,"Master sending");
  while(true)
  {
    i = MotorRotationCount(OUT_C);
    n = 0;
    lf = 0;
    rg = 0;
    while (ButtonCount(BTNCENTER, 0)%2 == 0)
    {
      n = n + 1;
      i = MotorRotationCount(OUT_C) - j;
      j = MotorRotationCount(OUT_C);
      if (ButtonPressed(BTNLEFT, 0) == true) lf = lf + 1; else lf = 0;
      if (ButtonPressed(BTNRIGHT, 0) == true) rg = rg + 1; else rg = 0;
      s = NumToStr(i) + " " + NumToStr(lf) + " " + NumToStr(rg);
      TextOut(0,LCD_LINE3,"              ");
      //TextOut(0,LCD_LINE4,"              ");
      TextOut(5,LCD_LINE3,s);
      //NumOut(5,LCD_LINE4,ButtonCount(BTNCENTER, 0));
      ack = 0;
      SendRemoteString(BT_CONN,OUTBOX,s)
      until(ack==0xFF)
      {
        until(ReceiveRemoteNumber(INBOX,true,ack) == NO_ERR);
      }
      Wait(40);
    }
    while (ButtonCount(BTNCENTER, 0)%2 == 1)
      {
        ack = 0;
        SendRemoteString(BT_CONN,OUTBOX,"Stop")
        until(ack==0xFF)
        {
          until(ReceiveRemoteNumber(INBOX,true,ack) == NO_ERR);
        }
        Wait(40);
      }
    }
  }
}