/*
 * 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 hunpacker_(unsigned short *buffer, int *error, int *fd)

{
    int i;
    int nread,nhead;
    unsigned short word;
    unsigned short buffer_temp[13], *oo, *oi, *o1; //packed mode

///*** goes back a word***/
//    lseek(*fd, -2, SEEK_CUR); //SEEK_CUR ---> from current position
       
    *error=0;

/*** read the buffer ***/
    nhead = 13;  /* packed */
    nread=read(*fd, buffer_temp, 2*nhead);
    if( nread==0 ) {
	//printf("hunpacker: Unexpected end of file %d at %d \n",*fd,nread);
	*error=1;
	return ;
    }
    if ( nread != 2*nhead) {
	//printf("hunpacker: Error on reading: nread = %d \n",nread);
	*error=-1;
 	return ; 
    }

/*** correct byte ***/ //endianess...
    for(i=0; i<nhead; i++) {
	word = buffer_temp[i];
	buffer_temp[i] = ( (word&0x00ff) << 8 ) | ( (word&0xff00) >> 8 );
    }


/*** buffer unpacking ***/
    if( nhead == 16 ) {                    //              NO!???
	oo=buffer; /* nopacking buffer */
	oi=buffer_temp;
	for( i=0; i<nhead; i++) *oo++ = *oi++;
    }
    if( nhead == 13 ) {
	oo=buffer; /* unpacking buffer */
	oi=buffer_temp;
	o1 = oi++;
	*oo++ = (*o1 & 0xfff8) >> 3;
	*oo++ = ( (*o1 & 0x0007) << 10 ) | ( (*oi & 0xffc0) >> 6); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x003f) << 7 ) | ( (*oi & 0xfe00) >> 9); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x01ff) << 4 ) | ( (*oi & 0xf000) >> 12); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x0fff) << 1 ) | ( (*oi & 0x8000) >> 15); 
	*oo++ = (*oi & 0x7ffc) >> 2;
	o1 = oi++;
	*oo++ = ( (*o1 & 0x0003) << 11 ) | ( (*oi & 0xffe0) >> 5); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x001f) << 8 ) | ( (*oi & 0xff00) >> 8); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x00ff) << 5 ) | ( (*oi & 0xf800) >> 11); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x07ff) << 2 ) | ( (*oi & 0xc000) >> 14); 
	*oo++ = (*oi & 0x3ffe) >> 1;
	o1 = oi++;
	*oo++ = ( (*o1 & 0x0001) << 12 ) | ( (*oi & 0xfff0) >> 4); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x000f) << 9 ) | ( (*oi & 0xff80) >> 7); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x007f) << 6 ) | ( (*oi & 0xfc00) >> 10); 
	o1 = oi++;
	*oo++ = ( (*o1 & 0x03ff) << 3 ) | ( (*oi & 0xe000) >> 13); 
	*oo++ = *oi++ & 0x1fff;
    }    

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

    return; 
}
