Ejemplo n.º 1
0
/**
 * Compares two lists of files and records the results into the master receipt
 */
void compare_records(FILE *rcpt, FILE *before, FILE *after)
{
	struct record *rbef = malloc(sizeof(struct record));
	struct record *raft = malloc(sizeof(struct record));
	
	while (read_struct(raft, after) == 0)
	{
		assert(read_struct(rbef, before) >= 0);
		
		// if there are new files, go until we're synced up
		while (strcmp(raft->filename, rbef->filename) != 0)
		{
			write_struct(raft, rcpt);
			free(raft->filename);
			if (read_struct(raft, after) != 0)
			{
				free(rbef->filename);
				goto cleanup;
			}
		}
		
		// file was modified, so record it
		if (raft->modified.tv_sec > rbef->modified.tv_sec)
		{
			write_struct(raft, rcpt);
		}
		
		free(raft->filename);
		free(rbef->filename);
	}
	
	cleanup:
		free(rbef);
		free(raft);
}
Ejemplo n.º 2
0
void
write_warmstart(void)
{
	(void) write_struct(RPCBFILE, (xdrproc_t)xdr_rpcblist_ptr, &list_rbl);
#ifdef PORTMAP
	(void) write_struct(PMAPFILE, (xdrproc_t)xdr_pmaplist_ptr, &list_pml);
#endif

}
Ejemplo n.º 3
0
int
free_blocknum(int blocknum)
{
	vcb_t *vcbp = retrieve_vcb();
	free_t freeb;
	freeb.f_next = vcbp->vb_free;
	if (write_struct(blocknum, &freeb) < 0)
		return -1;
	vcbp->vb_free = blocknum;
	write_struct(0, vcbp);
	return 0;
}
Ejemplo n.º 4
0
static char *def_tuple(CTX *ctx, struct ir_struct_type *st, bool add_names)
{
    // NOTE: we use the same C type for empty tuples and compounds; should be ok
    if (st->members_count == 0)
        return VOID_MANGLE;
    char *m = get_mangle(ctx, st);
    if (m)
        return m;
    assert(ctx->writing_types);
    m = talloc_strdup(ctx, MANGLE_PREFIX "tuple_");
    for (int n = 0; n < st->members_count; n++) {
        struct ir_struct_member *sm = st->members[n];
        mangle_append_sub(&m, def_type(ctx, sm->type));
        assert(add_names == (sm->name[0]));
        if (sm->name)
            m = talloc_asprintf_append_buffer(m, "n%zd_%s_", strlen(sm->name),
                                              sm->name);
    }
    if (use_anon_mangle_for_tuples) {
        char *new_mangle = HT_GET_DEF(dstr, dstr, ctx->tuple_abbrev, m, NULL);
        if (!new_mangle) {
            new_mangle = gen_anon_mangle(ctx, "tuple");
            HT_INSERT(dstr, dstr, ctx->tuple_abbrev, m, new_mangle);
        }
        m = new_mangle;
    }
    add_mangle(ctx, st, m);
    if (!check_redef(ctx, m))
        write_struct(ctx, st, m);
    return m;
}
Ejemplo n.º 5
0
int issue_noarg_command(u8 cmd)
{
	struct noarg_request req;
	debug_printf(4, "%s() cmd: %d\n", __func__, cmd);
	req.req = cmd;
	write_struct(REQM, &req);
	return wait_for_response();
}
Ejemplo n.º 6
0
int card_info_cmd(enum card_info_subcommand cmd)
{
	struct card_info_req cir;
	cir.o = 'o';
	cir.subcommand = cmd;

	write_struct(REQM, &cir);
	return wait_for_response();
}
Ejemplo n.º 7
0
int get_log_at_offset(u32 offset)
{
	struct fetch_log_cmd cmd;
	cmd.m = 'm';
	cmd.offset = u32_to_be32(offset);

	debug_printf(2, "getting log at offset: %08x\n", offset);
	write_struct(REQM, &cmd);
	return wait_for_response();
}
Ejemplo n.º 8
0
void inc_seq(void)
{
	/*
	 * Oddly enough, the sequence number appears
	 * to be of normal endianness.
	 */
	//u32 tmpseq = be32_to_u32(seq.seq);
	//seq.seq = u32_to_be32(tmpseq+1);
	eyefi_seq.seq++;
	write_struct(REQC, &eyefi_seq);
}
Ejemplo n.º 9
0
int 	 
get_free_blocknum()
{
	vcb_t *vbp = retrieve_vcb();
	int res = vbp->vb_free;
	free_t freeb;
	if (res > 0)
		read_struct(res, &freeb);
	vbp->vb_free = freeb.f_next;
	write_struct(0, vbp);
	return res;
}
Ejemplo n.º 10
0
static char *def_struct(CTX *ctx, struct ir_struct_type *st)
{
    char *m = get_mangle(ctx, st);
    if (m)
        return m;
    assert(ctx->writing_types);
    // In theory we must not mangle at all. If there is C code that
    // uses the same struct, they must use the same name (and have
    // the same members and so on).
    // xxx handle structs nested inside functions
    m = talloc_strdup(ctx, st->name);
    add_mangle(ctx, st, m);
    write_struct(ctx, st, m);
    return m;
}
Ejemplo n.º 11
0
int network_action(char cmd, char *essid, char *ascii_password)
{
	struct net_request nr;
	memset(&nr, 0, sizeof(nr));

	nr.req = cmd;
	strcpy(&nr.essid[0], essid);
	nr.essid_len = strlen(essid);

	if (ascii_password) {
		int ret = make_network_key(&nr.key, essid, ascii_password);
		if (ret)
			return ret;
	}
	write_struct(REQM, &nr);
	return wait_for_response();
}
Ejemplo n.º 12
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--;
      }
     }
    }
   }
