//If big-little endian problem: switch tmp1&0xFF00 + tmp2&0x00FF ->
// tmp1&0x00FF + tmp2&0xFF00
#include <stdio.h>
#include "ACphysics.h"

int ACphysics(int length,unsigned short* datapointer,struct datastruct* physicspointer){

//physics structure
struct datastruct physicsdata;

//pointer to struct
struct datastruct *physicspointer;

//read variables
int i,err,found;
unsigned short buffer[100];
unsigned short tmp1,tmp2;

   int iter=2;

  *physicspointer=physicsdata; 
  
  //look for header AC11, then cut out the event to a temp buffer
  while(found==0 && iter<length)
    {
      tmp1=*datapointer;
      tmp2=*(datapointer+1);
      //printf("check: %hx\n",tmp1);
      if(tmp1==0x11AC)
	{ 
	  found=1;
	  for(i=0;i<64;i++)
	    {
	      buffer[i]=*datapointer;
	      datapointer++;
	    }
	  tmp1=0x0000;
	}
      else if((tmp1&0xFF00) + (tmp2&0x00FF)==0xAC11)
	{
	  found=1;
	  for(i=0;i<64;i++)
	    {
	      buffer[i]=(tmp1&0xFF00) + (tmp2&0x00FF);
	      datapointer++;
	      tmp1=tmp2;
	      tmp2=*(datapointer+1);
	    }
	}
      else{
	datapointer++;
	iter=iter+2;}
    }
  
  //check errors
  if(iter>=length)
    err=2;
  else if(buffer[1]==0xAC22)
    err=0;
  else
    err=1;

  //Fill physicsdata from buffer
  for(i=0;i<2;i++) physicsdata.header[i]=buffer[i];
  physicsdata.status=buffer[2];
  physicsdata.hitmap=buffer[3];
  for(i=0;i<6;i++) physicsdata.regist[i]=buffer[4+i];
  for(i=0;i<16;i++) physicsdata.shift[i]=buffer[10+i];
  for(i=0;i<16;i++) physicsdata.counters[i]=buffer[26+i];
  for(i=0;i<8;i++) physicsdata.coinc[i]=buffer[42+i];
  physicsdata.trigg=buffer[50];
  for(i=0;i<2;i++) physicsdata.clock[i]=buffer[51+i];
  for(i=0;i<2;i++) physicsdata.temp[i]=buffer[53+i];
  for(i=0;i<8;i++) physicsdata.DAC[i]=buffer[55+i];
  physicsdata.CRC=buffer[63];

  return err;

}

