/* Acquisition Loop with  TDC V1190 - MG xx/xx/2005 @ LIXAM-CNRS*/


/* ============================================================================================================================ */
/* INCLUDES */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "bits.h"

#include "tdc1190_driver_high.h"
#include "bits.h"

/* ============================================================================================================================ */
/* DEFINE */
/*#define SOFT_TRIG*/
#define DMA_ON 
#define OFF 0
#define ON  1
/* ============================================================================================================================ */
#define TAILLE_DMA  1024
#define TAILLE_DATA 10
#define TAILLE_BUFFER TAILLE_DMA*TAILLE_DATA
int main (void)
{

  tdc1190 test;
  int rtf1,rtf2, count,i;
  unsigned int status=0;
  long data[TAILLE_DATA];
  unsigned long buffer[TAILLE_BUFFER];
  unsigned long pause=0,end_fifo=0,total_wc = 0;;

  /* Init TDC*/
  InitTdc(&test,0x1220000,128);
 
  /*TDC Status : Set and Get*/
  printf("Init Module for acquisition...\n");
  SetTdc_EventMaxHit(&test,16);
  SetTdc_AcqMode(&test,1);
  SetTdc_TestMode(&test,0xbbaa,0x0007,ON);
  SetTdc_KeepToken(&test,ON);
  SetTdc_EventHeaderTrailer(&test, OFF);
  SetTdc_MeasurementConfig(&test, 1);
  SetTdc_ErrorMark(&test,OFF);
  SetTdc_AlmostFull(&test,TAILLE_DMA);
  SetTdc_InterruptLevel(&test,6);
  /*  PrintTdc_Status(&test);*/
 
  /*Init Real Time acquisition */
  rtf1 = open("/dev/rtf1",O_RDWR);
  rtf2 = open("/dev/rtf2",O_RDWR);
  if (rtf1 == -1 || rtf2 == -1)
    {
      printf("Error in the real time fifo initialization !\n");
      exit(1);
    }
  ioctl(test.tdc_access.fd,UNIVERSE_DEBUT,TAILLE_DMA);
  ioctl(test.tdc_access.fd,UNIVERSE_IRQ,BIT8);
  ioctl(test.tdc_access.fd,UNIVERSE_IRQ,BIT6);

  /*Send a Real trig to the unit */
  printf("Send Trigger & Read out ...\n");
  do
    {
      total_wc = 0;
      count = read(rtf1,data,sizeof(long)*TAILLE_DATA)/4;
      printf("count=%i // ",count);
      for(i=0;i<count;i++)
	{
	   printf("data=%i // ",data[i]);
	  if (data[i] == -3)
	    {
	      printf("p");
	      pause++;
	    }
	  else
	    {
	      if (data[i] == -1)
		{
		  printf("e");
		  end_fifo = 1;
		  break;
		}
	      else
		{
		  total_wc += data[i];
		}
	    }
	}
      printf("\n");
      if (total_wc != 0)
	{
	  read(rtf2,buffer,sizeof(unsigned long)*total_wc);
	}
      GetTdc_Status(&test, &status);
    } while (!(status&4));
  
  printf("Module full !! \n");

  /* End */
  ioctl(test.tdc_access.fd,UNIVERSE_FIN,0);
  ioctl(test.tdc_access.fd,UNIVERSE_N_IRQ,BIT6);
  ioctl(test.tdc_access.fd,UNIVERSE_N_IRQ,BIT8);

  SetTdc_TestMode(&test,0xbbaa,0x00cc,OFF);
  close_vme(&test.tdc_access);
  return 0;
}
