/*
 * 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 */

/*void findstart_(unsigned short *buffer, int *error, int *fd)*/

/*{*/
/*     int nread; */
/*     unsigned short word;//, *p_buffer; */


/* /\*** reads a word ***\/ */
/* //    p_buffer=&buffer; */
/*     nread=read(*fd, buffer, 2); */
/*     if(nread == 0) { */
/* 	printf("findstart: Unexpected end of file %d at %d \n",*fd,nread); */
/* 	*error=1; */
/* 	return ; */
/*     } */
/*     if(nread != 2) { */
/* 	printf("findstart: Error on reading: nread = %d \n",nread); */
/* 	*error=-1; */
/*  	return ;  */
/*     } */

/* /\*** correct byte ***\/ //??????????????????????SCAMBIA */
/*     word = buffer; */
/*     buffer = ( (word&0x00ff) << 8 ) | ( (word&0xff00) >> 8 ); */
/* //    printf("buffer %x , word: %x: \n", buffer, word);//??? */


/*   looks for a DSP header beginning (a word beginning with 1110)   */
    
void findstart_(int *error, int *fd)

{
    int nread;
    unsigned short word;
    unsigned short temp;
   
    do {
	nread=read(*fd, &word, 2); //reads 16 bits
	if(nread == 0) {
	    //printf("findstart: Unexpected end of file %d at %d \n",*fd,nread);
	    *error=1;
	    return ;
	}
	if(nread != 2) {
	    //printf("findstart: Error on reading: bytes read -> nread = %d \n",nread);
	    *error=-1;
	    return ;
	}


	/*** corrects byte ***/ //endianess...
	temp = word;
	word = ( (temp&0x00ff) << 8 ) | ( (temp&0xff00) >> 8 );
//	printf("word %x , temp: %x: \n", word, temp);//??? */

	
        /*** goes back 8 bits ***/
	lseek(*fd, -1, SEEK_CUR); //SEEK_CUR ---> from current position

//	unsigned short num=lseek(*fd, -1, SEEK_CUR); //SEEK_CUR ---> from current position
//	printf("%i \n",num);
	
    }
    while ((word&0xf000) != 0xe000);
    
    /*** goes back 8 bits ***/
    lseek(*fd, -1, SEEK_CUR);


    return;
}
