/* Endace headers. */
#include "dagapi.h"
#include "dag_platform.h"
#define TEST_BURST_SIZE 1024

static unsigned char records_read[TEST_BURST_SIZE];
static FILE *g_file = NULL;
static char filename[128] = "packets.erf";
static unsigned char* acquire_packet_from_somewhere(int *size);

/* this function reads from the ERF file */
unsigned char* acquire_packet_from_somewhere(int *size)
{
    unsigned char* ret_record = records_read;
    int read_len = 0;
    if ( NULL == g_file )
    {
        g_file = fopen(filename,"rb");
        if ( NULL == g_file )
        {
            printf("Unable to open %s\n",filename);
            exit(1);
        }
    }
    read_len = fread( ret_record, 1, TEST_BURST_SIZE, g_file);
    if ( read_len != TEST_BURST_SIZE)
    {
        if ( !feof(g_file) )
        {
            printf("Error in file read \n" );
            exit(1);
        }
        if (fseek(g_file,0L,SEEK_SET))
        {
            printf("Error in file seek\n" );
            exit(1);
        }
        printf("FEOF \n");
    }
    *size = read_len;
    return ret_record;
}
int main (int argc, char **argv)
{

    int dagfd ;
    int dagstream = 1; /* dagstream shud be an odd number for transmit*/
    unsigned char *records =NULL;
	uint8_t continue_run = 1;
    int len = 0;
    int captured_recs = 0;
    char *dagname = "/dev/dag0";
    int size = 0;

    if ( argc > 1 )
    {
        strcpy( filename, argv[1]);
    }
	if ((dagfd = dag_open(dagname)) < 0)
    {
		printf("dag_open falild %s: %s\n", dagname, strerror(errno));
        return -1;
    }
	if (dag_attach_stream(dagfd, dagstream, 0, 0) < 0)
    {
	   printf("dag_attach_stream %s:%u: %s\n", dagname, dagstream, strerror(errno));
       return -1;
    }
	if (dag_start_stream(dagfd, dagstream) < 0)
    {
		printf("dag_start_stream %s:%u: %s\n", dagname, dagstream, strerror(errno));
        return -1;
    }
   
    
    while (continue_run)
    {
        /* get record(s) to transmit - records may have more than 1 erf packets*/
        /* The ERF packets shud be 8 byte aligned */
        records = acquire_packet_from_somewhere(&len);
        
        printf("Got %d bytes to transmit \n",len);
        dag_tx_stream_copy_bytes (dagfd, dagstream, records, len);
    }
    dag_stop_stream(dagfd, dagstream);
	dag_detach_stream(dagfd, dagstream);
	dag_close(dagfd);
}
