#include "common.h"
#include <stdio.h>

int serial()
{
	int a;
	int i,j,n1,n0;
        float x;

	/* Waiting for the START bit */
	do {
		/* first we wait until we get a low level */
                while (demodulator()<0.0);
		while (demodulator()>0.0);
                /* read start bit */
                bit_phase=0;
                i=get_bit_raw();
	} while (i); /* If the start bit fails we wait again */

	/* read the word data bits using DPLL */
	j=fskdp->nbit;
	for (a=n1=0;j;j--) {
		i=get_bit_raw();
		if (i) n1++;
		a>>=1; a|=i;
	}
	j=8-fskdp->nbit;
	a>>=j;

	/* we read the parity bit (if needed) and we check it */
	if (fskdp->parity) {
		i=get_bit_raw(); if (i) n1++;
		if (fskdp->parity==1) {		/* parity=1 (even) */
			if (n1&1) a|=0x100;	/* error */
		} else {			/* parity=2 (odd) */
			if (!(n1&1)) a|=0x100;	/* error */
		}
	}

	/* We read the STOP bits. All these bits must be 1.*/
        /* We don't return until all the STOP bits are 1.*/

        if (fskdp->nstop>1 || fskdp->nstop05==1) {
            j=0;
            while (get_bit_raw()==0) {a|=0x200; j++;}
            if (j>30) a|=0x400;  /* Break */
        }

        // If we have 1 or 2 STOP bits we wait only half a bit
        if (fskdp->nstop05==0) {
            j=0;
            do {
                for (bit_phase=0;bit_phase<0x8000;bit_phase+=fskdp->phs)
                    x=demodulator();
                if (x<0) {a|=0x200; j++;}
            } while (x<0.0 && fskdp->mode==RTTY);
            if (j>60) a|=0x400;  /* Break */
        }

	/* We return:  */
	/* Bit 8 : Parity Error */
	/* Bit 9 : Framing Error */

	return a;
}
