Esempio n. 1
0
METHODDEF       boolean get_app0(j_decompress_ptr cinfo)
/* Process an APP0 marker */
{
#define JFIF_LEN 14
	INT32           length;
	UINT8           b[JFIF_LEN];
	int             buffp;

	INPUT_VARS(cinfo);

	INPUT_2BYTES(cinfo, length, return FALSE);
	length -= 2;

	/* See if a JFIF APP0 marker is present */

	if(length >= JFIF_LEN)
	{
		for(buffp = 0; buffp < JFIF_LEN; buffp++)
			INPUT_BYTE(cinfo, b[buffp], return FALSE);
		length -= JFIF_LEN;

		if(b[0] == 0x4A && b[1] == 0x46 && b[2] == 0x49 && b[3] == 0x46 && b[4] == 0)
		{
			/* Found JFIF APP0 marker: check version */
			/* Major version must be 1, anything else signals an incompatible change.
			 * We used to treat this as an error, but now it's a nonfatal warning,
			 * because some bozo at Hijaak couldn't read the spec.
			 * Minor version should be 0..2, but process anyway if newer.
			 */
			if(b[5] != 1)
				WARNMS2(cinfo, JWRN_JFIF_MAJOR, b[5], b[6]);
			else if(b[6] > 2)
				TRACEMS2(cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6]);
			/* Save info */
			cinfo->saw_JFIF_marker = TRUE;
			cinfo->density_unit = b[7];
			cinfo->X_density = (b[8] << 8) + b[9];
			cinfo->Y_density = (b[10] << 8) + b[11];
			TRACEMS3(cinfo, 1, JTRC_JFIF, cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
			if(b[12] | b[13])
				TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13]);
			if(length != ((INT32) b[12] * (INT32) b[13] * (INT32) 3))
				TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int)length);
		}
		else
		{
			/* Start of APP0 does not match "JFIF" */
			TRACEMS1(cinfo, 1, JTRC_APP0, (int)length + JFIF_LEN);
		}
	}
	else
	{
Esempio n. 2
0
LOCAL           boolean open_ems_store(j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed)
{
	EMScontext      ctx;

	/* Is EMS driver there? */
	if(!jems_available())
		return FALSE;

	/* Get status, make sure EMS is OK */
	ctx.ax = 0x4000;
	jems_calldriver((EMScontext far *) & ctx);
	if(HIBYTE(ctx.ax) != 0)
		return FALSE;

	/* Get version, must be >= 4.0 */
	ctx.ax = 0x4600;
	jems_calldriver((EMScontext far *) & ctx);
	if(HIBYTE(ctx.ax) != 0 || LOBYTE(ctx.ax) < 0x40)
		return FALSE;

	/* Try to allocate requested space */
	ctx.ax = 0x4300;
	ctx.bx = (unsigned short)((total_bytes_needed + EMSPAGESIZE - 1L) / EMSPAGESIZE);
	jems_calldriver((EMScontext far *) & ctx);
	if(HIBYTE(ctx.ax) != 0)
		return FALSE;

	/* Succeeded, save the handle and away we go */
	info->handle.ems_handle = ctx.dx;
	info->read_backing_store = read_ems_store;
	info->write_backing_store = write_ems_store;
	info->close_backing_store = close_ems_store;
	TRACEMS1(cinfo, 1, JTRC_EMS_OPEN, ctx.dx);
	return TRUE;				/* succeeded */
}
Esempio n. 3
0
open_xms_store (j_common_ptr cinfo, backing_store_ptr info,
		long total_bytes_needed)
{
  XMScontext ctx;

  /* Get address of XMS driver */
  jxms_getdriver((XMSDRIVER far *) & xms_driver);
  if (xms_driver == NULL)
    return FALSE;		/* no driver to be had */

  /* Get version number, must be >= 2.00 */
  ctx.ax = 0x0000;
  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
  if (ctx.ax < (unsigned short) 0x0200)
    return FALSE;

  /* Try to get space (expressed in kilobytes) */
  ctx.dx = (unsigned short) ((total_bytes_needed + 1023L) >> 10);
  ctx.ax = 0x0900;
  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
  if (ctx.ax != 1)
    return FALSE;

  /* Succeeded, save the handle and away we go */
  info->handle.xms_handle = ctx.dx;
  info->read_backing_store = read_xms_store;
  info->write_backing_store = write_xms_store;
  info->close_backing_store = close_xms_store;
  TRACEMS1(cinfo, 1, JTRC_XMS_OPEN, ctx.dx);
  return TRUE;			/* succeeded */
}
Esempio n. 4
0
/*LOCAL*/static void create_colormap (j_decompress_ptr cinfo)
{
	my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
	JSAMPARRAY colormap;		/* Created colormap */
	int total_colors;		/* Number of distinct output colors */
	int i, j, k, nci, blksize, blkdist, ptr, val;

	/* Select number of colors for each component */
	total_colors = select_ncolors(cinfo, cquantize->Ncolors);

	/* Report selected color counts */
	if (cinfo->out_color_components == 3)
	{	TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
			 total_colors, cquantize->Ncolors[0],
			 cquantize->Ncolors[1], cquantize->Ncolors[2]);
	}
	else
	{	TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
	}
	/* Allocate and fill in the colormap. */
	/* The colors are ordered in the map in standard row-major order, */
	/* i.e. rightmost (highest-indexed) color changes most rapidly. */

	colormap = (*cinfo->mem->alloc_sarray)
		((j_common_ptr) cinfo, JPOOL_IMAGE,
		 (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);

	/* blksize is number of adjacent repeated entries for a component */
	/* blkdist is distance between groups of identical entries for a component */
	blkdist = total_colors;

	for (i = 0; i < cinfo->out_color_components; i++)
	{
		/* fill in colormap entries for i'th color component */
		nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
		blksize = blkdist / nci;
		for (j = 0; j < nci; j++)
		{
			/* Compute j'th output value (out of nci) for component */
			val = output_value(cinfo, i, j, nci-1);
			/* Fill in all colormap entries that have this value of this component */
			for (ptr = j * blksize; ptr < total_colors; ptr += blkdist)
			{
				/* fill in blksize entries beginning at ptr */
				for (k = 0; k < blksize; k++)
				{	colormap[i][ptr+k] = (JSAMPLE) val; 	}
			}
		}
		blkdist = blksize;		/* blksize of this color is blkdist of next */
	}

	/* Save the colormap in private storage,
	 * where it will survive color quantization mode changes.
	 */
	cquantize->sv_colormap	= colormap;
	cquantize->sv_actual	= total_colors;
}
Esempio n. 5
0
METHODDEF boolean
get_app0 (j_decompress_ptr cinfo)
/* Process an APP0 marker */
{
#define JFIF_LEN 14
  INT32 length;
  UINT8 b[JFIF_LEN];
  int buffp;
  INPUT_VARS(cinfo);

  INPUT_2BYTES(cinfo, length, return FALSE);
  length -= 2;

  /* See if a JFIF APP0 marker is present */

  if (length >= JFIF_LEN) {
    for (buffp = 0; buffp < JFIF_LEN; buffp++)
      INPUT_BYTE(cinfo, b[buffp], return FALSE);
    length -= JFIF_LEN;

    if (b[0]==0x4A && b[1]==0x46 && b[2]==0x49 && b[3]==0x46 && b[4]==0) {
      /* Found JFIF APP0 marker: check version */
      /* Major version must be 1 */
      if (b[5] != 1)
	ERREXIT2(cinfo, JERR_JFIF_MAJOR, b[5], b[6]);
      /* Minor version should be 0..2, but try to process anyway if newer */
      if (b[6] > 2)
	TRACEMS2(cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6]);
      /* Save info */
      cinfo->saw_JFIF_marker = TRUE;
      cinfo->density_unit = b[7];
      cinfo->X_density = (b[8] << 8) + b[9];
      cinfo->Y_density = (b[10] << 8) + b[11];
      TRACEMS3(cinfo, 1, JTRC_JFIF,
	       cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
      if (b[12] | b[13])
	TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13]);
      if (length != ((INT32) b[12] * (INT32) b[13] * (INT32) 3))
	TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) length);
    } else {
      /* Start of APP0 does not match "JFIF" */
      TRACEMS1(cinfo, 1, JTRC_APP0, (int) length + JFIF_LEN);
    }
  } else {
Esempio n. 6
0
close_xms_store (j_common_ptr cinfo, backing_store_ptr info)
{
  XMScontext ctx;

  ctx.dx = info->handle.xms_handle;
  ctx.ax = 0x0a00;
  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
  TRACEMS1(cinfo, 1, JTRC_XMS_CLOSE, info->handle.xms_handle);
  /* we ignore any error return from the driver */
}
Esempio n. 7
0
close_ems_store (j_common_ptr cinfo, backing_store_ptr info)
{
  EMScontext ctx;

  ctx.ax = 0x4500;
  ctx.dx = info->handle.ems_handle;
  jems_calldriver((EMScontext far *) & ctx);
  TRACEMS1(cinfo, 1, JTRC_EMS_CLOSE, info->handle.ems_handle);
  /* we ignore any error return from the driver */
}
METHODDEF void
close_file_store (backing_store_ptr info)
{
  jdos_close(info->handle.file_handle);	/* close the file */
  remove(info->temp_name);	/* delete the file */
/* If your system doesn't have remove(), try unlink() instead.
 * remove() is the ANSI-standard name for this function, but
 * unlink() was more common in pre-ANSI systems.
 */
  TRACEMS1(methods, 1, "Closed DOS file %d", info->handle.file_handle);
}
METHODDEF void
close_ems_store (backing_store_ptr info)
{
  EMScontext ctx;

  ctx.ax = 0x4500;
  ctx.dx = info->handle.ems_handle;
  jems_calldriver((EMScontext far *) & ctx);
  TRACEMS1(methods, 1, "Freed EMS handle %u", info->handle.ems_handle);
  /* we ignore any error return from the driver */
}
METHODDEF void
close_xms_store (backing_store_ptr info)
{
  XMScontext ctx;

  ctx.dx = info->handle.xms_handle;
  ctx.ax = 0x0a00;
  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
  TRACEMS1(methods, 1, "Freed XMS handle %u", info->handle.xms_handle);
  /* we ignore any error return from the driver */
}
Esempio n. 11
0
/*{{{  write_synamps_exit(transform_info_ptr tinfo) {*/
METHODDEF void
write_synamps_exit(transform_info_ptr tinfo) {
 struct write_synamps_storage *local_arg=(struct write_synamps_storage *)tinfo->methods->local_storage;
#define SETUP_OFFSET_NSWEEPS 360
#define SETUP_OFFSET_NUMSAMPLES 864
#define SETUP_OFFSET_EVENTTABLEPOS 886

 /* Apparently NeuroScan write this even for epoched files although there's no event table there... 
  * It is important there to compute bytes_per_sample */
 local_arg->EEG.EventTablePos=ftell(local_arg->SCAN);
 if (local_arg->output_format==FORMAT_CNTFILE) {
  TEEG TagType;
  EVENT1 event;
  int const nevents=local_arg->triggers.current_length/sizeof(struct trigger);
  int n;

  TagType.Teeg=TEEG_EVENT_TAB1;
  TagType.Size=(nevents+1)*sm_EVENT1[0].offset;	/* sm_EVENT1[0].offset is sizeof(EVENT1) in the file. */
  TagType.p_o.Offset=0L;
# ifndef LITTLE_ENDIAN
  change_byteorder((char *)&TagType, sm_TEEG);
# endif
  write_struct((char *)&TagType, sm_TEEG, local_arg->SCAN);

  for (n=0; n<nevents; n++) {
   struct trigger * const intrig=((struct trigger *)local_arg->triggers.buffer_start)+n;
   int acc=NAV_STARTSTOP, type=0, resp=0, keyboard=0;
   while (acc>=0 && intrig->code!=neuroscan_accept_translation[acc]) acc--;
   if (acc<0) {
    acc=0;
    if (intrig->code>0) {
     type=intrig->code;
    } else {
     resp=(-intrig->code)&0xf;
     if (resp==0) {
      keyboard=(-intrig->code)>>4;
      if (keyboard==0) {
       TRACEMS1(tinfo->emethods, 1, "write_synamps_exit: Can't decipher event code %d\n", MSGPARM(intrig->code));
      } else {
       keyboard--;
      }
     }
    }
   }
Esempio n. 12
0
/* This subroutine encapsulates the coding of the different event codes
 * into a unified signed code */
LOCAL void
read_synamps_push_keys(transform_info_ptr tinfo, long position, int TrigVal, int KeyPad, int KeyBoard, enum NEUROSCAN_ACCEPTVALUES Accept) {
 struct read_synamps_storage * const local_arg=(struct read_synamps_storage *)tinfo->methods->local_storage;
 int code;
 if (Accept!=0 && (Accept<NAV_DCRESET || Accept>NAV_STARTSTOP)) {
  TRACEMS2(tinfo->emethods, 0, "read_synamps_push_keys: Unknown Accept value %d at position %d!\n", MSGPARM(Accept), MSGPARM(position));
  return;
 }
 code=TrigVal-KeyPad+neuroscan_accept_translation[Accept];
 if (code==0) {
  /* At least in Edit 4.x, KeyPad F2 is written as KeyBoard=0 with everything else 0 too... */
  code= -(((KeyBoard&0xf)+1)<<4);
 }
 if (code==0) {
  TRACEMS1(tinfo->emethods, 0, "read_synamps_push_keys: Trigger with trigcode 0 at position %d!\n", MSGPARM(position));
 } else {
  push_trigger(&local_arg->triggers, position, code, NULL);
 }
}
Esempio n. 13
0
/*{{{  get_mfxepoch(transform_info_ptr tinfo)*/
METHODDEF DATATYPE *
get_mfxepoch(transform_info_ptr tinfo) {
 struct get_mfxepoch_storage *local_arg=(struct get_mfxepoch_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 DATATYPE *newepoch;
 int again=FALSE;
 long epochlength;

 if (local_arg->epochs--==0) return NULL;

 do {
  again=FALSE;
  if ((newepoch=(DATATYPE *)mfx_getepoch(local_arg->fileptr, &epochlength, local_arg->beforetrig-local_arg->offset, local_arg->aftertrig+local_arg->offset, local_arg->trigname, args[ARGS_TRIGCODE].arg.i))==NULL) {
   /* MFX_READERR4 is the normal end-of-file 'error' */
   TRACEMS1(tinfo->emethods, (mfx_lasterr==MFX_READERR4 ? 1 : 0), "get_mfxepoch: mfx error >%s<\n", MSGPARM(mfx_errors[mfx_lasterr]));
   /* If the error was due to the beforetrig time being too long, try to
    * skip this epoch and try the next one */
   if (mfx_lasterr==MFX_NEGSEEK) {
    again=TRUE;
    mfx_seektrigger(local_arg->fileptr, local_arg->trigname, args[ARGS_TRIGCODE].arg.i);
    TRACEMS(tinfo->emethods, 1, "get_mfxepoch: Retrying...\n");
   }
  }
 } while (again);
 if (newepoch!=NULL) {
  /* TOUCH TINFO ONLY IF GETEPOCH WAS SUCCESSFUL */
  get_mfxinfo(local_arg->fileptr, tinfo);
  tinfo->z_label=NULL;
  tinfo->nr_of_points=epochlength;
  tinfo->length_of_output_region=epochlength*tinfo->nr_of_channels;
  tinfo->beforetrig=local_arg->beforetrig;
  tinfo->aftertrig=tinfo->nr_of_points-tinfo->beforetrig;
  tinfo->multiplexed=TRUE;
  tinfo->sfreq=1.0/(local_arg->fileptr)->fileheader.sample_period;
  tinfo->data_type=TIME_DATA;
  tinfo->itemsize=1;	/* Still, mfx doesn't support tuple data */
  tinfo->leaveright=0;
  tinfo->nrofaverages=1;
 }
 return newepoch;
}
Esempio n. 14
0
LOCAL boolean
get_sos (j_decompress_ptr cinfo)
/* Process a SOS marker */
{
  INT32 length;
  int i, ci, n, c, cc, ccc;
  jpeg_component_info * compptr;
  INPUT_VARS(cinfo);

  if (! cinfo->marker->saw_SOF)
    ERREXIT(cinfo, JERR_SOS_NO_SOF);

  INPUT_2BYTES(cinfo, length, return FALSE);

  INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */

  if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
    ERREXIT(cinfo, JERR_BAD_LENGTH);

  TRACEMS1(cinfo, 1, JTRC_SOS, n);

  cinfo->comps_in_scan = n;

  /* Collect the component-spec parameters */

  for (i = 0; i < n; i++) {
    INPUT_BYTE(cinfo, cc, return FALSE);
    INPUT_BYTE(cinfo, c, return FALSE);
    
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	 ci++, compptr++) {
      if (cc == compptr->component_id)
	goto id_found;
    }

    ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);

  id_found:

    cinfo->cur_comp_info[i] = compptr;
    compptr->dc_tbl_no = (c >> 4) & 15;
    compptr->ac_tbl_no = (c     ) & 15;
    
    TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
	     compptr->dc_tbl_no, compptr->ac_tbl_no);
  }

  /* Collect the additional scan parameters Ss, Se, Ah/Al.
   * Currently we just validate that they are right for sequential JPEG.
   * This ought to be an error condition, but we make it a warning because
   * there are some baseline files out there with all zeroes in these bytes.
   * (Thank you, Logitech :-(.)
   */
  INPUT_BYTE(cinfo, c, return FALSE);
  INPUT_BYTE(cinfo, cc, return FALSE);
  INPUT_BYTE(cinfo, ccc, return FALSE);
  if (c != 0 || cc != DCTSIZE2-1 || ccc != 0)
    WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);

  /* Prepare to scan data & restart markers */
  cinfo->marker->next_restart_num = 0;

  INPUT_SYNC(cinfo);
  return TRUE;
}
Esempio n. 15
0
get_sos (j_decompress_ptr cinfo)
/* Process a SOS marker */
{
  INT32 length;
  int i, ci, n, c, cc;
  jpeg_component_info * compptr;
  INPUT_VARS(cinfo);

  if (! cinfo->marker->saw_SOF)
    ERREXIT(cinfo, JERR_SOS_NO_SOF);

  INPUT_2BYTES(cinfo, length, return FALSE);

  INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */

  if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
    ERREXIT(cinfo, JERR_BAD_LENGTH);

  TRACEMS1(cinfo, 1, JTRC_SOS, n);

  cinfo->comps_in_scan = n;

  /* Collect the component-spec parameters */

  for (i = 0; i < n; i++) {
    INPUT_BYTE(cinfo, cc, return FALSE);
    INPUT_BYTE(cinfo, c, return FALSE);
    
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	 ci++, compptr++) {
      if (cc == compptr->component_id)
	goto id_found;
    }

    ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);

  id_found:

    cinfo->cur_comp_info[i] = compptr;
    compptr->dc_tbl_no = (c >> 4) & 15;
    compptr->ac_tbl_no = (c     ) & 15;
    
    TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
	     compptr->dc_tbl_no, compptr->ac_tbl_no);
  }

  /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  INPUT_BYTE(cinfo, c, return FALSE);
  cinfo->Ss = c;
  INPUT_BYTE(cinfo, c, return FALSE);
  cinfo->Se = c;
  INPUT_BYTE(cinfo, c, return FALSE);
  cinfo->Ah = (c >> 4) & 15;
  cinfo->Al = (c     ) & 15;

  TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
	   cinfo->Ah, cinfo->Al);

  /* Prepare to scan data & restart markers */
  cinfo->marker->next_restart_num = 0;

  /* Count another SOS marker */
  cinfo->input_scan_number++;

  INPUT_SYNC(cinfo);
  return TRUE;
}
Esempio n. 16
0
/*{{{  read_freiburg_init(transform_info_ptr tinfo) {*/
METHODDEF void
read_freiburg_init(transform_info_ptr tinfo) {
 struct read_freiburg_storage *local_arg=(struct read_freiburg_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 struct stat statbuf;

 /*{{{  Process options*/
 local_arg->fromepoch=(args[ARGS_FROMEPOCH].is_set ? args[ARGS_FROMEPOCH].arg.i : 1);
 local_arg->epochs=(args[ARGS_EPOCHS].is_set ? args[ARGS_EPOCHS].arg.i : -1);
 /*}}}  */
 local_arg->channelnames=NULL;
 local_arg->uV_per_bit=NULL;
 growing_buf_init(&local_arg->segment_table); /* This sets buffer_start=NULL */
 local_arg->nr_of_channels=0;

 if (args[ARGS_CONTINUOUS].is_set) {
  /*{{{  Open a continuous (sleep, Bernd Tritschler) file*/
  FILE *infile;
  local_arg->in_channels= &sleep_channels[0];

  if (stat(args[ARGS_IFILE].arg.s, &statbuf)!= 0 || !S_ISREG(statbuf.st_mode)) {
   /* File does not exist or isn't a regular file: Try BT format */
#ifdef __GNUC__
   char co_name[strlen(args[ARGS_IFILE].arg.s)+4];
   char coa_name[strlen(args[ARGS_IFILE].arg.s)+5];
#else
   char co_name[MAX_PATHLEN];
   char coa_name[MAX_PATHLEN];
#endif
   char coa_buf[MAX_COALINE];
   FILE *coafile;

   strcpy(co_name, args[ARGS_IFILE].arg.s); strcat(co_name, ".co");
   if((infile=fopen(co_name,"rb"))==NULL) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't open file %s\n", MSGPARM(co_name));
   }
   local_arg->infile=infile;
   if (args[ARGS_REPAIR_OFFSET].is_set) {
    fseek(infile, args[ARGS_REPAIR_OFFSET].arg.i, SEEK_SET);
   } else {
   if (read_struct((char *)&local_arg->btfile, sm_BT_file, infile)==0) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Header read error in file %s\n", MSGPARM(co_name));
   }
#  ifndef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->btfile, sm_BT_file);
#  endif
   }
   strcpy(coa_name, args[ARGS_IFILE].arg.s); strcat(coa_name, ".coa");
   if((coafile=fopen(coa_name,"rb"))==NULL) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No file %s found\n", MSGPARM(coa_name));
   } else {
    while (!feof(coafile)) {
     Bool repeat;
     fgets(coa_buf, MAX_COALINE-1, coafile);
     do {
      repeat=FALSE;
      if (strncmp(coa_buf, "Channel_Table ", 14)==0) {
       int havechannels=0, stringlength=0;
       long tablepos=ftell(coafile);
       char *innames;
       while (!feof(coafile)) {
	char *eol;
	fgets(coa_buf, MAX_COALINE-1, coafile);
	if (!isdigit(*coa_buf)) break;
	if (strncmp(coa_buf, "0 0 ", 4)==0) {
	 /* Empty channel descriptors: Don't generate channelnames */
	} else {
	 for (eol=coa_buf+strlen(coa_buf)-1; eol>=coa_buf && (*eol=='\n' || *eol=='\r'); eol--) *eol='\0';
	 /* This includes 1 for the zero at the end: */
	 stringlength+=strlen(strrchr(coa_buf, ' '));
	}
	havechannels++;
       }
       if (havechannels==0) continue;	/* Channel table is unuseable */
       local_arg->nr_of_channels=havechannels;
       innames=NULL;
       if ((stringlength!=0 && 
	   ((local_arg->channelnames=(char **)malloc(havechannels*sizeof(char *)))==NULL || 
	    (innames=(char *)malloc(stringlength))==NULL)) ||
	   (local_arg->uV_per_bit=(float *)malloc(havechannels*sizeof(float)))==NULL) {
	ERREXIT(tinfo->emethods, "read_freiburg_init: Error allocating .coa memory\n");
       }
       fseek(coafile, tablepos, SEEK_SET);
       havechannels=0;
       while (!feof(coafile)) {
	char *eol;
	fgets(coa_buf, MAX_COALINE-1, coafile);
	if (!isdigit(*coa_buf)) break;
	for (eol=coa_buf+strlen(coa_buf)-1; eol>=coa_buf && (*eol=='\n' || *eol=='\r'); eol--) *eol='\0';
	if (innames!=NULL) {
	 strcpy(innames, strrchr(coa_buf, ' ')+1);
	 local_arg->channelnames[havechannels]=innames;
	 innames+=strlen(innames)+1;
	}
	/* The sensitivity in .coa files is given as nV/Bit */
	local_arg->uV_per_bit[havechannels]=atoi(strchr(coa_buf, ' ')+1)/1000.0;
	if (local_arg->uV_per_bit[havechannels]==0.0) {
	 local_arg->uV_per_bit[havechannels]=0.086;
	 TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Sensitivity for channel %d set to 86 nV/Bit\n", MSGPARM(havechannels));
	}
	havechannels++;
       }
       repeat=TRUE;
      } else if (strncmp(coa_buf, SEGMENT_TABLE_STRING, strlen(SEGMENT_TABLE_STRING))==0) {
       long current_offset=0;
       char *inbuf=coa_buf;
       Bool havesomething=FALSE;

       growing_buf_allocate(&local_arg->segment_table, 0);
       while (!feof(coafile)) {
	int const nextchar=fgetc(coafile);
	if (nextchar=='\r' || nextchar=='\n' || nextchar==' ') {
	 if (havesomething) {
	  *inbuf = '\0';
	  current_offset+=atoi(coa_buf);
	  growing_buf_append(&local_arg->segment_table, (char *)&current_offset, sizeof(long));
	  inbuf=coa_buf;
	  havesomething=FALSE;
	 }
	 if (nextchar=='\n') break;
	} else {
	 *inbuf++ = nextchar;
	 havesomething=TRUE;
	}
       }
       repeat=FALSE;
      }
     } while (repeat);
    }
    fclose(coafile);
    if (local_arg->uV_per_bit==NULL) {
     TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No channel table found in file %s\n", MSGPARM(coa_name));
    }
    if (local_arg->segment_table.buffer_start==NULL) {
     TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No segment table found in file %s\n", MSGPARM(coa_name));
    }
    /* Determine the exact number of points in file: Start with the previous
     * segment and add the last segment. */
    fstat(fileno(infile),&statbuf);
    //printf("File size is %ld\n", statbuf.st_size);
    //printf("Last segment (EOF) at %ld\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
    while (local_arg->segment_table.current_length>=1 && ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]>=statbuf.st_size) {
     //printf("%ld - Removing last segment!\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
     local_arg->segment_table.current_length--;
    }
    /* Size without the last segment */
    tinfo->points_in_file=(local_arg->segment_table.current_length/sizeof(long)-1)*SEGMENT_LENGTH;
    /* Count the points in the last segment */
    {
     array myarray;
     int length_of_last_segment=0;
     myarray.element_skip=tinfo->itemsize=1;
     myarray.nr_of_vectors=1;
     myarray.nr_of_elements=local_arg->nr_of_channels;
     if (array_allocate(&myarray)==NULL) {
      ERREXIT(tinfo->emethods, "read_freiburg_init: Error allocating myarray\n");
     }
     fseek(infile, ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1], SEEK_SET);
     //printf("Seeking to %ld\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
     tinfo->nr_of_channels=local_arg->nr_of_channels; /* This is used by freiburg_get_segment_init! */
     freiburg_get_segment_init(tinfo);
     while (freiburg_get_segment(tinfo, &myarray)==0) length_of_last_segment++;
     freiburg_get_segment_free(tinfo);
     tinfo->points_in_file+=length_of_last_segment;
     TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Last segment has %ld points\n",length_of_last_segment);
     array_free(&myarray);
    }
   }
   if (local_arg->channelnames==NULL && local_arg->btfile.text[0]=='\0') {
    local_arg->in_channels= &goeppi_channels[0];
    TRACEMS(tinfo->emethods, 0, "read_freiburg_init: Assuming Goeppingen style setup!\n");
   }
   local_arg->continuous_type=SLEEP_BT_TYPE;
   TRACEMS(tinfo->emethods, 1, "read_freiburg_init: Opened file in BT format\n");
  } else {
   if((infile=fopen(args[ARGS_IFILE].arg.s,"rb"))==NULL) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't open file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
   }
   if (args[ARGS_REPAIR_OFFSET].is_set) {
    fseek(infile, args[ARGS_REPAIR_OFFSET].arg.i, SEEK_SET);
   } else {
   if (read_struct((char *)&local_arg->btfile, sm_BT_file, infile)==0) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Header read error in file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
   }
