/* initialize and retrieve data from DMA buffer */ 
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <apci3600.h>

#include "apci3600-def.h"
#include "event.h"
#include "retrieve.h"
#include "apci3600msg.h"
#include "apci.h"

//--------------------------------------------------------------------------------
int apci3600_loop_and_read_data(struct apci3600_card_t * pboard, uint8_t b_Module, int data_file, unsigned long long max)
{	
	unsigned long long acquired = 0;		
	/* wait for event */
	printf("will now wait for events ( CTRL-C to quit)\n");
	while(1)
	{
	
		
		apci3600_event_t evt;
		if ( apci3600_wait_for_event(pboard,&evt) )
		{
			return -1;
		}
			
		printf("event received :\n source\t0x%X\n mask\t0x%X\n buffnumber\t0x%X\n", evt.source, evt.mask, evt.buffnumber);
		
		/* an event is here - check it is what we wait */
		switch(evt.source)
		{
			case 0x00000004:
			case 0x00000008:
			case 0x00000010:
			case 0x00000020:
				if (evt.source == (0x00000004 << b_Module) )
					break;
			default:
				printf("event ignored\n");
				continue;
		}
		
		/* this is for us */
		switch(evt.mask )
		{
			case 0x00000001:
				/* DMA : data is here */
				break;
			case 0x00000002:
				printf("Internal FIFO error interrupt\n");
				return -1;
			case 0x00000004:
				printf("SDRAM Overflow interrupt\n");
				return -1;
			case 0x00000008:
				printf("PC Buffer Overflow interrupt\n");
				return -1;
			case 0x00000010:
				/* Auto-Stop interrupt */
				break;
			default:
				printf("unknown mask - aborting program\n");
				return -1;
		}
		
		/* read data */
		while(1)
		{
			int readnb;
			uint32_t buffer[10000];
			
			readnb = read( pboard->base, buffer, sizeof(buffer) ); 
			
			if (0 ==readnb) /* no data */
				break;

			if(-1==readnb)
			{
				perror("read");
				return -1;
			}
			
			printf("read %d bytes\n",readnb);
			
			/* data are provided in "packets" preceded by a 4-bytes header describing the content
			 * bits 31-4 Number of values in 4 bytes units
			 * bit 3-2: Index of the source ( 0 .. 3 )
			 * bit 0: Source (0: ADC ,  1: Chronometer)
			 */
			
			{
				int ret = write(data_file, buffer, readnb); 
				if ( -1 == ret  )
				{
					perror("write");
					return -1;
				}
				
				// short write could mean a problem, but let ignore it in this sample 
			}
			
			acquired += readnb;
			/* leave the loop if max <> 0 and acquired is bigger */
			if(max && (acquired>=max) )
			{
				printf("a total of %llu bytes were acquired\n",acquired);
				return 0;
			}
		}
	}
	
	return 0;	
}
