/*****************************************************************
Function to read AC physics data v1.1
Author: Petter Hofverberg, petter@particle.kth.se

0408 v1.0 alive
0409 Added shifting operators to fix problem with odd data (BBAC|11DD)
                                                              -----
Errors: (returned to the main program as the variable "err")
err=
0 - Ok
1 - Data found, but corrupt
2 - Data dont found in buffer

ToDo: i)  do it endian-independent
      ii) check for more events in the same file?
******************************************************************/

#include <stdio.h>
#include "AC.h"
int i,err,found,j;

int ACphysics(int length,unsigned short* datapointer,struct physicsstruct* physicspointer)
{
  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);

      if(tmp1==0x11AC)
      //if(tmp1==0xAC11) //flipped
	{ 
	  found=1;
	  for(i=0;i<64;i++)
	    {
	      buffer[i]=flip(*datapointer);
	      datapointer++;
	    }
	  tmp1=0x0000;
	}
      else if(((tmp1&0xFF00) >> 8 ) + ((tmp2&0x00FF) << 8 ) == 0x11AC)
	//else if((tmp1&0x00FF) + (tmp2&0xFF00)==0xAC11) //flipped
	{
	  found=1;
	  for(i=0;i<64;i++)
	    {
	      buffer[i]=flip(((tmp1&0xFF00) >> 8 ) + ((tmp2&0x00FF) << 8 ));
	      //buffer[i]=(tmp1&0x00FF) + (tmp2&0xFF00); //flipped
	      datapointer++;
	      tmp1=tmp2;
	      tmp2=*(datapointer+1);
	    }
	}
      else{
	datapointer++;
	iter=iter+2;}
    }
  
  //check errors
  if(found==0)
    err=2;
  else if(buffer[1]==0x22AC || 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;

}

