#ifdef __BORLANDC__
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <dos.h> // needed for delay()
#else
#include <msp430x14x.h>
#endif
#include <stdio.h>

// core includes

#include "basic.h"
#include "config.h"
#include "outfmt.h"
#include "eventq.h"
#include "cmdparse.h"
#include "cmdproc.h"
#include "version.h"
#include "gpio.h"
#include "watchdog.h"
#include "rtc.h"
#include "poll.h"
#include "sensor.h"
#include "timer.h"
#include "usart0.h"
#include "usart1.h"
#include "adc12.h"
#include "timerb.h"

// sensor includes
#ifdef CONFIG_INIT_SENSORS
#include "SHT11.h"
#include "sht11.h"
#include "M5535A.h"
#endif

#ifdef CONFIG_INCLUDE_GFI
#include "gfi.h"
#endif

#ifdef CONFIG_INCLUDE_KVH
#include "kvh.h"
#endif

extern void skelSensorInit(int);
void processCommand(void);

void hwInit(void) 
{
  int i;

  WDTCTL = WDTPW + WDTHOLD;             // Stop WDT
  BCSCTL1 &= ~XT2OFF;                   // XT2on
  
  do {
    IFG1 &= ~OFIFG;                     // Clear OSCFault flag
    for (i = 0xFF; i > 0; i--);         // Time for flag to set
  } while ((IFG1 & OFIFG) != 0);        // OSCFault flag still set?                

  BCSCTL2 |= SELM1 + SELS;              // MCLK = SMCLK = XT2 (safe)
  
}

void main(void)
{
  int dummy;
  
  // core init
  hwInit();
  gpioInit();
  eventqInit();
  usart0Init(false);
#ifdef CONFIG_INCLUDE_KVH
  usart1Init(false);
#endif
  cmdprocInit();
  cmdparseInit();
  outfmtInit();
  versionInit();
  watchdogInit();
  timerInit();
  sensorInit();
  
#ifdef CONFIG_INCLUDE_RTC
  rtcInit();
#endif
  
#ifdef CONFIG_INIT_SENSORS
  SHT11_Init();
  M5535A_Init();
#endif

#ifdef CONFIG_INCLUDE_KVH
  kvhInit();
#endif

#ifdef CONFIG_INCLUDE_GFI
  gfiInit();
#endif
   
#if defined(CONFIG_INCLUDE_KVH) || defined(CONFIG_INCLUDE_GFI)
  adc12Init();
  timerbInit();
  adc12ScanEnable();
#endif

  pollInit();

  outfmtSendPrompt();
  
  while(1) {
    eventqProcessEvents();
#ifdef __BORLANDC__
    processCommand();
#else
    // _BIS_SR(CPUOFF);                    // Enter LPM0 
    _NOP();
#endif

  }
}

#ifdef __BORLANDC__

static boolean sendLF = true;

void processCommand(void)
{
  char ch;
  if (kbhit() == true) {
    ch = getch();

    switch (ch) {
      case 'q':
        exit(0);
	break;
      case 'z':
        watchdog_timer();
	timerShow();
	break;
      default:
	break;
      }

    cmdprocAccumulateChExt(ch);
    if ((ch == 0x0d) && (sendLF == true)) {
      cmdprocAccumulateChExt(0x0a);
    }
  } // kbhit
}
#endif
