/* SigLib - DTMF Detection Example
This file reads some dtmf tones from a .WAV file and prints the results on the screen */

#include <stdio.h>
#include <ctype.h>
#include <siglib.h>
#include "nhl.h"

/* Define constants */
#define	DTMF_SAMPLE_LENGTH			102L

/* Declare arrays and variables */
SLData_t		*pData;								/* Data array pointers */
SLData_t		*pDTMFDetectState;					/* DTMF detector state */
WAV_FILE_INFO	WavInfo;

void	main(void);

void main (void)

{
	SLFixData_t	Finished = 0;
	SLStatus_t	KeyCode;
	SLFixData_t	SampleCount;
	SLStatus_t	PreviousKeyCode = SIGLIB_NO_DTMF_SIGNAL;	/* Initialise to no DTMF key detected */
	SLFixData_t	KeyCodeLength = 0;							/* Length of key code stream */
	SLFixData_t	KeyCodeRegistered = SIGLIB_FALSE;			/* A key code has not been registered */
	FILE		*pInputFile;

	pData = SUF_VectorArrayAllocate (DTMF_SAMPLE_LENGTH);
	pDTMFDetectState = SUF_VectorArrayAllocate (SIGLIB_GOERTZEL_DELAY_LENGTH);

	if ((pInputFile = fopen("tones.wav", "rb")) == NULL)	/* Note this file is binary */
	{
		printf ("Error opening input .WAV file\n");
		exit (1);
	}

	WavInfo = wav_read_header (pInputFile);
	if (WavInfo.NumberOfChannels == 0)				/* Check how many channels */
	{
		printf ("Error reading .WAV file header\n");
		exit (1);
	}

	wav_display_info (WavInfo);
	printf ("\n.WAV file data. '.' indicates no tone present\n");
	printf ("                '-' indicates signal present but not DTMF\n\n");

	SIF_DtmfDetect (pDTMFDetectState,					/* Pointer to filter state array */
					((SLData_t)WavInfo.SampleRate),		/* Sample rate */
					DTMF_SAMPLE_LENGTH);				/* Array length */

	while ((SampleCount = wav_read_data (pData, pInputFile, WavInfo, DTMF_SAMPLE_LENGTH)) == DTMF_SAMPLE_LENGTH)
	{
		KeyCode =
			SDA_DtmfDetectAndValidate (pData,				/* Source array pointer */
									   pDTMFDetectState,	/* Pointer to filter state array */
									   ((SLData_t)1000.0),	/* Threshold for signal energy */
									   &PreviousKeyCode,	/* Pointer to previous key code */
									   &KeyCodeLength,		/* Pointer to key code run length */
									   &KeyCodeRegistered,	/* Pointer to storage for key code registration flag */
									   DTMF_SAMPLE_LENGTH);	/* Array length */

		if (KeyCode == SIGLIB_NO_SIGNAL_PRESENT)
		{
			printf (". ");
		}

		else if (KeyCode == SIGLIB_NO_DTMF_SIGNAL)
		{
			printf ("- ");
		}

		else if (KeyCode != SIGLIB_DTMF_CONTINUATION)
		{
			printf ("%c ", SUF_KeyCodeToAscii (KeyCode));
		}
	}

	printf ("\n\n\n");

	SUF_MemoryFree (pData);							/* Free memory */
	SUF_MemoryFree (pDTMFDetectState);
}



