#include "app.h"
#include "nexa.h"

enum { UNKNOWN, T0, T1, T2, T3, OK, DONE };

static unsigned char temp1state = UNKNOWN;

       unsigned long temp1_x_data;
static unsigned int temp1x_numBits;

void temp1ResetDecoder () {
	temp1_x_data = 0;
	temp1x_numBits = 0;
	temp1state = UNKNOWN;
}

static boolean temp1isDone() { return temp1state == DONE; }

static void temp1done () { temp1state = DONE; }

static void temp1gotBit (char value) {

	// X
	temp1x_numBits++;
	temp1_x_data = (temp1_x_data << 1) + (value & 0x01);

	temp1state = OK;
}

static int temp1decode (unsigned int width) {
  
        
	switch (temp1state) {
	case UNKNOWN: // Start of frame
		if ( 3400 <= width && width <= 3800 ) {
			temp1state = T0;
		}
                else {
                  return -1;	// error, reset
                }
		break;

	case T0: // First half of pulse : HIGH around 230us

                if( temp1x_numBits == 32 ) {	// end of frame
			temp1state = DONE;
                        temp1_x_data = (temp1_x_data>>8);      // Mask away some bits at the end
			return 1;
		}
                else if ( 340 <= width && width <= 480 ) {
			temp1state = T1;
		}
		else {
                  if( temp1x_numBits == 0 && 3400 <= width && width <= 3800 ) {
                    temp1state = T0;
                  }
                  else {
                    return -1;	// error, reset
                  }
                }
		break;

	case T1:
                if ( 800 <= width && width <= 1000) {
			temp1gotBit(0);
		} else if ( 1600 <= width && width <= 1900 ) {
			temp1gotBit(1);
		} else  {
                  return -1;	// error, reset
                }
		temp1state = T0;
		break;
	}
	return 0;
}

boolean nextPulseTemp1 (unsigned int width) {
  
    if( width > 0 ) {
		if (temp1state != DONE)

			switch (temp1decode(width)) {
			case -1:
				temp1ResetDecoder();
				break;
			case 1:  temp1done();  break;
		}
	}
	return temp1isDone();
}

