#include <stdio.h>
#include <stdlib.h>
#include "header.h"
#include "universe_io.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

int main(int argc,char **argv)
{
  int fd,res,i;
  struct vme_access_slsi loc;
  struct vme_access_lsi loc2;
  struct lsi_config conf;
  unsigned char lsi1,lsi2;

  if (argc != 2)
    {
      printf("usage : %s device\n",argv[0]);
      exit(1);
    }
  fd = open(argv[1],O_RDWR);
  if (fd == -1)
    {
      printf("%s isn't a valid device\n",argv[1]);
      exit(1);
    }
  loc.offset = TDC_BASE + MODULE_RESET;
  loc.valeur = 0x00000000;
  
  loc.region = REGION0;
  res = ioctl(fd,UNIVERSE_WRITE24,&loc);
  if (res == -1)
    {
      printf("erreur ioctl 0x%08x\n",(int)loc.erreur);
    }
   conf.taille = 0x00010000;
  conf.premiere_addr_vme = 0x00000000;
  conf.AMcode = 0x3d;
  conf.profondeur_donnees = D16;
  sprintf(conf.nom,"%s","a24d16");
  res = ioctl(fd,UNIVERSE_WDW_RQST,&conf);
  if (res == -1)
    {
      printf("erreur ioctl 0x%08x\n",(int)conf.erreur);
      lsi1 = 9;
    }
  else
    {
      printf("AMCode 0x3D --- LSI lecture-ecriture \n");
      loc2.offset = 0;
      loc2.valeur = 0x00000000;
      loc2.lsi = conf.lsi;
      lsi1 = conf.lsi;
      for(i=0;i<5;i++)
	{
	  loc2.offset += i<<1;
	  res = ioctl(fd,UNIVERSE_READ_LSI,&loc2);
	  if (res == -1)
	    {
	      printf("erreur1 ioctl 0x%08x %d  %d\n",(int)loc2.erreur,
		     conf.lsi,loc2.lsi);
	    }
	  loc2.valeur = 0x00000000;
	  res = ioctl(fd,UNIVERSE_WRITE_LSI,&loc2);
	  if (res == -1)
	    {
	      printf("erreur1 ioctl 0x%08x %d  %d\n",(int)loc2.erreur,
		     conf.lsi,loc2.lsi);
	    }
	}
    }
  conf.taille = 0x01000000;
  conf.premiere_addr_vme = 0xEEEE0000;
  conf.AMcode = 0x09;
  conf.profondeur_donnees = D16;
  sprintf(conf.nom,"%s","a32d16");
  res = ioctl(fd,UNIVERSE_WDW_RQST,&conf);
  if (res == -1)
    {
      lsi2 = 9;
      printf("erreur ioctl 0x%08x\n",(int)conf.erreur);
    }
  else
    {
      printf("AMCode 0x09 --- LSI lecture-ecriture \n");
      loc2.offset = 0;
      loc2.valeur = 0x00000000;
      loc2.lsi = conf.lsi;
      lsi2 = conf.lsi;
      for(i=0;i<5;i++)
	{
	  loc2.offset += i<<1;
	  res = ioctl(fd,UNIVERSE_READ_LSI,&loc2);
	  if (res == -1)
	    {
	      printf("erreur2 ioctl 0x%08x %d  %d\n",(int)loc2.erreur,
		     conf.lsi,loc2.lsi);
	    }
	  loc2.valeur = 0x00000000;
	  res = ioctl(fd,UNIVERSE_WRITE_LSI,&loc2);
	  if (res == -1)
	    {
	      printf("erreur2 ioctl 0x%08x %d  %d\n",(int)loc2.erreur,
		     conf.lsi,loc2.lsi);
	    }
	}
    }
  system("cat /proc/iomem");
  res = ioctl(fd,UNIVERSE_RELEASE_WDW,lsi1);
  res = ioctl(fd,UNIVERSE_RELEASE_WDW,lsi2);
  close(fd);
  return 0;
}
