#include <stdio.h>
#include <stdlib.h>

main()
{
   FILE *fi,*fo;
   int numread;
   unsigned short istimes[4];
   float t2old,t2new,t2start,t2end,t1x,t1xold,t1xhold,t1xnew,t1y,t1yold,t1ynew;
   float ax,ay,t2,accelx,accely,scale;
   int i,lines=0;

   t2new=0.;
   t1xnew=0.;
   t1ynew=0.;
   t1x=0.;

   fi=fopen("accel.out","rb");
   fo=fopen("accel.fmt","w");
   while(1){
      for(i=0;i<85;i++){
         numread=(int)fread(istimes,sizeof(unsigned short),3,fi);
         if(numread == 0)exit(0);
         lines++;

         t2old=t2new;
         t1xold=t1xnew;
         t1yold=t1ynew;
         t1xhold=t1x;

         t2new=(float)istimes[0];
         t1xnew=(float)istimes[1];
         t1ynew=(float)istimes[2];

/* during close/open blocks in accel, get 2 cycles, see if this happened
*/
         t2=t2new-t2old;
         if(t2 < 0)t2+=65536.;
         if(t2 < 10000.){
            scale=1.;
         }else{
            scale=0.5;
         }

         t1x=t1xnew-t1xold;
         if(t1x < 0.)t1x+=65536.;
         t1y=t1ynew-t1yold;
         if(t1y < 0.)t1y+=65536.;
         t1x*=scale;
         t1y*=scale;

         t2start=t2old-t1xhold/2.;
         t2end  =t2new-t1x/2.;
         t2=t2end-t2start;
         if(t2 < 0.)t2+=65536.;
         t2*=scale;
         t2+=4.; /* to account for 4 machine cycles timer 2 is off during read*/

         accelx=(t1x/t2-0.5)/0.125;
         accely=(t1y/t2-0.5)/0.125;

         if(lines <= 2)continue;
         fprintf(fo,"%f %f %f %f %f\n",accelx,accely,t1x,t1y,t2);
      }
      numread=(int)fread(istimes,sizeof(unsigned short),1,fi); /*filler bytes*/
      if(numread == 0)exit(0);
   }
}