#  ifdef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->btfile, sm_BT_file);
#  endif
   }
   local_arg->continuous_type=SLEEP_KL_TYPE;
   /* Year and day are swapped in KL format with respect to BT format... */
   {short buf=local_arg->btfile.start_year; local_arg->btfile.start_year=local_arg->btfile.start_day; local_arg->btfile.start_day=buf;}
   /* Well, sometimes or most of the time, in KL files the sampling interval 
    * was not set correctly... */
   if (!args[ARGS_SFREQ].is_set && local_arg->btfile.sampling_interval_us!=9765 && local_arg->btfile.sampling_interval_us!=9766) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: sampling_interval_us was %d, corrected!\n", MSGPARM(local_arg->btfile.sampling_interval_us));
    local_arg->btfile.sampling_interval_us=9766;
   }
   TRACEMS(tinfo->emethods, 1, "read_freiburg_init: Opened file in KL format\n");
  }
  if (args[ARGS_REPAIR_CHANNELS].is_set) local_arg->btfile.nr_of_channels=args[ARGS_REPAIR_CHANNELS].arg.i;
  tinfo->nr_of_channels=local_arg->btfile.nr_of_channels;
  if (tinfo->nr_of_channels<=0 || tinfo->nr_of_channels>MAX_NUMBER_OF_CHANNELS_IN_EP) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Impossible: %d channels?\n", MSGPARM(tinfo->nr_of_channels));
  }
  if (local_arg->nr_of_channels==0) {
   local_arg->nr_of_channels=tinfo->nr_of_channels;
  } else {
   if (local_arg->nr_of_channels!=tinfo->nr_of_channels) {
    ERREXIT2(tinfo->emethods, "read_freiburg_init: Setup has %d channels, but the file has %d!\n", MSGPARM(local_arg->nr_of_channels), MSGPARM(tinfo->nr_of_channels));
   }
  }
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 1.0e6/local_arg->btfile.sampling_interval_us);
  tinfo->sfreq=local_arg->sfreq;
  if (tinfo->sfreq<=0.0 || tinfo->sfreq>MAX_POSSIBLE_SFREQ) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Impossible: sfreq=%gHz?\n", MSGPARM(tinfo->sfreq));
  }

  /*{{{  Parse arguments that can be in seconds*/
  tinfo->nr_of_points=gettimeslice(tinfo, args[ARGS_NCHANNELS].arg.s);
  if (tinfo->nr_of_points<=0) {
   /* Read the whole file as one epoch */
   TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Reading %ld points\n",tinfo->points_in_file);
   tinfo->nr_of_points=tinfo->points_in_file;
  }
  local_arg->offset=(args[ARGS_OFFSET].is_set ? gettimeslice(tinfo, args[ARGS_OFFSET].arg.s) : 0);
  local_arg->epochlength=tinfo->nr_of_points;
  /*}}}  */

  tinfo->beforetrig= -local_arg->offset;
  tinfo->aftertrig=tinfo->nr_of_points+local_arg->offset;
  /*}}}  */
 } else {
  local_arg->in_channels= &freiburg_channels[0];
  local_arg->current_trigger=0;
  if (stat(args[ARGS_IFILE].arg.s, &statbuf)!=0) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't stat file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
  }
  local_arg->nr_of_channels=atoi(args[ARGS_NCHANNELS].arg.s);
  /* average mode if the name does not belong to a directory */
  local_arg->average_mode= !S_ISDIR(statbuf.st_mode);
  tinfo->nr_of_channels=MAX_NUMBER_OF_CHANNELS_IN_EP;
 }
 freiburg_get_segment_init(tinfo);
 local_arg->current_point=0;

 tinfo->methods->init_done=TRUE;
}
Esempio n. 17
0
/*{{{  write_synamps_init(transform_info_ptr tinfo) {*/
METHODDEF void
write_synamps_init(transform_info_ptr tinfo) {
 struct write_synamps_storage *local_arg=(struct write_synamps_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 double xmin, xmax, ymin, ymax;
 int NoOfChannels=tinfo->nr_of_channels;
 int channel;

 growing_buf_init(&local_arg->triggers);
 local_arg->output_format=(args[ARGS_OUTPUTFORMAT].is_set ? (enum output_formats)args[ARGS_OUTPUTFORMAT].arg.i : FORMAT_EEGFILE);
 local_arg->SCAN=fopen(args[ARGS_OFILE].arg.s, "r+b");
 if (!args[ARGS_APPEND].is_set || local_arg->SCAN==NULL) {   /* target does not exist*/
 /*{{{  Create file*/
 if (local_arg->SCAN!=NULL) fclose(local_arg->SCAN);
 /*{{{  Calculate the span in x-y channel positions*/
 xmin=ymin=  FLT_MAX; 
 xmax=ymax= -FLT_MAX; 
 for (channel=0; channel<tinfo->nr_of_channels; channel++) {
  const double this_x=tinfo->probepos[3*channel], this_y=tinfo->probepos[3*channel+1];
  if (this_x>xmax) xmax=this_x;
  if (this_x<xmin) xmin=this_x;
  if (this_y>ymax) ymax=this_y;
  if (this_y<ymin) ymin=this_y;
 }
 if (xmax==xmin) {
  xmax+=0.5;
  xmin-=0.5;
 }
 if (ymax==ymin) {
  ymax+=0.5;
  ymin-=0.5;
 }
 /*}}}  */

 if ((local_arg->SCAN=fopen(args[ARGS_OFILE].arg.s, "wb"))==NULL) {
  ERREXIT1(tinfo->emethods, "write_synamps_init: Can't open %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
 }
 /*{{{  Many settings, taken from example files...*/
 strcpy(local_arg->EEG.rev, "Version 3.0");
 local_arg->EEG.AdditionalFiles=local_arg->EEG.NextFile=local_arg->EEG.PrevFile=0;
 switch (local_arg->output_format) {
  case FORMAT_EEGFILE:
   local_arg->EEG.review = 1;
   local_arg->EEG.savemode=NSM_EEGF;
   local_arg->EEG.type = NTY_EPOCHED;
   local_arg->EEG.ContinousType=0;
   local_arg->EEG.nsweeps=local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=0;
   break;
  case FORMAT_CNTFILE:
   local_arg->EEG.review = 1;
   local_arg->EEG.savemode=NSM_CONT;
   local_arg->EEG.type = 0;
   local_arg->EEG.ContinousType=NST_SYNAMPS-NST_CONT0;
   local_arg->EEG.nsweeps=1;
   local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=0;
   break;
  case FORMAT_AVGFILE:
   local_arg->EEG.review = 0;
   local_arg->EEG.savemode=NSM_AVGD;
   local_arg->EEG.type = NTY_AVERAGED;
   local_arg->EEG.ContinousType=0;
   local_arg->EEG.nsweeps=local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=(tinfo->nrofaverages>0 ? tinfo->nrofaverages : 1);
   break;
 }
 /* Since the comment can be of arbitrary length and thus also larger than the
  * rest of the header, we should limit ourselves to the size of the id field */
 strncpy(local_arg->EEG.id, tinfo->comment, sizeof(local_arg->EEG.id));
 /* The date is coded in the comment, and read_synamps appends the date and time
  * from the corresponding fields and the contents of the id field, so that
  * the comment2time reader could be confused by the two date/time fields if we
  * would not somehow invalidate remnants of the date field here... */
 {char *slash;
  while ((slash=strchr(local_arg->EEG.id, '/'))!=NULL) {
   *slash='|';
  }
 }
 strcpy(local_arg->EEG.oper, "Unspecified");
 strcpy(local_arg->EEG.doctor, "Unspecified");
 strcpy(local_arg->EEG.referral, "Unspecified");
 strcpy(local_arg->EEG.hospital, "Unspecified");
 strcpy(local_arg->EEG.patient, "Unspecified");
 local_arg->EEG.age = 0;
 local_arg->EEG.sex = 'U';
 local_arg->EEG.hand = 'U';
 strcpy(local_arg->EEG.med, "Unspecified");
 strcpy(local_arg->EEG.category, "Unspecified");
 strcpy(local_arg->EEG.state, "Unspecified");
 strcpy(local_arg->EEG.label, "Unspecified");
 {short dd, mm, yy, yyyy, hh, mi, ss;
 if (comment2time(tinfo->comment, &dd, &mm, &yy, &yyyy, &hh, &mi, &ss)) {
  char buffer[16]; /* Must be long enough to fit date (10) and time (12) +1 */
  /* This is necessary because the date field was devised for 2-digit years.
   * With 4-digit years it uses all 10 bytes and the trailing zero
   * does not fit in any more. */
  snprintf(buffer, 16, "%02d/%02d/%04d", mm, dd, yyyy);
  strncpy(local_arg->EEG.date, buffer, sizeof(local_arg->EEG.date));
  snprintf(buffer, 16, "%02d:%02d:%02d", hh, mi, ss);
  strncpy(local_arg->EEG.time, buffer, sizeof(local_arg->EEG.time));
 }
 }
 local_arg->EEG.rejectcnt = 0;
 local_arg->EEG.pnts=(tinfo->data_type==FREQ_DATA ? tinfo->nroffreq : tinfo->nr_of_points);
 local_arg->EEG.nchannels=NoOfChannels;
 local_arg->EEG.avgupdate=1;
 local_arg->EEG.domain=(tinfo->data_type==FREQ_DATA ? 1 : 0);
 local_arg->EEG.variance=0;
 local_arg->EEG.rate=(uint16_t)rint(tinfo->sfreq);
 if (tinfo->data_type==FREQ_DATA) {
  /* I know that this field is supposed to contain the taper window size in %,
     but we need some way to store basefreq and 'rate' is only integer... */
  local_arg->EEG.SpectWinLength=tinfo->basefreq;
 }
 if (local_arg->EEG.rate==0) {
  local_arg->EEG.rate=1;
  TRACEMS(tinfo->emethods, 0, "write_synamps_init: Rate was zero, corrected to 1!\n");
 }
 local_arg->EEG.scale=3.4375;	/* This is a common sensitivity factor, used if sensitivities for channels are zero */
 local_arg->EEG.veogcorrect=0;
 local_arg->EEG.heogcorrect=0;
 local_arg->EEG.aux1correct=0;
 local_arg->EEG.aux2correct=0;
 local_arg->EEG.veogtrig=15;	/* Trigger threshold in percent of the maximum */
 local_arg->EEG.heogtrig=10;
 local_arg->EEG.aux1trig=10;
 local_arg->EEG.aux2trig=10;
 local_arg->EEG.veogchnl=find_channel_number(tinfo, "VEOG");
 local_arg->EEG.heogchnl=find_channel_number(tinfo, "HEOG");
 local_arg->EEG.veogdir=0;	/* 0=positive, 1=negative */
 local_arg->EEG.veog_n=10;	/* "Number of points per waveform", really: minimum acceptable # averages */
 local_arg->EEG.heog_n=10;
 local_arg->EEG.veogmaxcnt=(int16_t)rint(0.3*tinfo->sfreq);	/* "Number of observations per point", really: event window size in points */
 local_arg->EEG.heogmaxcnt=(int16_t)rint(0.5*tinfo->sfreq);
 local_arg->EEG.AmpSensitivity=10;	/* External Amplifier gain */
 local_arg->EEG.baseline=0;
 local_arg->EEG.reject=0;
 local_arg->EEG.trigtype=2;	/* 2=Port */
 local_arg->EEG.trigval=255;	/* Hold */
 local_arg->EEG.dir=0;	/* Invert (negative up)=0 */
 local_arg->EEG.dispmin= -1;	/* displayed y range */
 local_arg->EEG.dispmax= +1;
 local_arg->EEG.DisplayXmin=local_arg->EEG.AutoMin=local_arg->EEG.rejstart=local_arg->EEG.offstart=local_arg->EEG.xmin= -tinfo->beforetrig/tinfo->sfreq;
 local_arg->EEG.DisplayXmax=local_arg->EEG.AutoMax=local_arg->EEG.rejstop=local_arg->EEG.offstop=local_arg->EEG.xmax= tinfo->aftertrig/tinfo->sfreq;
 local_arg->EEG.zmin=0.0;
 local_arg->EEG.zmax=0.1;
 strcpy(local_arg->EEG.ref, "A1-A2");
 strcpy(local_arg->EEG.screen,   "--------");
 local_arg->EEG.CalMode=2;
 local_arg->EEG.CalMethod=0;
 local_arg->EEG.CalUpdate=1;
 local_arg->EEG.CalBaseline=0;
 local_arg->EEG.CalSweeps=5;
 local_arg->EEG.CalAttenuator=1;
 local_arg->EEG.CalPulseVolt=1;
 local_arg->EEG.CalPulseStart=0;
 local_arg->EEG.CalPulseStop=0;
 local_arg->EEG.CalFreq=10;
 strcpy(local_arg->EEG.taskfile, "--------");
 strcpy(local_arg->EEG.seqfile,  "--------");	/* Otherwise tries to read a seqfile */
 local_arg->EEG.HeadGain=150;
 local_arg->EEG.FspFValue=2.5;
 local_arg->EEG.FspBlockSize=200;
 local_arg->EEG.fratio=1.0;
 local_arg->EEG.minor_rev=12;	/* Necessary ! Otherwise a different file structure is assumed... */
 local_arg->EEG.eegupdate=1;

 local_arg->EEG.xscale=local_arg->EEG.yscale=0;
 local_arg->EEG.xsize=40;
 local_arg->EEG.ysize=20;
 local_arg->EEG.ACmode=0;

 local_arg->EEG.XScaleValue=XSCALEVALUE;
 local_arg->EEG.XScaleInterval=XSCALEINTERVAL;
 local_arg->EEG.YScaleValue=YSCALEVALUE;
 local_arg->EEG.YScaleInterval=YSCALEINTERVAL;

 local_arg->EEG.ScaleToolX1=20;
 local_arg->EEG.ScaleToolY1=170;
 local_arg->EEG.ScaleToolX2=23.1535;
 local_arg->EEG.ScaleToolY2=153.87;

 local_arg->EEG.port=715;
 local_arg->EEG.NumSamples=0;
 local_arg->EEG.FilterFlag=0;
 local_arg->EEG.LowCutoff=4;
 local_arg->EEG.LowPoles=2;
 local_arg->EEG.HighCutoff=50;
 local_arg->EEG.HighPoles=2;
 local_arg->EEG.FilterType=3;
 local_arg->EEG.FilterDomain=1;
 local_arg->EEG.SnrFlag=0;
 local_arg->EEG.CoherenceFlag=0;
 local_arg->EEG.ContinousSeconds=4;
 local_arg->EEG.ChannelOffset=sizeof(int16_t);
 local_arg->EEG.AutoCorrectFlag=0;
 local_arg->EEG.DCThreshold='F';
 /*}}}  */
 /*{{{  Write SETUP structure*/
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&local_arg->EEG, sm_SETUP);
# endif
 write_struct((char *)&local_arg->EEG, sm_SETUP, local_arg->SCAN);
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&local_arg->EEG, sm_SETUP);
# endif
 /*}}}  */

 if ((local_arg->Channels=(ELECTLOC *)calloc(NoOfChannels,sizeof(ELECTLOC)))==NULL) {
  ERREXIT(tinfo->emethods, "write_synamps_init: Error allocating Channels list\n");
 }
 for (channel=0; channel<NoOfChannels; channel++) {
  /*{{{  Settings in the channel structure*/
  strncpy(local_arg->Channels[channel].lab, tinfo->channelnames[channel],sizeof(local_arg->Channels[channel].lab));
  local_arg->Channels[channel].reference=0;
  local_arg->Channels[channel].skip=0;
  local_arg->Channels[channel].reject=0;
  local_arg->Channels[channel].display=1;
  local_arg->Channels[channel].bad=0;
  local_arg->Channels[channel].n=(local_arg->output_format==FORMAT_AVGFILE ? local_arg->EEG.acceptcnt : (local_arg->output_format==FORMAT_CNTFILE ? 0 : 1));
  local_arg->Channels[channel].avg_reference=0;
  local_arg->Channels[channel].ClipAdd=0;
  local_arg->Channels[channel].x_coord= (tinfo->probepos[3*channel  ]-xmin)/(xmax-xmin)*RANGE_TO_COVER+XOFFSET;
  local_arg->Channels[channel].y_coord=((ymax-tinfo->probepos[3*channel+1])/(ymax-ymin)*RANGE_TO_COVER+YOFFSET)/3;
  local_arg->Channels[channel].veog_wt=0;
  local_arg->Channels[channel].veog_std=0;
  local_arg->Channels[channel].heog_wt=0;
  local_arg->Channels[channel].heog_std=0;
  local_arg->Channels[channel].baseline=0;
  local_arg->Channels[channel].Filtered=0;
  local_arg->Channels[channel].sensitivity=204.8/args[ARGS_CONVFACTOR].arg.d; /* This arranges for conv_factor to act as the expected product before integer truncation */
  local_arg->Channels[channel].Gain=5;
  local_arg->Channels[channel].HiPass=0;	/* 0=DC */
  local_arg->Channels[channel].LoPass=4;
  local_arg->Channels[channel].Page=0;
  local_arg->Channels[channel].Size=0;
  local_arg->Channels[channel].Impedance=0;
  local_arg->Channels[channel].PhysicalChnl=channel;	/* Channel mapping */
  local_arg->Channels[channel].Rectify=0;
  local_arg->Channels[channel].calib=1.0;
  /*}}}  */
  /*{{{  Write ELECTLOC struct*/
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  write_struct((char *)&local_arg->Channels[channel], sm_ELECTLOC, local_arg->SCAN);
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  /*}}}  */
 }
 local_arg->SizeofHeader = ftell(local_arg->SCAN);
 TRACEMS2(tinfo->emethods, 1, "write_synamps_init: Creating file %s, format `%s'\n", MSGPARM(args[ARGS_OFILE].arg.s), MSGPARM(neuroscan_subtype_names[NEUROSCAN_SUBTYPE(&local_arg->EEG)]));
 /*}}}  */
 } else {
  /*{{{  Append to file*/
  enum NEUROSCAN_SUBTYPES SubType;
  if (read_struct((char *)&local_arg->EEG, sm_SETUP, local_arg->SCAN)==0) {
   ERREXIT(tinfo->emethods, "write_synamps_init: Can't read file header.\n");
  }
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->EEG, sm_SETUP);
#  endif
  NoOfChannels = local_arg->EEG.nchannels;
  /*{{{  Allocate channel header*/
  if ((local_arg->Channels=(ELECTLOC *)malloc(NoOfChannels*sizeof(ELECTLOC)))==NULL) {
   ERREXIT(tinfo->emethods, "write_synamps_init: Error allocating Channels list\n");
  }
  /*}}}  */
  for (channel=0; channel<NoOfChannels; channel++) {
   if (read_struct((char *)&local_arg->Channels[channel], sm_ELECTLOC, local_arg->SCAN)==0) {
    ERREXIT(tinfo->emethods, "write_synamps_init: Can't read channel headers.\n");
   }
#  ifndef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  }
  local_arg->SizeofHeader = ftell(local_arg->SCAN);
  SubType=NEUROSCAN_SUBTYPE(&local_arg->EEG);
  switch (SubType) {
   case NST_EPOCHS:
    if (local_arg->output_format!=FORMAT_EEGFILE) {
     TRACEMS(tinfo->emethods, 0, "write_synamps_init: Appending to epoch file, discarding option -c\n");
     local_arg->output_format=FORMAT_EEGFILE;
    }
    fseek(local_arg->SCAN, 0, SEEK_END);
    break;
   case NST_CONTINUOUS:
   case NST_SYNAMPS: {
    TEEG TagType;
    EVENT1 event;
    if (local_arg->output_format!=FORMAT_CNTFILE) {
     TRACEMS(tinfo->emethods, 0, "write_synamps_init: Appending to continuous file, assuming option -c\n");
     local_arg->output_format=FORMAT_CNTFILE;
    }
    fseek(local_arg->SCAN, local_arg->EEG.EventTablePos, SEEK_SET);
    /* Here we face two evils in one header: Coding enums as chars and
     * allowing longs at odd addresses. Well... */
    if (1==read_struct((char *)&TagType, sm_TEEG, local_arg->SCAN)) {
#    ifndef LITTLE_ENDIAN
     change_byteorder((char *)&TagType, sm_TEEG);
#    endif
     if (TagType.Teeg==TEEG_EVENT_TAB1) {
      /*{{{  Read the event table*/
      int tag;
      int const ntags=TagType.Size/sm_EVENT1[0].offset;	/* sm_EVENT1[0].offset is sizeof(EVENT1) in the file. */
      for (tag=0; tag<ntags; tag++) {
       if (1!=read_struct((char *)&event, sm_EVENT1, local_arg->SCAN)) {
	ERREXIT(tinfo->emethods, "write_synamps_init: Can't read an event table entry.\n");
	break;
       }
#      ifndef LITTLE_ENDIAN
       change_byteorder((char *)&event, sm_EVENT1);
#      endif
       {
       int const TrigVal=event.StimType &0xff;
       int const KeyBoard=event.KeyBoard&0xf;
       int const KeyPad=Event_KeyPad_value(event);
       int const Accept=Event_Accept_value(event);
       int code=TrigVal-KeyPad+neuroscan_accept_translation[Accept];
       if (code==0) {
        code= -((KeyBoard+1)<<4);
       }
       push_trigger(&local_arg->triggers,offset2point(tinfo, event.Offset),code,NULL);
       }
      }
      /*}}}  */
     } else {
      ERREXIT(tinfo->emethods, "write_synamps_init: Type 2 events are not yet supported.\n");
     }
    } else {
     ERREXIT(tinfo->emethods, "write_synamps_init: Can't read the event table header.\n");
    }
    fseek(local_arg->SCAN, local_arg->EEG.EventTablePos, SEEK_SET);
    }
    break;
   default:
    ERREXIT1(tinfo->emethods, "write_synamps: Cannot append to file type `%s'\n", MSGPARM(neuroscan_subtype_names[SubType]));
    break;
  }
  /* Conformance to the incoming epochs is checked in write_synamps */
  TRACEMS1(tinfo->emethods, 1, "write_synamps_init: Appending to file %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
  /*}}}  */
 }

 tinfo->methods->init_done=TRUE;
}
Esempio n. 18
0
METHODDEF DATATYPE *
read_freiburg(transform_info_ptr tinfo) {
 struct read_freiburg_storage *local_arg=(struct read_freiburg_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 struct freiburg_channels_struct *in_channels=local_arg->in_channels;
 array myarray;
 FILE *infile;
 int i, point, channel;
 int trial_not_accepted;
 long length_of_data;
 short header[FREIBURG_HEADER_LENGTH/sizeof(short)];
 char const *last_sep=strrchr(args[ARGS_IFILE].arg.s, PATHSEP);
 char const *last_component=(last_sep==NULL ? args[ARGS_IFILE].arg.s : last_sep+1);
 char comment[MAX_COMMENTLEN];

 tinfo->nrofaverages=1;
 if (args[ARGS_CONTINUOUS].is_set) {
  /*{{{  Read an epoch from a continuous file*/
  infile=local_arg->infile;

  if (local_arg->epochs--==0) return NULL;

  /*{{{  Configure myarray*/
  myarray.element_skip=tinfo->itemsize=1;
  myarray.nr_of_vectors=tinfo->nr_of_points=local_arg->epochlength;
  myarray.nr_of_elements=tinfo->nr_of_channels=local_arg->nr_of_channels;
  if (array_allocate(&myarray)==NULL) {
   ERREXIT(tinfo->emethods, "read_freiburg: Error allocating data\n");
  }
  tinfo->multiplexed=TRUE;
  /*}}}  */

  do {
   do {
    if (local_arg->segment_table.buffer_start!=NULL && local_arg->current_point%SEGMENT_LENGTH==0) {
     int const segment=local_arg->current_point/SEGMENT_LENGTH;
     long const nr_of_segments=local_arg->segment_table.current_length/sizeof(long);
     if (segment>=nr_of_segments) {
      array_free(&myarray);
      return NULL;
     }
     fseek(infile, ((long *)local_arg->segment_table.buffer_start)[segment], SEEK_SET);
     local_arg->no_last_values=TRUE;
    }
    if (freiburg_get_segment(tinfo, &myarray)!=0) {
     array_free(&myarray);
     return NULL;
    }
   } while (myarray.message!=ARRAY_ENDOFSCAN);
  } while (--local_arg->fromepoch>0);
  snprintf(comment, MAX_COMMENTLEN, "%s %s %02d/%02d/%04d,%02d:%02d:%02d", (local_arg->continuous_type==SLEEP_BT_TYPE ? "sleep_BT" : "sleep_KL"), last_component, local_arg->btfile.start_month, local_arg->btfile.start_day, local_arg->btfile.start_year, local_arg->btfile.start_hour, local_arg->btfile.start_minute, local_arg->btfile.start_second);
  tinfo->sfreq=local_arg->sfreq;
  /*}}}  */
 } else
 /*{{{  Read an epoch from a single (epoched or averaged) file*/
 do {	/* Return here if trial was not accepted */
 trial_not_accepted=FALSE;

 if (local_arg->epochs--==0 || (local_arg->average_mode && local_arg->current_trigger>=1)) return NULL;

 if (local_arg->average_mode) {
  /*{{{  Prepare reading an averaged file*/
  if((infile=fopen(args[ARGS_IFILE].arg.s,"rb"))==NULL) {
   ERREXIT1(tinfo->emethods, "read_freiburg: Can't open file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
  }
  fseek(infile, 0, SEEK_END);
  length_of_data=ftell(infile)-FREIBURG_HEADER_LENGTH;
  local_arg->current_trigger++;
  snprintf(comment, MAX_COMMENTLEN, "Freiburg-avg %s", last_component);
  /*}}}  */
 } else {
  /*{{{  Build pathname of the single trial to read*/
  /* A directory name was given. */
  char const * const expnumber=args[ARGS_IFILE].arg.s+strlen(args[ARGS_IFILE].arg.s)-2;
#ifdef __GNUC__
#define NEWFILENAME_SIZE (strlen(args[ARGS_IFILE].arg.s)+strlen(last_component)+20)
#else
#define NEWFILENAME_SIZE MAX_PATHLEN
#endif
  char newfilename[NEWFILENAME_SIZE];
  do {	/* Files from which only the parameter part exists are rejected */
   int div100=local_arg->current_trigger/100, mod100=local_arg->current_trigger%100;
   snprintf(newfilename, NEWFILENAME_SIZE, "%s%c%s%02d%c%c%s%02d%02d", args[ARGS_IFILE].arg.s, PATHSEP, last_component, div100, PATHSEP, tolower(expnumber[-1]), expnumber, div100, mod100);
   TRACEMS1(tinfo->emethods, 1, "read_freiburg: Constructed filename %s\n", MSGPARM(newfilename));

   if((infile=fopen(newfilename,"rb"))==NULL) {
    if (local_arg->current_trigger==0) {
     ERREXIT1(tinfo->emethods, "read_freiburg: Can't open file %s\n", MSGPARM(newfilename));
    } else {
     return NULL;
    }
   }
   fseek(infile, 0, SEEK_END);
   length_of_data=ftell(infile)-FREIBURG_HEADER_LENGTH;
   local_arg->current_trigger++;
  } while (length_of_data==0 || --local_arg->fromepoch>0);
  snprintf(comment, MAX_COMMENTLEN, "Freiburg-raw %s", last_component);
  /*}}}  */
 }

 /*{{{  Read the 64-Byte header*/
 fseek(infile, 0, SEEK_SET);
 fread(header, 1, FREIBURG_HEADER_LENGTH, infile);
 for (i=0; i<18; i++) {
# ifdef LITTLE_ENDIAN
  Intel_int16((uint16_t *)&header[i]);
# endif
  TRACEMS2(tinfo->emethods, 3, "read_freiburg: Header %02d: %d\n", MSGPARM(i), MSGPARM(header[i]));
 }
 /*}}}  */

 if (local_arg->average_mode) {
  if ((length_of_data/sizeof(short))%local_arg->nr_of_channels!=0) {
   ERREXIT2(tinfo->emethods, "read_freiburg: length_of_data=%d does not fit with nr_of_channels=%d\n", MSGPARM(length_of_data), MSGPARM(local_arg->nr_of_channels));
  }
  tinfo->nr_of_points=(length_of_data/sizeof(short))/local_arg->nr_of_channels;
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 200.0); /* The most likely value */
 } else {
  local_arg->nr_of_channels=header[14];
  /* Note: In a lot of experiments, one point MORE is available in the data
   * than specified in the header, but this occurs erratically. We could only
   * check for this during decompression, but that's probably too much fuss. */
  tinfo->nr_of_points=header[16]/header[15];
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 1000.0/header[15]);
 }
 tinfo->sfreq=local_arg->sfreq;
 /*{{{  Parse arguments that can be in seconds*/
 local_arg->offset=(args[ARGS_OFFSET].is_set ? gettimeslice(tinfo, args[ARGS_OFFSET].arg.s) : 0);
 /*}}}  */
 tinfo->beforetrig= -local_arg->offset;
 tinfo->aftertrig=tinfo->nr_of_points+local_arg->offset;

 /*{{{  Configure myarray*/
 myarray.element_skip=tinfo->itemsize=1;
 myarray.nr_of_vectors=tinfo->nr_of_points;
 myarray.nr_of_elements=tinfo->nr_of_channels=local_arg->nr_of_channels;
 if (array_allocate(&myarray)==NULL) {
  ERREXIT(tinfo->emethods, "read_freiburg: Error allocating data\n");
 }
 tinfo->multiplexed=TRUE;
 /*}}}  */

 fseek(infile, FREIBURG_HEADER_LENGTH, SEEK_SET);
 if (local_arg->average_mode) {
  /*{{{  Read averaged epoch*/
  for (point=0; point<tinfo->nr_of_points; point++) {
#ifdef __GNUC__
   short buffer[tinfo->nr_of_channels];
#else
   short buffer[MAX_NR_OF_CHANNELS];
#endif
   if ((int)fread(buffer, sizeof(short), tinfo->nr_of_channels, infile)!=tinfo->nr_of_channels) {
    ERREXIT1(tinfo->emethods, "read_freiburg: Error reading data point %d\n", MSGPARM(point));
   }
   for (channel=0; channel<tinfo->nr_of_channels; channel++) {
#  ifdef LITTLE_ENDIAN
    Intel_int16((uint16_t *)&buffer[channel]);
#  endif
    array_write(&myarray, (DATATYPE)buffer[channel]);
   }
  }
  /*}}}  */
 } else {
  /*{{{  Read compressed single trial*/
#  ifdef DISPLAY_ADJECTIVES
  char *adjektiv_ende=strchr(((char *)header)+36, ' ');
  if (adjektiv_ende!=NULL) *adjektiv_ende='\0';
  printf("Single trial: nr_of_points=%d, nr_of_channels=%d, Adjektiv=%s\n", tinfo->nr_of_points, tinfo->nr_of_channels, ((char *)header)+36);
#  endif
  local_arg->infile=infile;
  do {
   if (freiburg_get_segment(tinfo, &myarray)!=0) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg: Decompression out of bounds for trial %d - skipped\n", MSGPARM(local_arg->current_trigger-1));
    array_free(&myarray);
    trial_not_accepted=TRUE;
    break;
   }
  } while (myarray.message!=ARRAY_ENDOFSCAN);
  /*}}}  */
 }
 fclose(infile);
 } while (trial_not_accepted);
 /*}}}  */

 /*{{{  Look for a Freiburg channel setup for this number of channels*/
 /* Force create_channelgrid to really allocate the channel info anew.
  * Otherwise, free_tinfo will free someone else's data ! */
 tinfo->channelnames=NULL; tinfo->probepos=NULL;
 if (local_arg->channelnames!=NULL) {
  copy_channelinfo(tinfo, local_arg->channelnames, NULL);
 } else {
  while (in_channels->nr_of_channels!=0 && in_channels->nr_of_channels!=tinfo->nr_of_channels) in_channels++;
  if (in_channels->nr_of_channels==0) {
   TRACEMS1(tinfo->emethods, 1, "read_freiburg: Don't have a setup for %d channels.\n", MSGPARM(tinfo->nr_of_channels));
  } else {
   copy_channelinfo(tinfo, in_channels->channelnames, NULL);
  }
 }
 create_channelgrid(tinfo); /* Create defaults for any missing channel info */
 /*}}}  */
 
 if ((tinfo->comment=(char *)malloc(strlen(comment)+1))==NULL) {
  ERREXIT(tinfo->emethods, "read_freiburg: Error allocating comment memory\n");
 }
 strcpy(tinfo->comment, comment);

 if (local_arg->zero_idiotism_warned==FALSE && local_arg->zero_idiotism_encountered) {
  TRACEMS(tinfo->emethods, 0, "read_freiburg: All-zero data points have been encountered and omitted!\n");
  local_arg->zero_idiotism_warned=TRUE;
 }
 tinfo->z_label=NULL;
 tinfo->tsdata=myarray.start;
 tinfo->length_of_output_region=tinfo->nr_of_channels*tinfo->nr_of_points;
 tinfo->leaveright=0;
 tinfo->data_type=TIME_DATA;

 return tinfo->tsdata;
}