/* Output & Timer with  TDC V1190 - MG xx/xx/2005 @ LIXAM-CNRS*/


/* ============================================================================================================================ */
/* INCLUDES */
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>

#include "tdc1190_driver_high.h"

/* ============================================================================================================================ */
/* DEFINE */
#define SOFT_TRIG
#define MMAP_ON 
#define OFF 0
#define ON  1
/* ============================================================================================================================ */
int main (void)
{
  int i=0,ok=0;
  tdc1190 test;
  unsigned int out[5];
  unsigned int status=0;

  struct itimerval timer;
  timer.it_value.tv_sec=60;
  timer.it_value.tv_usec=1000000;


  /* Init TDC*/
  InitTdc(&test,0x1220000,128);
 
  /*TDC Status : Set and Get*/
  printf("Init Module for acquisition...\n");
  SetTdc_EventMaxHit(&test,1);
  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,4);
  /*PrintTdc_Status(&test);*/
 

  /*Send a Soft trig to the unit */
  printf("Send Trigger...\n");
  do
    {
#ifdef SOFT_TRIG
      SetTdc_SoftTrigger(&test);sleep(1);
#endif
      GetTdc_Status(&test, &status);
      ok=status&2;
    } while(!ok);

  printf("----------------\n");   
  printf("TDC Output Registers Status... \n");
  GetTdc_Status(&test, &status);
  printf("Status Register :bx%15.0f \n",Set2Bit(status));
  /*Event Register Status */
  printf("-- Event Register --  ");
  GetTdc_EventCounter(&test, &status);
  printf("Counter :0x%08x  /  ",status);
  GetTdc_EventStored(&test, &status);
  printf("Stored value:0x%08x  \n",status);

  /* Fifo Register Status */
  printf("-- Fifo Register --  ");
  GetTdc_EventFIFO_Status(&test, &status);
  printf("Status:0x%08x  /  ",status);
  GetTdc_EventFIFO(&test, &status);
  printf("Counter :0x%08x  /  ",status);
  GetTdc_EventFIFO_Stored(&test, &status);
  printf("Stored value :0x%08x  \n",status);  

  /* Read-out Buffer */ 
  i=0;  
  printf("----------------\n");
  printf("Readout ...\n");
  setitimer(ITIMER_REAL,&timer,NULL);
  getitimer(ITIMER_REAL,&timer);  
  printf("%li (s) %li (us) \n",timer.it_value.tv_sec,timer.it_value.tv_usec);
  do 
    {
#ifdef MMAP_ON
	  read_MMAPoutput(&test.tdc_access, out);  
#else
	  read_output(&test.tdc_access, out);   
#endif    
      print_output(out);
      GetTdc_Status(&test, &status);
      ok=status&1;
      i+=1;
    } while (ok);
  getitimer(ITIMER_REAL,&timer);
  printf("%li (s) %li (us) \n",timer.it_value.tv_sec,timer.it_value.tv_usec);

  printf("Transfer %i KB\n\n",(i/256));


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