#if 0

#include "SFBSerial.h"
#include "SFBReflex.h"
#include "SFBWiring.h"          /* For delay() */
#include "SFBEeprom.h"          /* For eeprom_startup_initialization */
#include "stdio.h"              /* For printf */
#include <stdlib.h>             /* For exit() */
#include <unistd.h>             /* For read */
#include <fcntl.h>              /* For fnctl */
#include <string.h>             /* For strlen */
#include <errno.h>              /* For errno */

extern void startupEarlyInits(); // In startup.cpp
extern void startupLateInits(); // In startup.cpp

static bool stdinBlocking = true;
static void setStdinBlocking(bool set); 

static void quit(int code) {
  if (!stdinBlocking) setStdinBlocking(true); // Clean up behind ourselves
  exit(code);
}

static void dbgMsg(const char * m, int err=0) {
  if (err==0) fprintf(stderr,"%s\n",m);
  else        fprintf(stderr,"%s: %s\n",m,strerror(err));
}

static void die(const char * m, int err = 0, int code = 1) {
  dbgMsg(m,err);
  quit(code);
}

static void setStdinBlocking(bool set) {
  stdinBlocking = set;

  int flags = fcntl(0, F_GETFL);
  if (set)  flags &= ~O_NONBLOCK;
  else      flags |= O_NONBLOCK;

  if (fcntl(0, F_SETFL, flags) != 0) 
    die("stdinBlock: Unable to set stdin blocking",errno);
}

/*
 * 'open_serial(const char * path)' - Open serial on device path
 *
 * Returns the file descriptor on success or -1 on error.
 */
int open_serial(const char * path) {
  int fd = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1) {
    perror("open_serial: Unable to open");
    return -1;
  }
  return fd;
}

static char * serialPath = 0;

extern void eeprom_set_directoryImpl(const char * dirPath);

static void startup() {
  startupLateInits();

  int tryFD = open_serial(serialPath);
  API_ASSERT_GREATER_EQUAL(tryFD,0);
  SouthFace.getHWSerial().setFD(tryFD);

  SouthFace.begin(9600,true);
  setStdinBlocking(false);

  NorthFace.begin(38400,false); // Baud rate is actually phony - just want conscious control
  NorthFace.getHWSerial().setFD(0);
  NorthFace.getHWSerial().setOutputFD(1);

}

void NorthQuitHandler(u8 * packet) {
  if (zPacketPrefix(packet,"quit"))
    quit(0);
  Body.triggerUp();
}

void packetBridge(u8 * packet) {
  u32 from = Body.source();    // Get source of packet
  for (u32 face = NORTH; face <= WEST; ++face) {
    if (face==from) continue;   // Don't send back to where it came from
    Faces[face].println(packet,packetLength(packet)); // Otherwise forward it on
  }
}

int main(int argc, char ** argv) {
  if (argc != 2)
    quit(1);

  startupEarlyInits();
  serialPath = argv[1];

  // NORTH talks to user, SOUTH talks to serial device
  NorthFace.reflex('q',NorthQuitHandler);
  Body.otherwise(packetBridge);

  eeprom_set_directoryImpl(".");

  startup();
  while (1) {
    delay(1);
  }
  quit(0);
}

#endif //#if 0