Ejemplo n.º 13
0
/*{{{  write_rec_close_file(transform_info_ptr tinfo) {*/
LOCAL void
write_rec_close_file(transform_info_ptr tinfo) {
 struct write_rec_storage *local_arg=(struct write_rec_storage *)tinfo->methods->local_storage;
 char numbuf[NUMBUF_LENGTH];

 snprintf(numbuf, NUMBUF_LENGTH, "%ld", local_arg->nr_of_records);
 memset(&local_arg->fheader.nr_of_records, ' ', sizeof(local_arg->fheader.nr_of_records));
 copy_nstring(local_arg->fheader.nr_of_records, numbuf, sizeof(local_arg->fheader.nr_of_records));
 fseek(local_arg->outfptr, 0L, SEEK_SET);
#ifndef LITTLE_ENDIAN
 change_byteorder((char *)&local_arg->fheader, sm_REC_file);
#endif
 write_struct((char *)&local_arg->fheader, sm_REC_file, local_arg->outfptr);
 if (local_arg->outfptr!=stdout && local_arg->outfptr!=stderr) {
  fclose(local_arg->outfptr);
 } else {
  fflush(local_arg->outfptr);
 }
}
Ejemplo n.º 14
0
/**
 * Recurses a given directory pointer, and writes data to the file
 * pointer when it finds files
 */
