#include </usr/local/include/libraw1394/csr.h>
#include </usr/local/include/libraw1394/raw1394.h>
#include "uc1394.h"

#define DEBUG 1
#define PORT 0

int my_iso_handler(raw1394handle_t, int, size_t, quadlet_t *);
quadlet_t byte_swap(quadlet_t);

int main(void)
{
  int i, node;
  raw1394handle_t handle;
  struct raw1394_portinfo pinf[16];
  quadlet_t buffer;

  handle = raw1394_new_handle();

   if(!handle){
    if(DEBUG)
      printf("Could not get handle\n");
    exit(1);
  }
  
  raw1394_get_port_info(handle, pinf, 16);
   
  if(raw1394_set_port(handle, PORT) < 0)
    exit(1);

  if(pinf[PORT].nodes == 1){
    if(DEBUG)
      printf("No devices connected to this firewire port, please connect the uc1394 and try again\n");
    exit(0);
  }

  // Search the nodes to f1ind the uc1394
  // loop breaks when found
  for (i = 0; i < pinf[PORT].nodes; i++) {
    if(DEBUG)
      printf("Checking node %d\n", i);

    buffer = 0;

    if (raw1394_start_read(handle, 0xffc0 | i, UCBASE+UC_BUS_BASE+0x0008, 4, &buffer, 0) < 0)
      if(DEBUG)
	printf("failed to read the node\n");
    raw1394_loop_iterate(handle);
   
    // check the last value and see if its the uc1394
    if((byte_swap(buffer)&0xFFFFFF00)>>8 == 0xB02A){
      node = i;
      break;
    }
  }

  // check the last value and make sure its the uc1394
  // good check if the loop exits without finding the uc1394
  if((byte_swap(buffer)&0xFFFFFF00)>>8 != 0xB02A){
    printf("Failed to find the uc1394\n");
    exit(0);
  }

  if(DEBUG)
    printf("Found UC1394 at node %d\n", node);
  
  if(raw1394_set_iso_handler(handle, 0, my_iso_handler) < 0) {
    printf("Failed to set the iso handler\n");
    raw1394_stop_iso_rcv(handle, 0);
    return 0;
  }
  
  if(raw1394_start_iso_rcv(handle, 0) < 0) {
   printf("Could not set the iso handler\n");
   return 0;
  }
  
  while(1) {
    raw1394_loop_iterate(handle);
    printf("Something on the bus happended \n");
  }
  
}

int my_iso_handler(raw1394handle_t h, int channel,  size_t length, quadlet_t *d)
{
  printf("In iso handler for channel %d, and length %d \n", channel, length);

  return 1;

}

quadlet_t byte_swap(quadlet_t d) // performs a byte swap if needed
{
  return ((d&0x000000FF)<<24|(d&0x0000FF00)<<8|(d&0x00FF0000)>>8|(d&0xFF000000)>>24);
}


