/***************************************************************************/
/* example_exception_handler.c
 * 
 * Simple example of how exception/signal handling works using a user
 * define exception handler.
 * 
 * Build:  
 *  $COMMONCC -o example_exception_handler example_exception_handler.c $VMELIBS
 *
 */
/***************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>

#include "Vme.h"

#define VME_MAP_ADDRESS 0x10000000
#define VME_MAP_SIZE    1024*1024  /* 1 MB */ 
#define VME_MAP_AM      0x09       /* Extended VME address */

void MyExceptionHandler(int);

void MyExceptionHandler (int signal_nr)
{
  int bus_error;
  printf("MyExceptionHandler> received signal nr %d\n",signal_nr);
  if (signal_nr == SIGBUS)
    {
      bus_error = VmeGetBusErrorType();
      printf("MyExceptionHandler> bus error type = %d\n",
	     bus_error);
    }
}

/***************************************************************************/
main (int argc, char *argv[])
/*---------------------------
*/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
{
  u_long vme_address = VME_MAP_ADDRESS;
  int    cid, signal_nr;
  volatile int data;
  int    *vme_base;
/*.........................................................................*/

  /* Use a different VME base address if specified.
   */
  if ((argc==2)&&(sscanf(argv[1],"%x",&vme_address)!=1))
    {
      printf("Usage: %s <vme-base-address>\n",argv[0]);
      exit(1);
    }
  
  /* Define the exception handling policy.
   */  
  VmeSetExceptionHandling(Vme_EXCEPTION_PRINT);
  VmeSetExceptionHandler (MyExceptionHandler);

  /* Open a VME channel for Programmed I/O.
   */
  cid = VmeOpenChannel("Example1","pio");
  if (cid < 0 ) 
    exit(1);
  
  /* Map VME address space.
   */
  vme_base = (int *)VmeMapAddress(cid,vme_address,VME_MAP_SIZE,VME_MAP_AM);
  if (vme_base == NULL)
    exit(1);
  
  /* We try to access two times a maybe wrong address 
   * to see the result of a bus error.
   */
  printf("Reading from VME address 0x%x \n",vme_address);
  Vme_D32READ(vme_base, &vme_base[0], data);
  printf("Reading from VME address 0x%x again ...\n",vme_address);
  Vme_D32READ(vme_base, &vme_base[0], data);

  /* Close Vme channel. Do not forget to call this function
   * before you exit otherwise you might get some trouble later.
   */
  (void)VmeCloseChannel(cid);
}