 void loop() 
 {
     // Mirror host input to the ESP8266
-    if ( SWserial.available() ) {
-      int char_in = SWserial.read();
-      switch (char_in) {
-        case '\n': break; // ignore linefeed
-        case '\r':
-           SWserial.print ("\n\r");
-           h_handle_line();
-           break;
-        default:
-           SWserial.write (char_in);  // Mirror to host for human consumption
-           hlinebuf[hlineoff++] = char_in;
-           if (hlineoff > 254) {
-              log("H", "line too long, ignoring");
-              hlineoff = 0;
-           }
-      }
-    }
+    handle_host();
  
     // Collect input from the ESP8266 into lines and do things when appropriate.
     if ( Serial.available() ) {

    while (millis() - time < 200) {
      if ( Serial.available() ) {
         int char_in = Serial.read();
         SWserial.write(char_in);
         if (char_in == '>') {
            log ("H","waited");
            return;
         }
      }
      delay (1);
    }
    log ("H","timeout");
}
void rsend (char * msg) {
    Serial.print ("AT+CIPSEND=0,");
    Serial.print (strlen(msg)+4);
    Serial.print ("\r\n");
    wait_for_data();
    Serial.print (msg);
    Serial.print ("\r\n");
    Serial.print ("? ");
    state = 8;
}
void handle_command (char * command) {
    log ("!",command);
         if (!strcmp (command, "OK?")) { handle_command_ok(command); }
    else if (!strcmp (command, "pic")) { handle_command_pic(command); }
    else {

#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "ov2640_regs.h"

//#define HOSTCONN
//#if defined HOSTCONN
//#include <AltSoftSerial.h>
//AltSoftSerial SWserial;
//#endif

void handle_host ();
void xlog (char * origin, char * text);
void xlognum (char * origin, char * text, int number);
void w_handle_line ();
void rsend (char * msg);

void state_0_1 ();
void state_1_2 ();
void state_2_3 ();
void state_3_4 ();
void state_4_5 ();
void state_5_6 ();
void state_6_7 ();
void state_7_6 ();
void state_8_7 ();

void handle_command (char * command);
void handle_command_ok (char * command);
void handle_command_pic (char * command);

const int CS = 6;
ArduCAM cam(OV2640, CS);