void record_files(char *path, DIR *dp, FILE *fp)
{
	struct dirent *ent;
	while ((ent = readdir(dp)) != NULL)
	{
		// skip dot files
		if (ent->d_name[0] != '.')
		{
			int pathsize = strlen(path) + ent->d_namlen + 2;
			char *newpath = malloc(pathsize * sizeof(char));
			snprintf(newpath, pathsize, "%s/%s", path, ent->d_name);
			
			if (ent->d_type == DT_DIR)
			{
				DIR *ndp = opendir(newpath);
				// we don't have permission, continue
				if (ndp == NULL)
				{
					continue;
				}
				
				record_files(newpath, ndp, fp);
				
				closedir(ndp);
			}
			else
			{
				struct stat info;
				assert(stat(newpath, &info) == 0);
				
				struct record rec;
				rec.filename = newpath;
				rec.modified = info.st_mtimespec;
				
				write_struct(&rec, fp);
			}
			
			free(newpath);
		}
	}
}
Ejemplo n.º 15
0
/*{{{  write_synamps(transform_info_ptr tinfo) {*/
METHODDEF DATATYPE *
write_synamps(transform_info_ptr calltinfo) {
 struct write_synamps_storage *local_arg=(struct write_synamps_storage *)calltinfo->methods->local_storage;
 transform_argument *args=calltinfo->methods->arguments;
 NEUROSCAN_EPOCHED_SWEEP_HEAD sweephead;
 long tsdata_step, tsdata_steps, tsdata_stepwidth;
 array myarray;
 /* Note that 'tinfo' instead of 'tinfoptr' is used here so that we don't have to modify 
  * all of the older code which stored only one epoch */
 transform_info_ptr tinfo=calltinfo;

 if (args[ARGS_LINKED].is_set) {
  /* Go to the start: */
  for (; tinfo->previous!=NULL; tinfo=tinfo->previous);
 }
 for (; tinfo!=NULL; tinfo=tinfo->next) {
  DATATYPE * const orig_tsdata=tinfo->tsdata;
 /*{{{  Assert that epoch size didn't change & itemsize==1*/
 if (tinfo->itemsize!=1) {
  ERREXIT(tinfo->emethods, "write_synamps: Only itemsize=1 is supported.\n");
 }
 if (local_arg->EEG.nchannels!=tinfo->nr_of_channels) {
  ERREXIT2(tinfo->emethods, "write_synamps: nr_of_channels was %d, now %d\n", MSGPARM(local_arg->EEG.nchannels), MSGPARM(tinfo->nr_of_channels));
 }
 /*}}}  */

 if (tinfo->data_type==FREQ_DATA) {
  tinfo->nr_of_points=tinfo->nroffreq;
  tsdata_steps=tinfo->nrofshifts;
  tsdata_stepwidth=tinfo->nr_of_channels*tinfo->nroffreq*tinfo->itemsize;
 } else {
  tsdata_steps=1;
  tsdata_stepwidth=0;
 }
 for (tsdata_step=0; tsdata_step<tsdata_steps; tinfo->tsdata+=tsdata_stepwidth, tsdata_step++) {
 switch (local_arg->output_format) {
  case FORMAT_EEGFILE:
 if (local_arg->EEG.pnts!=tinfo->nr_of_points) {
  ERREXIT2(tinfo->emethods, "write_synamps: nr_of_points was %d, now %d\n", MSGPARM(local_arg->EEG.pnts), MSGPARM(tinfo->nr_of_points));
 }
 /*{{{  Set sweephead values*/
 sweephead.accept=1;
 sweephead.type=254;
 sweephead.correct=0;
 sweephead.rt=0;
 sweephead.response=0;
 if (tinfo->condition>0) {
  sweephead.type=tinfo->condition&0xff;
 } else if (tinfo->condition<0 && (-tinfo->condition)<=0xf) {
  sweephead.type=0;
  sweephead.response= -tinfo->condition;
 } else {
  /* KeyBoard event: Do it the same way 'Edit' does when epoching,
   * mapping F1 to type=1 and so on (overlap with stim codes, but they
   * should know how they want it...) */
  sweephead.type= (-tinfo->condition)>>4;
 }
 /*}}}  */
 /*{{{  Write sweephead struct*/
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&sweephead, sm_NEUROSCAN_EPOCHED_SWEEP_HEAD);
# endif
 write_struct((char *)&sweephead, sm_NEUROSCAN_EPOCHED_SWEEP_HEAD, local_arg->SCAN);
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&sweephead, sm_NEUROSCAN_EPOCHED_SWEEP_HEAD);
# endif
 /*}}}  */
 local_arg->EEG.nsweeps++;	/* This gets patched into the header by write_synamps_exit */
 local_arg->EEG.compsweeps++;
 local_arg->EEG.acceptcnt++;
   break;
  case FORMAT_AVGFILE:
   if (local_arg->EEG.NumSamples!=0) {
    ERREXIT(tinfo->emethods, "write_synamps: Only a single epoch may be written to an .AVG file!\n");
   }
  case FORMAT_CNTFILE:
   if (tinfo->triggers.buffer_start!=NULL) {
    struct trigger *intrig=(struct trigger *)tinfo->triggers.buffer_start+1;
    while (intrig->code!=0) {
     push_trigger(&local_arg->triggers,local_arg->EEG.NumSamples+intrig->position,intrig->code,intrig->description);
     intrig++;
    }
   }
   local_arg->EEG.NumSamples+=tinfo->nr_of_points;
   break;
 }

 tinfo_array(tinfo, &myarray);
 if (local_arg->output_format==FORMAT_AVGFILE) {
  /* points are the elements */
  float *pdata, * const buffer=(float *)malloc(myarray.nr_of_elements*sizeof(float));
  const char *fill="\0\0\0\0\0";
  if (buffer==NULL) {
   ERREXIT(tinfo->emethods, "write_synamps: Error allocating AVGFILE buffer\n");
  }
  do {
   int const channel=myarray.current_vector;
   /* Write the `5-byte channel header that is no longer used' */
   fwrite(fill, 1, 5, local_arg->SCAN);
   pdata=buffer;
   do {
    *pdata=NEUROSCAN_FLOATCONV(&local_arg->Channels[channel], array_scan(&myarray));
# ifndef LITTLE_ENDIAN
    Intel_float(pdata);
# endif
    pdata++;
   } while (myarray.message==ARRAY_CONTINUE);
   if ((int)fwrite(buffer,sizeof(float),myarray.nr_of_elements,local_arg->SCAN)!=myarray.nr_of_elements) {
    ERREXIT(tinfo->emethods, "write_synamps: Error writing data point\n");
   }
  } while (myarray.message!=ARRAY_ENDOFSCAN);
  free(buffer);
 } else {
 int16_t * const buffer=(int16_t *)malloc(myarray.nr_of_vectors*sizeof(int16_t));
 if (buffer==NULL) {
  ERREXIT(tinfo->emethods, "write_synamps: Error allocating buffer\n");
 }
 array_transpose(&myarray);	/* channels are the elements */
 do {
  int channel=0;
  do {
   DATATYPE hold=array_scan(&myarray), hold2;
   /* Code anything exceeding the representable range, including +-Inf, as min/max representable value. */
   hold2=NEUROSCAN_SHORTCONV(&local_arg->Channels[channel], hold);
   if (hold2< -32768) hold2= -32768;
   else if (hold2> 32767) hold2= 32767;
   buffer[channel]=(int16_t)hold2;
# ifndef LITTLE_ENDIAN
   Intel_int16(&buffer[channel]);
# endif
   channel++;
  } while (myarray.message==ARRAY_CONTINUE);
  if ((int)fwrite(buffer,sizeof(int16_t),myarray.nr_of_elements,local_arg->SCAN)!=myarray.nr_of_elements) {
   ERREXIT(tinfo->emethods, "write_synamps: Error writing data point\n");
  }
 } while (myarray.message!=ARRAY_ENDOFSCAN);
 free(buffer);
 }
 } /* FREQ_DATA shifts loop */
 tinfo->tsdata=orig_tsdata;
  if (!args[ARGS_LINKED].is_set) {
   break;
  }
 } /* Linked epochs loop */

 return calltinfo->tsdata;	/* Simply to return something `useful' */
}
Ejemplo n.º 16
0
/*{{{  write_rec_open_file(transform_info_ptr tinfo) {*/
LOCAL void
write_rec_open_file(transform_info_ptr tinfo) {
 struct write_rec_storage *local_arg=(struct write_rec_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 FILE *outfptr=NULL;
 
 if (strcmp(args[ARGS_OFILE].arg.s, "stdout")==0) outfptr=stdout;
 else if (strcmp(args[ARGS_OFILE].arg.s, "stderr")==0) outfptr=stderr;
 local_arg->appendmode=args[ARGS_APPEND].is_set;
 if (local_arg->appendmode) {
  /*{{{  Append mode open if cofile exists and is of non-zero length*/
  if (outfptr==NULL) {
   if ((outfptr=fopen(args[ARGS_OFILE].arg.s, "r+b"))!=NULL) {
    fseek(outfptr, 0L, SEEK_END);
    if (ftell(outfptr)==0L) {
     local_arg->appendmode=FALSE;	/* If at start: write header */
    }
   }
  }
  /*}}}  */
 }
 if (outfptr==NULL) {
  /*{{{  Open the REC file in truncate mode*/
  local_arg->appendmode=FALSE;	/* write header */
  if ((outfptr=fopen(args[ARGS_OFILE].arg.s, "wb"))==NULL) {
   ERREXIT1(tinfo->emethods, "write_rec_open_file: Can't open %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
  }
  /*}}}  */
 }
 local_arg->outfptr=outfptr;
 if (local_arg->appendmode) {
  /* Read rather than write header in append mode */
  fseek(outfptr, 0L, SEEK_SET);
  if (read_struct((char *)&local_arg->fheader, sm_REC_file, outfptr)==0) {
   ERREXIT1(tinfo->emethods, "write_rec_open_file: Can't read header in file %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
  }
# ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->fheader, sm_REC_file);
# endif
  local_arg->nr_of_records=atoi(local_arg->fheader.nr_of_records);
  fseek(outfptr, 0L, SEEK_END);
 } else {
  /*{{{  Write header*/
  REC_channel_header channelheader;
  const long channelheader_length=CHANNELHEADER_SIZE_PER_CHANNEL*tinfo->nr_of_channels;
  int channel;
  short dd, mm, yy, yyyy, hh, mi, ss;
  char numbuf[NUMBUF_LENGTH];

  setlocale(LC_NUMERIC, "C"); /* Print fractional numbers with decimal point */
#define fileheader local_arg->fheader
  memset(&fileheader, ' ', sizeof(REC_file_header));
  copy_nstring(fileheader.version, "0", sizeof(fileheader.version));
  if (args[ARGS_PATIENT].is_set) copy_nstring(fileheader.patient, args[ARGS_PATIENT].arg.s, sizeof(fileheader.patient));
  if (args[ARGS_RECORDING].is_set) copy_nstring(fileheader.recording, args[ARGS_RECORDING].arg.s, sizeof(fileheader.recording));
  if (args[ARGS_DATETIME].is_set) {
   char * const comma=strchr(args[ARGS_DATETIME].arg.s, ',');
   if (comma==NULL) {
    ERREXIT(tinfo->emethods, "write_rec_open_file: Datetime format is dd.mm.yy,hh.mi.ss !\n");
   }
   copy_nstring(fileheader.startdate, args[ARGS_DATETIME].arg.s, sizeof(fileheader.startdate));
   copy_nstring(fileheader.starttime, comma+1, sizeof(fileheader.starttime));
  } else if (tinfo->comment!=NULL) {
   if (!args[ARGS_RECORDING].is_set) copy_nstring(fileheader.recording, tinfo->comment, sizeof(fileheader.recording));
   if (comment2time(tinfo->comment, &dd, &mm, &yy, &yyyy, &hh, &mi, &ss)) {
    snprintf(numbuf, NUMBUF_LENGTH, "%02d.%02d.%02d", dd, mm, yy);
    copy_nstring(fileheader.startdate, numbuf, sizeof(fileheader.startdate));
    snprintf(numbuf, NUMBUF_LENGTH, "%02d.%02d.%02d", hh, mi, ss);
    copy_nstring(fileheader.starttime, numbuf, sizeof(fileheader.starttime));
   }
  }
  if (*fileheader.startdate==' ') {
   /* Date/time weren't set otherwise: */
   copy_nstring(fileheader.startdate, "00.00.00", sizeof(fileheader.startdate));
   copy_nstring(fileheader.starttime, "00.00.00", sizeof(fileheader.starttime));
  }
  snprintf(numbuf, NUMBUF_LENGTH, "%ld", sm_REC_file[0].offset+channelheader_length);
  copy_nstring(fileheader.bytes_in_header, numbuf, sizeof(fileheader.bytes_in_header));
  copy_nstring(fileheader.data_format_version, (args[ARGS_DATA_FORMAT_VERSION].is_set ? args[ARGS_DATA_FORMAT_VERSION].arg.s : "write_rec file"), sizeof(fileheader.data_format_version));
  local_arg->nr_of_records=0;
  copy_nstring(fileheader.nr_of_records, "-1", sizeof(fileheader.nr_of_records));
  snprintf(numbuf, NUMBUF_LENGTH, "%g", ((double)local_arg->samples_per_record)/tinfo->sfreq);
  copy_nstring(fileheader.duration_s, numbuf, sizeof(fileheader.duration_s));
  snprintf(numbuf, NUMBUF_LENGTH, "%d", tinfo->nr_of_channels);
  copy_nstring(fileheader.nr_of_channels, numbuf, sizeof(fileheader.nr_of_channels));
#ifndef LITTLE_ENDIAN
  change_byteorder((char *)&fileheader, sm_REC_file);
#endif
  write_struct((char *)&fileheader, sm_REC_file, outfptr);
#ifndef LITTLE_ENDIAN
  change_byteorder((char *)&fileheader, sm_REC_file);
#endif
#undef fileheader

  if ((channelheader.label=(char (*)[16])malloc(channelheader_length))==NULL) {
   ERREXIT(tinfo->emethods, "write_rec_open_file: Error allocating channelheader memory\n");
  }
  channelheader.transducer=(char (*)[80])(channelheader.label+tinfo->nr_of_channels);
  channelheader.dimension=(char (*)[8])(channelheader.transducer+tinfo->nr_of_channels);
  channelheader.physmin=(char (*)[8])(channelheader.dimension+tinfo->nr_of_channels);
  channelheader.physmax=(char (*)[8])(channelheader.physmin+tinfo->nr_of_channels);
  channelheader.digmin=(char (*)[8])(channelheader.physmax+tinfo->nr_of_channels);
  channelheader.digmax=(char (*)[8])(channelheader.digmin+tinfo->nr_of_channels);
  channelheader.prefiltering=(char (*)[80])(channelheader.digmax+tinfo->nr_of_channels);
  channelheader.samples_per_record=(char (*)[8])(channelheader.prefiltering+tinfo->nr_of_channels);
  channelheader.reserved=(char (*)[32])(channelheader.samples_per_record+tinfo->nr_of_channels);
  memset(channelheader.label, ' ', channelheader_length);
  for (channel=0; channel<tinfo->nr_of_channels; channel++) {
   copy_nstring(channelheader.dimension[channel], "uV", sizeof(channelheader.dimension[channel]));
   copy_nstring(channelheader.label[channel], tinfo->channelnames[channel], sizeof(channelheader.label[channel]));
   snprintf(numbuf, NUMBUF_LENGTH, "%g", (double)local_arg->digmin*local_arg->resolution);
   copy_nstring(channelheader.physmin[channel], numbuf, sizeof(channelheader.physmin[channel]));
   snprintf(numbuf, NUMBUF_LENGTH, "%g", (double)local_arg->digmax*local_arg->resolution);
   copy_nstring(channelheader.physmax[channel], numbuf, sizeof(channelheader.physmax[channel]));
   snprintf(numbuf, NUMBUF_LENGTH, "%ld", local_arg->digmin);
   copy_nstring(channelheader.digmin[channel], numbuf, sizeof(channelheader.digmin[channel]));
   snprintf(numbuf, NUMBUF_LENGTH, "%ld", local_arg->digmax);
   copy_nstring(channelheader.digmax[channel], numbuf, sizeof(channelheader.digmax[channel]));
   snprintf(numbuf, NUMBUF_LENGTH, "%ld", local_arg->samples_per_record);
   copy_nstring(channelheader.samples_per_record[channel], numbuf, sizeof(channelheader.samples_per_record[channel]));
  }
  setlocale(LC_NUMERIC, ""); /* Reset locale to environment */
  if (tinfo->nr_of_channels!=(int)fwrite((void *)channelheader.label, CHANNELHEADER_SIZE_PER_CHANNEL, tinfo->nr_of_channels, local_arg->outfptr)) {
   ERREXIT(tinfo->emethods, "write_rec_open_file: Error writing channel headers\n");
  }
  free(channelheader.label);
  /*}}}  */
 }
}
Ejemplo n.º 17
0
/*{{{  write_vitaport_exit(transform_info_ptr tinfo) {*/
METHODDEF void
write_vitaport_exit(transform_info_ptr tinfo) {
    struct write_vitaport_storage *local_arg=(struct write_vitaport_storage *)tinfo->methods->local_storage;
    int channel, NoOfChannels=local_arg->fileheader.knum;
    long point;
    long const channellen=local_arg->total_points*sizeof(uint16_t);
    long const hdlen=local_arg->fileheader.hdlen;
    uint16_t checksum=0;

    local_arg->fileheaderII.dlen=hdlen+NoOfChannels*channellen;
    /*{{{  Write the file headers*/
# ifdef LITTLE_ENDIAN
    change_byteorder((char *)&local_arg->fileheader, sm_vitaport_fileheader);
    change_byteorder((char *)&local_arg->fileheaderII, sm_vitaportII_fileheader);
    change_byteorder((char *)&local_arg->fileext, sm_vitaportII_fileext);
# endif
    write_struct((char *)&local_arg->fileheader, sm_vitaport_fileheader, local_arg->outfile);
    write_struct((char *)&local_arg->fileheaderII, sm_vitaportII_fileheader, local_arg->outfile);
    write_struct((char *)&local_arg->fileext, sm_vitaportII_fileext, local_arg->outfile);
    /*}}}  */

    for (channel=0; channel<NoOfChannels; channel++) {
        /*{{{  Write a channel header*/
        /* This is the factor as we'd like to have it... */
        float factor=((float)(local_arg->channelmax[channel]> -local_arg->channelmin[channel] ? local_arg->channelmax[channel] : -local_arg->channelmin[channel]))/SHRT_MAX;

        if (strncmp(local_arg->channelheaders[channel].kname, VP_MARKERCHANNEL_NAME, 6)==0) {
            strcpy(local_arg->channelheaders[channel].kunit, "mrk");
            local_arg->channelheaders[channel].datype=VP_DATYPE_MARKER;
            /* Since the marker channel is read without the conversion factors,
             * set the conversion to 1.0 for this channel */
            local_arg->channelheaders[channel].mulfac=local_arg->channelheaders[channel].divfac=1;
            local_arg->channelheaders[channel].offset=0;
        } else {
            float const logdiff=log(factor)-TARGET_LOG_SHORTVAL;

            local_arg->channelheaders[channel].offset=0;
            if (logdiff<0) {
                /*{{{  Factor is small: Better to fix divfac and calculate mulfac after that*/
                double const divfac=exp(-logdiff);
                if (divfac>SHRT_MAX) {
                    local_arg->channelheaders[channel].divfac=SHRT_MAX;
                } else {
                    local_arg->channelheaders[channel].divfac=(unsigned short)divfac;
                }
                /* The +1 takes care that we never get below the `ideal' factor computed above. */
                local_arg->channelheaders[channel].mulfac=(unsigned short)(factor*local_arg->channelheaders[channel].divfac+1);
                if (local_arg->channelheaders[channel].mulfac==0) {
                    local_arg->channelheaders[channel].mulfac=1;
                    local_arg->channelheaders[channel].divfac=(unsigned short)(1.0/factor-1);
                }
                /*}}}  */
            } else {
                /*{{{  Factor is large: Better to fix mulfac and calculate divfac after that*/
                double const mulfac=exp(logdiff);
                if (mulfac>SHRT_MAX) {
                    local_arg->channelheaders[channel].mulfac=SHRT_MAX;
                } else {
                    local_arg->channelheaders[channel].mulfac=(unsigned short)mulfac;
                }
                /* The -1 takes care that we never get below the `ideal' factor computed above. */
                local_arg->channelheaders[channel].divfac=(unsigned short)(local_arg->channelheaders[channel].mulfac/factor-1);
                if (local_arg->channelheaders[channel].divfac==0) {
                    local_arg->channelheaders[channel].mulfac=(unsigned short)(factor+1);
                    local_arg->channelheaders[channel].divfac=1;
                }
                /*}}}  */
            }
        }
        /* Now see which factor we actually got constructed */
        factor=((float)local_arg->channelheaders[channel].mulfac)/local_arg->channelheaders[channel].divfac;

        local_arg->channelheadersII[channel].doffs=channel*channellen;
        local_arg->channelheadersII[channel].dlen=channellen;
#  ifdef LITTLE_ENDIAN
        change_byteorder((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader);
        change_byteorder((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader);
#  endif
        write_struct((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader, local_arg->outfile);
        write_struct((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader, local_arg->outfile);
#  ifdef LITTLE_ENDIAN
        change_byteorder((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader);
        change_byteorder((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader);
#  endif
        /*}}}  */
    }
    fwrite(&checksum, sizeof(checksum), 1, local_arg->outfile);

    TRACEMS(tinfo->emethods, 1, "write_vitaport_exit: Copying channels to output file...\n");

    /* We close and re-open the channel file because buffering is much more
     * efficient at least with DJGPP if the file is either only read or written */
    fclose(local_arg->channelfile);
    if ((local_arg->channelfile=fopen(local_arg->channelfilename, "rb"))==NULL) {
        ERREXIT1(tinfo->emethods, "write_vitaport_exit: Can't open temp file %s\n", MSGPARM(local_arg->channelfilename));
    }

    for (channel=0; channel<NoOfChannels; channel++) {
        /*{{{  Copy a channel to the target file */
        float const factor=((float)local_arg->channelheaders[channel].mulfac)/local_arg->channelheaders[channel].divfac;
        unsigned short const offset=local_arg->channelheaders[channel].offset;

        for (point=0; point<local_arg->total_points; point++) {
            DATATYPE dat;
            int16_t s;
            fseek(local_arg->channelfile, (point*NoOfChannels+channel)*sizeof(DATATYPE), SEEK_SET);
            if (fread(&dat, sizeof(DATATYPE), 1, local_arg->channelfile)!=1) {
                ERREXIT(tinfo->emethods, "write_vitaport_exit: Error reading temp file.\n");
            }
            s= (int16_t)rint(dat/factor)-offset;
#   ifdef LITTLE_ENDIAN
            Intel_int16((uint16_t *)&s);
#   endif
            if (fwrite(&s, sizeof(s), 1, local_arg->outfile)!=1) {
                ERREXIT(tinfo->emethods, "write_vitaport_exit: Write error.\n");
            }
        }
        /*}}}  */
    }
    fclose(local_arg->channelfile);
    unlink(local_arg->channelfilename);

    if (local_arg->triggers.current_length!=0) {
        long tagno, n_events;
        uint32_t length, trigpoint;
        int const nevents=local_arg->triggers.current_length/sizeof(struct trigger);
        struct vitaport_idiotic_multiplemarkertablenames *markertable_entry;

        /* Try to keep a security space of at least 20 free events */
        for (markertable_entry=markertable_names; markertable_entry->markertable_name!=NULL && markertable_entry->idiotically_fixed_length<nevents+20; markertable_entry++);
        if (markertable_entry->markertable_name==NULL) {
            if ((markertable_entry-1)->idiotically_fixed_length<=nevents) {
                /* Drop the requirement for at least 20 free events */
                markertable_entry--;
            } else {
                /* No use... */
                ERREXIT1(tinfo->emethods, "write_vitaport_exit: %d events wouldn't fit into the fixed-length VITAGRAPH marker tables!\nBlame the Vitaport people!\n", MSGPARM(nevents));
            }
        }
        n_events=markertable_entry->idiotically_fixed_length;

        fwrite(markertable_entry->markertable_name, 1, VP_TABLEVAR_LENGTH, local_arg->outfile);
        length=n_events*sizeof(length);
#ifdef LITTLE_ENDIAN
        Intel_int32((uint32_t *)&length);
#endif
        fwrite(&length, sizeof(length), 1, local_arg->outfile);
        for (tagno=0; tagno<n_events; tagno++) {
            if (tagno<nevents) {
                struct trigger * const intrig=((struct trigger *)local_arg->triggers.buffer_start)+tagno;
                /* Trigger positions are given in ms units */
                trigpoint=(long)rint(intrig->position*1000.0/local_arg->sfreq);
                /* Make trigpoint uneven if code%2==1 */
                trigpoint=trigpoint-trigpoint%2+(intrig->code-1)%2;
            } else {
                trigpoint= -1;
            }
#ifdef LITTLE_ENDIAN
            Intel_int32((uint32_t *)&trigpoint);
#endif
            fwrite(&trigpoint, sizeof(trigpoint), 1, local_arg->outfile);
        }
        for (; tagno<n_events; tagno++) {
            trigpoint= -1;
#ifdef LITTLE_ENDIAN
            Intel_int32((uint32_t *)&trigpoint);
#endif
            fwrite(&trigpoint, sizeof(trigpoint), 1, local_arg->outfile);
        }
    }

    fclose(local_arg->outfile);

    /*{{{  Free memory*/
    free_pointer((void **)&local_arg->channelfilename);
    free_pointer((void **)&local_arg->channelmax);
    free_pointer((void **)&local_arg->channelmin);
    free_pointer((void **)&local_arg->channelheaders);
    free_pointer((void **)&local_arg->channelheadersII);

    if (local_arg->triggers.buffer_start!=NULL) {
        clear_triggers(&local_arg->triggers);
        growing_buf_free(&local_arg->triggers);
    }
    /*}}}  */

    tinfo->methods->init_done=FALSE;
}
Ejemplo n.º 18
0
int 
add_data_block(inode_t *inodep, int blocknum)
		/* add this blocknum to the direct or indirects of the inodep 
		Returns 0 on success, -1 on error */
{
	if (inodep->i_blocks < 106){
		inodep->i_direct[inodep->i_blocks] = blocknum;
		inodep->i_blocks++;
		return 0;
	} else if (inodep->i_blocks < 235) {
		int single = inodep->i_single;
		indirect_t single_indrect;
		if (inodep->i_blocks == 106){
			/* add single indirect first */
			single = get_free_blocknum();
			if (single < 0)
				return -1;
			inodep->i_blocks++;
			inodep->i_single = single;
			clear_indirect(&single_indrect);
			write_struct(single, &single_indrect);
		}
		/* add blocknum */
		read_struct(single, &single_indrect);
		single_indrect.index[(inodep->i_blocks - 107)%128] = blocknum;
		if (write_struct(single, &single_indrect) < 0)
			return -1;
		inodep->i_blocks++;
		return 0;
	} else {
		int double_block_i = inodep->i_double;
		int index_block_i;
		indirect_t double_indirect;
		indirect_t index_block;
		int double_block_off = (inodep->i_blocks-236) / 129;
		if (inodep->i_blocks == 235){
			/* add double indirect block */
			double_block_i = get_free_blocknum();
			if (double_block_i < 0)
				return -1;
			inodep->i_blocks++;
			inodep->i_double = double_block_i;
			clear_indirect(&double_indirect);
			index_block_i = get_free_blocknum();
			if (index_block_i< 0)
				return -1;
			inodep->i_blocks++;
			double_indirect.index[0] = index_block_i;
			clear_indirect(&index_block);
			inodep->i_blocks++;
			if (write_struct(double_block_i, &double_indirect) < 0)
				return -1;
			if (write_struct(index_block_i, &index_block) < 0)
				return -1;
		} 
		else if ((inodep->i_blocks-236)%129 == 0){
			index_block_i = get_free_blocknum();
			if (index_block_i < 0)
				return -1;
			read_struct(double_block_i, &double_indirect);
			double_indirect.index[double_block_off] = index_block_i;
			inodep->i_blocks++;
			clear_indirect(&index_block);
			if (write_struct(double_block_i, &double_indirect) < 0)
				return -1;
			if (write_struct(index_block_i, &index_block) < 0)
				return -1;
		} 
		int index_block_off = inodep->i_blocks - 238 - 129 * double_block_off;
		read_struct(double_block_i, &double_indirect);
		index_block_i = double_indirect.index[double_block_off];
		read_struct(index_block_i, &index_block);
		index_block.index[index_block_off] = blocknum;
		if (write_struct(index_block_i, &index_block) < 0)
			return -1;
		inodep->i_blocks++;
		return 0;
	}
}
Ejemplo n.º 19
0
int 
format_disk(int size) /* size: total number of blocks on disk */
{
	/* format disk following rules: 
		+ vcb
		+ inode table
			- root
			- others
		+ root dirent
		+ free blocks 

	 Returns 0 on success, or -1 on error */

	int min_required_blocks;
	int free_starter;
	int root_dirent_block;
	int valid_block;
	int insert_block;
	struct timespec *now;
	entry_t entry;
	dirent_t root_dirent;
	free_t free_b;
	inode_t inode;
	valid_t valid;

	min_required_blocks = 1 			/* vcb */
						+ I_TABLE_SIZE  /* inode table */
						+ 1 			/* valid table */
						+ 1 			/* root dirent */;
	if (size < min_required_blocks){
		err("size must be at least %d", min_required_blocks);
		return -1;
	}

	free_starter = min_required_blocks;
	valid_block = free_starter -2;
	vcb.vb_magic = MAGIC;
	vcb.vb_blocksize = BLOCKSIZE;
	vcb.vb_root = 1;
	vcb.vb_free = free_starter;
	vcb.vb_itable_size = I_TABLE_SIZE;
	vcb.vb_clean = true;
	vcb.vb_valid = valid_block;
	if (write_struct(0, &vcb) < 0)				/* vcb */
		return -1;
	vcb_initialized = true;

	insert_block  = free_starter - 1;
	root_dirent_block = insert_block;
	if (!(now = get_time()))
		return -1;
	inode.i_ino  = 1;
	inode.i_type = S_IFDIR;
	inode.i_size = 2;
	inode.i_uid  = getuid();
	inode.i_gid  = getgid();
	inode.i_mode = 0777;
	inode.i_blocks = 1;
	inode.i_atime = *now;
	inode.i_mtime = *now;
	inode.i_ctime = *now;
	inode.i_direct[0] = root_dirent_block;
	for (int i=1; i<106; i++){
		inode.i_direct[i] = -1;
	}
	inode.i_single = -1;
	inode.i_double = -1;
	root = inode;
	if (write_struct(1, &root) < 0)				/* root inode */
		return -1;
	root_initialized = true;

	inode.i_ino = 0;
	inode.i_direct[0] = -1;
	for (int i=2; i<I_TABLE_SIZE+1; i++){
		if ( write_struct(i, &inode) < 0 )		/* the rest of I-node table */
			return -1;
	}

	valid.v_entries[1] = V_USED;
	for (int i=2; i<I_TABLE_SIZE+1; i++){
		valid.v_entries[i] = V_UNUSED;
	}
	if (write_struct(valid_block, &valid) < 0)  /* valid table */
		return -1;

	clear_dirent(&root_dirent);
	entry.et_ino = 1;
	strcpy(entry.et_name, ".");			/* .  entry */
	root_dirent.d_entries[0] = entry;	
	strcpy(entry.et_name, "..");			/* .. entry */
	root_dirent.d_entries[1] = entry;
	if ( write_struct(root_dirent_block, &root_dirent) < 0 ) /* root dirent */
		return -1;

	for (int i=free_starter; i<size-1; i++){
		free_b.f_next = i + 1;
		if ( write_struct(i, &free_b) < 0 )
			return -1;
	}
	free_b.f_next = -1;
	if ( write_struct(size-1, &free_b) < 0 )		/* free blocks */
		return -1;

	return 0;
}
Ejemplo n.º 20
0
SaveResult write_bmp(const FilePath& filePath,
  const Bitmap& bmp,
  BitmapQuality quality)
{
  BinaryWriter out(filePath);
  if (!out.good()){
    return SaveResult::SaveFailed(error_open_file_write(filePath));
  }

  const auto bitsPerPixel = bits_per_pixel(quality);
  const IntSize size(bmp.GetSize());
  const int rowStride = bmp_row_stride(bitsPerPixel, size.w);

  switch(quality){
    // Note: No default, to ensure warning if unhandled enum value
  case BitmapQuality::COLOR_8BIT:
    {
      const auto pixelData = quantized(bmp, Dithering::ON);
      PaletteColors paletteColors(pixelData.palette.size());

      write_struct(out,
        create_bitmap_file_header(paletteColors, rowStride, size.h));
      write_struct(out,
        create_bitmap_info_header_8bipp(bmp.GetSize(),
          default_DPI(),
          PaletteColors(pixelData.palette.size()),
          false));
      write_8bipp_BI_RGB(out, pixelData);
      return SaveResult::SaveSuccessful();
    }

  case BitmapQuality::GRAY_8BIT:
    {
      MappedColors pixelData(desaturate_AlphaMap(bmp), grayscale_color_table());
      PaletteColors paletteColors(pixelData.palette.size());
      write_struct(out,
        create_bitmap_file_header(paletteColors, rowStride, size.h));
      write_struct(out,
        create_bitmap_info_header_8bipp(bmp.GetSize(),
          default_DPI(),
          PaletteColors(pixelData.palette.size()),
          false));
      write_8bipp_BI_RGB(out, pixelData);
      return SaveResult::SaveSuccessful();
    }

  case BitmapQuality::COLOR_24BIT:
    {
      write_struct(out,
        create_bitmap_file_header(PaletteColors(0), rowStride, size.h));
      write_struct(out,
        create_bitmap_info_header_24bipp(bmp.GetSize(),
          default_DPI(),
          false));
      write_24bipp_BI_RGB(out, bmp);
      return SaveResult::SaveSuccessful();
    }
  }

  assert(false);
  return SaveResult::SaveFailed(utf8_string("Internal error in save_bitmap"));
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
void testit0(void)
{
	char c;
	struct testbuf tb;
	int i;
	int fdin;
	int fdout;

	//start_direct();
	print_direct_status();
	//enable_direct_mode(60, 120);
	enable_direct_mode(DIRECT_WAIT_FOREVER, DIRECT_WAIT_FOREVER);
	print_direct_status();
	start_direct();
	exit(0);
	//char new_cmd[] = {'O', 0x06, 0x0d, 0x0a, 0x31, 0x30, 0x2e, 0x36, 0x2e, 0x30, 0x2e, 0x31, 0x33, 0x37};

	//printf("waiting...\n");
	//print_transfer_status();
	//exit(0);
	//int doagain = 1;
	//wlan_disable(0);
	//int to_test[] = {5, 8, 9, 11, 15, 16, 255, -1};
	int to_test[] = {0xFF, -1};

	zero_card_files();
	for (i = 0; i < 100; i++) {
		print_transfer_status();
	}
	exit(0);
	while (1) {
	//fprintf(stderr, "testing...\n");
	for (i = 0; i < 255; i++) {
		int cmd = to_test[i];
		if (cmd == -1)
			break;
		//zero_card_files();
		card_info_cmd(cmd);
		printf("UNKNOWN %3d result: ", cmd);
		int printed = dumpbuf(eyefi_buf, 256);
		if (!printed)
			printf("\n");
		print_transfer_status();
		print_connected_to();
	}
	}
	exit(0);
	scan_print_nets();
	printf("WLAN enabled: %d\n", wlan_enabled());
	//wlan_disable();
	printf("WLAN enabled: %d\n", wlan_enabled());
	for (i = 10; i <= 13; i++) {
		int printed;
		zero_card_files();
		card_info_cmd(i);
		printf("UNKNOWN %d result:\n", i);
		printed = dumpbuf(eyefi_buf, 64);
		printf("WLAN enabled: %d\n", wlan_enabled());
	}
	i = 0xff;
	card_info_cmd(i);
	printf("UNKNOWN %d result:", i);
	dumpbuf(eyefi_buf, 64);
	exit(3);

	card_info_cmd(3);
	printf("o3 result:\n");
	dumpbuf(eyefi_buf, 64);

	memset(&zbuf[0], 0, EYEFI_BUF_SIZE);
	zbuf[0] = 'o';
	zbuf[1] = 2;

	write_to(REQM, &zbuf[0], 16384);
	printf("o2 written\n");
	printf("seq: %x\n", (int)eyefi_seq.seq);
	inc_seq();

	for (i=0; i < 4; i++) {
		read_from(RSPC);
		printf("RSPC %d:\n", i);
		dumpbuf(eyefi_buf, 64);
		usleep(20000);
	}

	printf("RSPM1:\n");
	read_from(RSPM);
	dumpbuf(eyefi_buf, 64);

	memset(&zbuf[0], 0, EYEFI_BUF_SIZE);
	write_to(RSPM, zbuf, EYEFI_BUF_SIZE);
	write_to(REQM, zbuf, EYEFI_BUF_SIZE);

	fdin = open("/home/dave/projects/eyefi/EYEFIFWU.BIN.2.0001", O_RDONLY);
	perror("fdin");
	fdout = open("/media/EYE-FI/EYEFIFWU.BIN", O_WRONLY|O_CREAT);
	perror("fdout");
	if (fdin <= 0 || fdout <= 0)
		exit(1);
	fd_flush(fdin);
	i = read(fdin, &fwbuf[0], 524288);
	perror("read");
	if (i != 524288)
		exit(2);
	i = write(fdout, &fwbuf[0], 524288);
	fd_flush(fdout);
	perror("write");
	if (i != 524288)
		exit(3);

	printf("RSPM2:\n");
	read_from(RSPM);
	dumpbuf(eyefi_buf, 64);

	reboot_card();
	printf("after reboot:\n");
	dumpbuf(eyefi_buf, 64);

	printf("cic3:\n");
	card_info_cmd(3);
	dumpbuf(eyefi_buf, 64);

	printf("cic2:\n");
	card_info_cmd(2);
	dumpbuf(eyefi_buf, 64);

	memset(&zbuf[0], 0, EYEFI_BUF_SIZE);
	write_to(RSPM, zbuf, EYEFI_BUF_SIZE);
	write_to(REQM, zbuf, EYEFI_BUF_SIZE);

	printf("cic2v2:\n");
	card_info_cmd(2);
	dumpbuf(eyefi_buf, 64);

	exit(0);
	strcpy(tb.name, "www.sr71.net/");
	tb.l1 = strlen(tb.name);
	for (i = 0; i < 10; i++) {
		tb.cmd = 'O';
		tb.l1 = i;
		write_struct(RSPM, &z);
		write_struct(REQM, &tb);
		wait_for_response();
		printf("buffer after O %d:\n", i);
		dumpbuf(eyefi_buf, 64);
		printf("----------------\n");
		write_struct(REQM, &tb);
		card_info_cmd(i);
		printf("card info(%d):\n", i);
		dumpbuf(eyefi_buf, 64);
		printf("-----------\n");
	}
	return;

	strcpy(tb.name, "/public/eyefi/servname");
	strcpy(tb.name, "/config/networks.xml");
	//tb.len = strlen(tb.name);
	tb.l1 = 0;
	for (c = 'O'; c <= 'O'; c++) {
		tb.cmd = c;
		write_struct(REQM, &tb);
		wait_for_response();
		printf("dumping buffer:\n");
		dumpbuf(eyefi_buf, 64);
		printf("buffer dump done\n");
	}
}