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

// Minimum threshold:
#define TH 780

extern fsk_data *fskdp;

const char * const codigo[]={
	"A._",
	"B_...",
	"C_._.",
	"D_..",
	"E.",
	"F.._.",
	"G__.",
	"H....",
	"I..",
	"J.___",
	"K_._",
	"L._..",
	"M__",
	"N_.",
	"O___",
	"P.__.",
	"Q__._",
	"R._.",
	"S...",
	"T_",
	"U.._",
	"V..._",
	"W.__",
	"X_.._",
	"Y_.__",
	"Z__..",
	"0_____",
	"1.____",
	"2..___",
	"3...__",
	"4...._",
	"5.....",
	"6_....",
	"7__...",
	"8___..",
	"9____.",
	".._._._",
	",__..__",
        "?..__..",
	"~"
	};

float sav=TH,th=TH;

int decimated()
{
        int i,s;
        for (i=s=0;i<64;i++) s+=1e6*demodulator();
        s>>=6;
        sav=sav*0.99+s*0.01;
        th=TH+sav*0.5;
        //fprintf(stderr,"%d %f\n",s,th);
        return s;
}

void morsedec()
{
        int i,j,ll,lh;
        char buf[1024];

        // wait for the signal
        while (decimated()<th && fskdp->mode==1) if (fskdp->mode!=CW) return;

        //register dit-dahhhs until a long space
        i=0;
        do {
            lh=1;
            //do {
               while (decimated()>th && fskdp->mode==CW) lh++;
               ll=1;
               while (decimated()<th && fskdp->mode==CW && ll<5*fskdp->cwt)
                   ll++;
               if (fskdp->mode!=CW) return;
            //} while (ll<fskdp->cwt*0.5);

            buf[i++]=(lh>2*fskdp->cwt)?'_':'.';
            if (fskdp->cwatim) {
                fskdp->cwt=(fskdp->cwt*2.*31.+lh)/64.;
#ifdef ENX11
                update_tim();
#endif
            }
        } while (ll<2*fskdp->cwt);
        buf[i]=0;
        // Search the code table
        for (i=0;codigo[i][0]!='~';i++) {
            if(strcmp(&codigo[i][1],buf)==0) {
                printf("%c",codigo[i][0]); fflush(stdout);
            }
        }
        if (ll>5*fskdp->cwt) {printf(" "); fflush(stdout);}
}
