/************************************************************
*     13/9/2005 modified by david fedele to read buffer-data
*     instead raw-data-file 
*     29/11/2005 modified by david fedele to include crc control 
**************************************************************
 **
 * include needed system headers
 */
#include <stdio.h>       /* include standard i/o library */
#include <stdlib.h>      /* include standard library */
#include <string.h>      /* include string library */
#include <unistd.h>      /* include unix standard library */
#include <sys/types.h>   /* */
#include <sys/stat.h>    /* */
#include <fcntl.h>       /* */
#include <errno.h>       /* error simbol definitions */
#include <time.h>        /* system time definitions */
#include <math.h>        /* math library */
/************************************************************
/*     13/9/2005 modified by david fedele                     */
/*     29/11/2005 modified by david fedele                     */
/*void readtrailer_(unsigned short *trailer, int *error, int *fd)*/
void getbytes_(int *nbytes, char *buffer, int *p, unsigned int *value);
unsigned char crc8_8(unsigned char old, unsigned char data);
void readtrailer_(unsigned short *trailer, int *error,char *buffer, int *len,int *curpos,int *startcrc,int *stopcrc,unsigned int *crctemp)
/**************************************************************/
{
    int i;

    *error=0;
/************************************************************
 *     13/9/2005 modified by david fedele                     */
  /*   int nread; */
    /* unsigned short word; */

/* /\*** read the buffer ***\/ */
/*     nread=read(*fd, trailer, 2*3);//il trailer e' lungo 6 parole da 8 bits */
/*     if( nread==0 ) { */
/* 	printf("readtrailer: Unexpected end of file %d at %d \n",*fd,nread); */
/* 	*error=1; */
/* 	return ; */
/*     } */
/*     if ( nread != 6) { */
/* 	printf("readtrailer: Error on reading: nread = %d \n",nread); */
/* 	*error=-1; */
/*  	return ;  */
/*     } */


/* /\*** correct byte ***\/ //endianess... */
/*     for(i=0; i<3; i++) { */
/* 	word = trailer[i]; */
/* 	trailer[i] = ( (word&0x00ff) << 8 ) | ( (word&0xff00) >> 8 ); */
/*     } */
    unsigned int word[3];
    int nbytes2=2;
    char *buff=buffer;

    if( *curpos+(2*3)-1>*len ) {
      //  printf("readtrailer: Unexpected end of file \n");
      *error=1;
	return ;
    }
    
    for (i=0;i<3;i++)
	getbytes_(&nbytes2,buff,curpos,&word[i]);

    
    for( i=0; i<3; i++) trailer[i]=word[i];
/****************************************************************/

//    for( i=0; i<3; i++) printf("%x \n",trailer[i]);//???


/************************************************************
*     29/11/2005 modified by david fedele                     */
    stopcrc=curpos;
    *crctemp=0;
    for(i=*startcrc-1;i<*stopcrc-2;i++)
      *crctemp=crc8_8(*crctemp,buffer[i]);
/****************************************************************/
    return; 
}
