示例#1
0
文件: IoBlowfish.c 项目: anthem/io
IoObject *IoBlowfish_setIsEncrypting(IoBlowfish *self, IoObject *locals, IoMessage *m)
{
	/*doc Blowfish setIsEncrypting(aBool)
	If aBool is true, encrypting mode is on, otherwise, decrypting mode is on.
	*/

	IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 0);
	IOASSERT(ISTRUE(v) || ISFALSE(v), "requires boolean argument");
	DATA(self)->isEncrypting = ISTRUE(v);
	return self;
}
示例#2
0
int rdbi_col_getW(
	rdbi_context_def *context,
    wchar_t *column_name,
    wchar_t *type,
    int  *length,
    int  *scale,
    int  *nullable,
    int  *is_autoincrement,
    int  *position,
    int  *eof)
{
    int   status;

    debug_on("rdbi_col_getW");

    status = (*(context->dispatch.col_getW))(context->drvr, column_name, type, length, scale, nullable, is_autoincrement,
                            position, eof);

    context->rdbi_last_status = status;

    debug_area()
    {
        if (*eof)
        {
            debug0("eof=TRUE");
        }
        else
        {
            debug6("column='%ls', type='%ls', length=%d, scale=%d, nullable=%s, position=%d",
                ISNULL(column_name), ISNULL(type), *length, *scale, ISTRUE(*nullable), *position);
        }
    }
    debug_return(NULL, status);
}
示例#3
0
文件: IoFile.c 项目: achoy/io
IO_METHOD(IoFile, remove)
{
	/*doc File remove
	Removes the file specified by the receiver's path.
	Raises an error if the file exists but is not removed. Returns self.
	*/

	int error = 0;

#if defined(__SYMBIAN32__)
	error = -1;
#elif defined(_MSC_VER) || defined(__MINGW32__)
	if(IoFile_justExists(self))
	{
		if(ISTRUE(IoFile_isDirectory(self, locals, m)))
		{
			error = rmdir(UTF8CSTRING(DATA(self)->path));
		}
		else
		{
			error = unlink(UTF8CSTRING(DATA(self)->path));
		}
	}
#else
	error = remove(UTF8CSTRING(DATA(self)->path));
#endif

	if (error && IoFile_justExists(self))
	{
		IoState_error_(IOSTATE, m, "error removing file '%s'", UTF8CSTRING(DATA(self)->path));
	}
	return self;
}
示例#4
0
文件: IoCurses.c 项目: Akiyah/io
IoObject *IoCurses_scrollok(IoCurses *self, IoObject *locals, IoMessage *m)
{
	/*doc Curses scrollok(aBoolean) 
    Enables / Disables automatic scrolling. Return self.
    */
    int b = ISTRUE(IoMessage_locals_valueArgAt_(m, locals, 0));
    scrollok(stdscr, b); // always returns OK
    return self;
}
示例#5
0
IoObject* IoMySQL_connect(IoObject* self, IoObject* locals, IoMessage* m) {
    IoObject *host = NULL, *user = NULL, *password = NULL, *database = NULL, *port = NULL, *socket = NULL, *ssl = NULL;

    /*doc MySQL connect(host, user, password, database, port, unixSocket, useSSL)
    Connect to a MySQL database.
    */

    switch(IoMessage_argCount(m)) {
    case 7:
        ssl = IoMessage_locals_quickValueArgAt_(m, locals, 6);
    case 6:
        socket = IoMessage_locals_quickValueArgAt_(m, locals, 5);
    case 5:
        port = IoMessage_locals_quickValueArgAt_(m, locals, 4);
    case 4:
        database = IoMessage_locals_quickValueArgAt_(m, locals, 3);
    case 3:
        password = IoMessage_locals_quickValueArgAt_(m, locals, 2);
    case 2:
        user = IoMessage_locals_quickValueArgAt_(m, locals, 1);
    case 1:
        host = IoMessage_locals_quickValueArgAt_(m, locals, 0);
    }

    if(DATA(self)->connected)
    {
        mysql_close(&DATA(self)->connection);
        DATA(self)->connected = 0;
    }

    if(mysql_real_connect(
                &DATA(self)->connection,
                host && ISSEQ(host) ? IoSeq_asCString(host) : NULL,
                user && ISSEQ(user) ? IoSeq_asCString(user) : NULL,
                password && ISSEQ(password) ? IoSeq_asCString(password) : NULL,
                database && ISSEQ(database) ? IoSeq_asCString(database) : NULL,
                port && ISNUMBER(port) ? (unsigned) IoNumber_asInt(port) : 0,
                socket && ISSEQ(socket) ? IoSeq_asCString(socket) : NULL,
                ssl && ISFALSE(ssl) ? 0 : CLIENT_SSL
            )) {
        DATA(self)->connected = 1;

        IoObject_setSlot_to_(self, IOSYMBOL("host"), host ? host : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("user"), user ? user : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("password"), password ? password : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("database"), database ? database : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("port"), port ? port : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("socket"), socket ? socket : IONIL(self));
        IoObject_setSlot_to_(self, IOSYMBOL("usingSSL"), ssl ? IOBOOL(self, ISTRUE(ssl)) : IOFALSE(self));
    }
    else
        IoState_error_(IOSTATE, m, "connection error(%d): %s", mysql_errno(&DATA(self)->connection), mysql_error(&DATA(self)->connection));

    return self;
}
示例#6
0
IoObject *IoCollector_setDebug(IoCollector *self, IoObject *locals, IoMessage *m)
{
	/*doc Collector setDebug(aBool)
	Turns on/off printing of collector debugging messages. Returns self.
	*/
	
	IoObject *aBool = IoMessage_locals_valueArgAt_(m, locals, 0);

	Collector_setDebug_(IOSTATE->collector, ISTRUE(aBool));
	return self;
}
示例#7
0
void
op_not(void)
{
    Var		ret, arg;

    arg = pop();
    ret.type = NUM;
    ret.v.num = !ISTRUE(arg);
    var_free(arg);
    push(ret);
}
示例#8
0
void
op_elseif(void)
{
    Var		cond;

    cond = pop();
    if (ISTRUE(cond)) {
	frame.pc++;
    } else {
	frame.pc = frame.m->code[frame.pc];
    }
    var_free(cond);
}
示例#9
0
void
op_while(void)
{
    Var		cond;

    cond = pop();
    if (!ISTRUE(cond)) {
	(void) pop();			/* take pc off stack */
	frame.pc = frame.m->code[frame.pc];
    } else {
	frame.pc++;		/* go to first instruction in loop */
    }
    var_free(cond);
}
示例#10
0
void
op_dowhile(void)
{
    Var		cond;

    cond = pop();
    if (ISTRUE(cond)) {				/* keep looping */
	frame.pc = frame.m->code[frame.pc];
    } else {					/* loop is finished */
	(void) pop();				/* remove sentinel */
	frame.pc += 2;				/* skip to end */
    }
    var_free(cond);
}
示例#11
0
文件: IoCoroutine.c 项目: jdp/io
IO_METHOD(IoCoroutine, setMessageDebugging)
{
	/*doc Coroutine setMessageDebugging(aBoolean)
	Turns on message level debugging for this coro. When on, this
coro will send a vmWillSendMessage message to the Debugger object before
each message send and pause itself. See the Debugger object documentation
for more information. 
*/
	IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 0);

	DATA(self)->debuggingOn = ISTRUE(v);
	IoState_updateDebuggingMode(IOSTATE);

	return self;
}
示例#12
0
void
op_or(void)
{
    Var		left;
    Var		ret;

    left = pop();
    if (!ISTRUE(left)) {	/* LHS false, evaluate RHS */
	frame.pc++;		/* skip over breakout goto */
    } else {			/* LHS true, skip to end */
	ret.type = NUM;
	ret.v.num = 1;
	push(ret);
	frame.pc = frame.m->code[frame.pc];	/* skip to breakout */
    }
    var_free(left);
}
示例#13
0
void
op_if(void)
{
    Var		cond;

    cond = pop();
    if(ISTRUE(cond)) {
	pushn(frame.m->code[frame.pc + 1]);	/* push end address */
	frame.pc += 2;				/* skip to code */
    } else if (frame.m->code[frame.pc]) {	/* if there's an elseif */
	pushn(frame.m->code[frame.pc + 1]);	/* push end address */
	frame.pc = frame.m->code[frame.pc];	/* go to elseif code */
    } else {
	frame.pc = frame.m->code[frame.pc + 1];	/* go to end address */
    }
    var_free(cond);
}
示例#14
0
文件: IoLoudmouth.c 项目: ADTSH/io
//doc Loudmouth connect Connects to the server. Returns <code>self</code>.
IoObject *IoLoudmouth_connect(IoLoudmouth *self, IoObject *locals, IoMessage *m) {
//  Q: Should we io_free() these?
  IoSeq* username   = IoObject_getSlot_(self, IOSYMBOL("username"));
  IoSeq* password   = IoObject_getSlot_(self, IOSYMBOL("password"));
  IoSeq* resource   = IoObject_getSlot_(self, IOSYMBOL("resource"));
  IoSeq* host       = IoObject_getSlot_(self, IOSYMBOL("host"));
  IoNumber* port    = IoObject_getSlot_(self, IOSYMBOL("port"));
  IoObject* use_ssl = IoObject_getSlot_(self, IOSYMBOL("useSsl"));

  IOASSERT(ISSEQ(username), "Loudmouth: username should be a Sequence");
  IOASSERT(ISSEQ(password), "Loudmouth: password should be a Sequence");
  IOASSERT(ISSEQ(resource), "Loudmouth: resource should be a Sequence");
  IOASSERT(ISSEQ(host),     "Loudmouth: host should be a Sequence");
  IOASSERT(ISNUMBER(port),  "Loudmouth: port should be a Number");

  if(LMCONN(self) == NULL) {
    LmConnection *connection = lm_connection_new_with_context(CSTRING(host), main_context);
    IoObject_setDataPointer_(self, connection);

    lm_connection_set_jid(connection, CSTRING(IoObject_getSlot_(self, IOSYMBOL("jid"))));
    lm_connection_set_port(connection, CNUMBER(port));

    if(ISTRUE(use_ssl) && lm_ssl_is_supported()) {
      LmSSL *ssl = lm_ssl_new(NULL, onSslError, NULL, NULL);
      lm_connection_set_ssl(connection, ssl);
      lm_ssl_unref(ssl);
    }

    LmMessageHandler* handler = lm_message_handler_new(onXmppMessage, self, NULL);
    lm_connection_register_message_handler(
      connection, handler,
      LM_MESSAGE_TYPE_MESSAGE, LM_HANDLER_PRIORITY_NORMAL
    );
    lm_message_handler_unref(handler);

    lm_connection_set_disconnect_function(connection, onXmppDisconnect, NULL, NULL);
  }

  lm_connection_open(LMCONN(self), onXmppConnect, self, NULL, NULL);
  return self;
}
BOOL CDisplayAdapterHelper::AdjustDllforProcess(HANDLE hProcess, LPSTR lpDllPath)
{
	BOOL bIs32Bit = FALSE;

//#ifdef _WIN64
//	BOOL myselfBitWide = TRUE;
//#else
//	BOOL mySelfBitWide = FALSE; 
//#endif
//	BOOL bSelfIsWow64 = FALSE;
//	IsWow64Process(GetCurrentProcess(), &bSelfIsWow64);
	IsWow64Process(hProcess, &bIs32Bit);

	if (!bIs32Bit)
	{
		CHAR tempStrBuf[MAX_PATH] = { 0 };

		if (ISTRUE(AdjustDllfor64bit(tempStrBuf, MAX_PATH, lpDllPath)))
		{
			memcpy(lpDllPath, tempStrBuf, strlen(tempStrBuf) + 1);
		}
	}
	return TRUE;
}
示例#16
0
static	void	parseconfigline (char *buf, unsigned int line, zconf_t *z)
{
	char		*end, *val, *p;
	char		*tag;
	unsigned int	len, found;
	zconf_para_t	*c;

	assert (buf[0] != '\0');

	p = &buf[strlen(buf)-1];        /* Chop off white space at eol */
	while ( p >= buf && isspace (*p) )
		*p-- = '\0';

	for (p = buf; isspace (*p); p++ )	/* Ignore leading white space */
		;
	
	/* Ignore comments and emtpy lines */
	if ( *p == '\0' || ISCOMMENT (p) )
		return;

	tag = p;
	/* Get the end of the first argument */
	end = &buf[strlen(buf)-1];
	while ( p < end && !ISDELIM (*p) )      /* Skip until delim */
		p++;
	*p++ = '\0';    /* Terminate this argument */
	dbg_val1 ("Parsing \"%s\"\n", tag);


	while ( p < end && ISDELIM (*p) )	/* Skip delim chars */
		p++;

	val = p;	/* Start of the value */
	dbg_val1 ("\tgot value \"%s\"\n", val);

	/* If starting with quote, skip until next quote */
	if ( *p == '"' || *p == '\'' )
	{
		p++;    /* Find next quote */
		while ( p <= end && *p && *p != *val )
			p++;
		*p = '\0';
		val++;          /* Skip the first quote */
	}
	else    /* Otherwise check if there is any comment char at the end */
	{
		while ( p < end && *p && !ISCOMMENT(p) )
			p++;
		if ( ISCOMMENT (p) )
		{
			do      /* Chop off white space before comment */
				*p-- = '\0';
			while ( p >= val && isspace (*p) );
		}
	}

	/* Otherwise it is already terminated above */

	found = 0;
	c = confpara;
	while ( !found && c->type != CONF_END )
	{
		len = strlen (c->label);
		if ( strcasecmp (tag, c->label) == 0 )
		{
			char	**str;
			char	quantity;
			long	lval;

			found = 1;
			switch ( c->type )
			{
			case CONF_LEVEL:
			case CONF_FACILITY:
			case CONF_STRING:
				str = (char **)c->var;
				*str = strdup (val);
				str_untaint (*str);	/* remove "bad" characters */
				break;
			case CONF_INT:
				sscanf (val, "%d", (int *)c->var);
				break;
			case CONF_TIMEINT:
				quantity = 'd';
				sscanf (val, "%ld%c", &lval, &quantity);
				if  ( quantity == 'm' )
					lval *= MINSEC;
				else if  ( quantity == 'h' )
					lval *= HOURSEC;
				else if  ( quantity == 'd' )
					lval *= DAYSEC;
				else if  ( quantity == 'w' )
					lval *= WEEKSEC;
				else if  ( quantity == 'y' )
					lval *= YEARSEC;
				(*(long *)c->var) = lval;
				break;
			case CONF_ALGO:
				if ( strcasecmp (val, "rsa") == 0 || strcasecmp (val, "rsamd5") == 0 )
					*((int *)c->var) = DK_ALGO_RSA;
				else if ( strcasecmp (val, "dsa") == 0 )
					*((int *)c->var) = DK_ALGO_DSA;
				else if ( strcasecmp (val, "rsasha1") == 0 )
					*((int *)c->var) = DK_ALGO_RSASHA1;
				else if ( strcasecmp (val, "nsec3dsa") == 0 ||
				          strcasecmp (val, "n3dsa") == 0 )
					*((int *)c->var) = DK_ALGO_NSEC3DSA;
				else if ( strcasecmp (val, "nsec3rsasha1") == 0 ||
					  strcasecmp (val, "n3rsasha1") == 0 )
					*((int *)c->var) = DK_ALGO_NSEC3RSASHA1;
				else
					error ("Illegal algorithm \"%s\" "
						"in line %d.\n" , val, line);
				break;
			case CONF_SERIAL:
				if ( strcasecmp (val, "unixtime") == 0 )
					*((serial_form_t *)c->var) = Unixtime;
				else if ( strcasecmp (val, "incremental") == 0 )
					*((serial_form_t *)c->var) = Incremental;
				else
					error ("Illegal serial no format \"%s\" "
						"in line %d.\n" , val, line);
				break;
			case CONF_BOOL:
				*((int *)c->var) = ISTRUE (val);
				break;
			default:
				fatal ("Illegal configuration type in line %d.\n", line);
			}
		}
		c++;
	}
	if ( !found )
		error ("Unknown configuration statement: %s \"%s\"\n", tag, val);
	return;
}
示例#17
0
IoObject* IoMySQL_query(IoObject* self, IoObject* locals, IoMessage* m)
{
    /*doc MySQL query(aQueryString)
    Perform a SQL query and return a list of results.
    <pre>
    db query("SELECT * FROM accounts") foreach(println)
    </pre>
    */

    IoObject * queryString = 0x0;
    bool useMap;

    MYSQL* conn = &DATA(self)->connection;
    MYSQL_RES* result;
    MYSQL_ROW row;
    MYSQL_FIELD* column;
    char** columnNames;
    unsigned c, colLength;
    unsigned long* colLengths;
    IoObject *list, *rowObject; //, *tmpObject;

    if(IoMessage_argCount(m) < 1 || !ISSEQ(queryString = IoMessage_locals_quickValueArgAt_(m, locals, 0)))
        IoState_error_(IOSTATE, m, "argument 0 to method 'query' must be a Sequence");

    useMap = IoMessage_argCount(m) > 1 && ISTRUE(IoMessage_locals_quickValueArgAt_(m, locals, 1));

    if(!DATA(self)->connected) //printf("not connected?\n");
        IoState_error_(IOSTATE, m, "not connected yet");

    if(mysql_real_query(conn, CSTRING(queryString), IOSEQ_LENGTH(queryString)))
        IoState_error_(IOSTATE, m, "query error(%d): %s", mysql_errno(&DATA(self)->connection), mysql_error(&DATA(self)->connection));

    if((result = mysql_store_result(conn)) && (colLength = mysql_num_fields(result))) {
        list = IoList_new(IOSTATE);

        if(useMap) {
            columnNames = (char**) malloc(colLength * sizeof(char*));
            for(c = 0; c < colLength && (column = mysql_fetch_field(result)); ++c)
                columnNames[c] = column->name;

            while((row = mysql_fetch_row(result)))
            {
                colLengths = mysql_fetch_lengths(result);
                rowObject = IoMap_new(IOSTATE);

                for(c = 0; c < colLength; ++c)
                    IoMap_rawAtPut(rowObject, IOSYMBOL(columnNames[c]), IOSEQ((unsigned char *)row[c], (size_t)colLengths[c]));

                IoList_rawAppend_(list, rowObject);
            }

            free(columnNames);
        }
        else
        {
            while((row = mysql_fetch_row(result))) {
                colLengths = mysql_fetch_lengths(result);
                rowObject = IoList_new(IOSTATE);

                for(c = 0; c < colLength; ++c)
                    IoList_rawAppend_(rowObject, IOSEQ((unsigned char *)row[c], (size_t)colLengths[c]));

                IoList_rawAppend_(list, rowObject);
            }
        }

        mysql_free_result(result);
        return list;
    }
    else
        return IONUMBER(mysql_affected_rows(conn));
}
示例#18
0
int main(int argc, char *argv[]) {
    int n, i, c, count = 0, sample = 0, chan = 0, status = 0, verbose = 0, labelSize;
    unsigned char buf[OPENBCI_BUFLEN], byte;
    char *labelString;
    SerialPort SP;
    host_t host;
    struct timespec tic, toc;

    /* these represent the general acquisition system properties */
    int nchans         = OPENBCI_NCHANS;
    float fsample      = OPENBCI_FSAMPLE;

    /* these are used in the communication with the FT buffer and represent statefull information */
    int ftSocket           = -1;
    ft_buffer_server_t *ftServer;
    message_t     *request  = NULL;
    message_t     *response = NULL;
    header_t      *header   = NULL;
    data_t        *data     = NULL;
    ft_chunkdef_t *label    = NULL;

    /* this contains the configuration details */
    configuration config;

    /* configure the default settings */
    config.blocksize     = 10;
    config.port          = 1972;
    config.hostname      = strdup("-");
    config.serial        = strdup("/dev/tty.usbserial-DN0094FY");
    config.reset         = strdup("on");
    config.datalog       = strdup("off");
    config.testsignal    = strdup("off");
    config.timestamp     = strdup("on");
    config.timeref       = strdup("start");

    config.enable_chan1  = strdup("on");
    config.enable_chan2  = strdup("on");
    config.enable_chan3  = strdup("on");
    config.enable_chan4  = strdup("on");
    config.enable_chan5  = strdup("on");
    config.enable_chan6  = strdup("on");
    config.enable_chan7  = strdup("on");
    config.enable_chan8  = strdup("on");
    config.enable_chan9  = strdup("on");
    config.enable_chan10 = strdup("on");
    config.enable_chan11 = strdup("on");

    config.label_chan1  = strdup("ADC1");
    config.label_chan2  = strdup("ADC2");
    config.label_chan3  = strdup("ADC3");
    config.label_chan4  = strdup("ADC4");
    config.label_chan5  = strdup("ADC5");
    config.label_chan6  = strdup("ADC6");
    config.label_chan7  = strdup("ADC7");
    config.label_chan8  = strdup("ADC8");
    config.label_chan9  = strdup("AccelerationX");
    config.label_chan10 = strdup("AccelerationY");
    config.label_chan11 = strdup("AccelerationZ");
    config.label_chan12 = strdup("TimeStamp");

    config.setting_chan1  = strdup("x1060110X");
    config.setting_chan2  = strdup("x2060110X");
    config.setting_chan3  = strdup("x3060110X");
    config.setting_chan4  = strdup("x4060110X");
    config.setting_chan5  = strdup("x5060110X");
    config.setting_chan6  = strdup("x6060110X");
    config.setting_chan7  = strdup("x7060110X");
    config.setting_chan8  = strdup("x8060110X");

    config.impedance_chan1  = strdup("z100Z");
    config.impedance_chan2  = strdup("z200Z");
    config.impedance_chan3  = strdup("z300Z");
    config.impedance_chan4  = strdup("z400Z");
    config.impedance_chan5  = strdup("z500Z");
    config.impedance_chan6  = strdup("z600Z");
    config.impedance_chan7  = strdup("z700Z");
    config.impedance_chan8  = strdup("z800Z");

    if (argc<2) {
        printf(usage);
        exit(0);
    }

    if (argc==2) {
        if (strncmp(argv[1], "/dev", 4)==0 || strncasecmp(argv[1], "COM", 3)==0)
            /* the second argument is the serial port */
            config.serial = strdup(argv[1]);
        else {
            /* the second argument is the configuration file */
            fprintf(stderr, "openbci2ft: loading configuration from '%s'\n", argv[1]);
            if (ini_parse(argv[1], iniHandler, &config) < 0) {
                fprintf(stderr, "Can't load '%s'\n", argv[1]);
                return 1;
            }
        }
    }

    if (argc>2)
        strcpy(host.name, argv[2]);
    else {
        strcpy(host.name, config.hostname);
    }

    if (argc>3)
        host.port = atoi(argv[3]);
    else {
        host.port = config.port;
    }

#define ISTRUE(s) strcasecmp(s, "on")==0
    nchans = 0;
    if (ISTRUE(config.enable_chan1))
        nchans++;
    if (ISTRUE(config.enable_chan2))
        nchans++;
    if (ISTRUE(config.enable_chan3))
        nchans++;
    if (ISTRUE(config.enable_chan4))
        nchans++;
    if (ISTRUE(config.enable_chan5))
        nchans++;
    if (ISTRUE(config.enable_chan6))
        nchans++;
    if (ISTRUE(config.enable_chan7))
        nchans++;
    if (ISTRUE(config.enable_chan8))
        nchans++;
    if (ISTRUE(config.enable_chan9))
        nchans++;
    if (ISTRUE(config.enable_chan10))
        nchans++;
    if (ISTRUE(config.enable_chan11))
        nchans++;
    if (ISTRUE(config.timestamp))
        nchans++;

    fprintf(stderr, "openbci2ft: serial       =  %s\n", config.serial);
    fprintf(stderr, "openbci2ft: hostname     =  %s\n", host.name);
    fprintf(stderr, "openbci2ft: port         =  %d\n", host.port);
    fprintf(stderr, "openbci2ft: blocksize    =  %d\n", config.blocksize);
    fprintf(stderr, "openbci2ft: reset        =  %s\n", config.reset);
    fprintf(stderr, "openbci2ft: datalog      =  %s\n", config.datalog);
    fprintf(stderr, "openbci2ft: timestamp    =  %s\n", config.timestamp);
    fprintf(stderr, "openbci2ft: testsignal   =  %s\n", config.testsignal);

    /* Spawn tcpserver or connect to remote buffer */
    if (strcmp(host.name, "-") == 0) {
        ftServer = ft_start_buffer_server(host.port, NULL, NULL, NULL);
        if (ftServer==NULL) {
            fprintf(stderr, "openbci2ft: could not start up a local buffer serving at port %i\n", host.port);
            return 1;
        }
        ftSocket = 0;
        printf("openbci2ft: streaming to local buffer on port %i\n", host.port);
    }
    else {
        ftSocket = open_connection(host.name, host.port);

        if (ftSocket < 0) {
            fprintf(stderr, "openbci2ft: could not connect to remote buffer at %s:%i\n", host.name, host.port);
            return 1;
        }
        printf("openbci2ft: streaming to remote buffer at %s:%i\n", host.name, host.port);
    }

    /* allocate the elements that will be used in the communication to the FT buffer */
    request      = malloc(sizeof(message_t));
    request->def = malloc(sizeof(messagedef_t));
    request->buf = NULL;
    request->def->version = VERSION;
    request->def->bufsize = 0;

    header      = malloc(sizeof(header_t));
    header->def = malloc(sizeof(headerdef_t));
    header->buf = NULL;

    data      = malloc(sizeof(data_t));
    data->def = malloc(sizeof(datadef_t));
    data->buf = NULL;

    /* define the header */
    header->def->nchans    = nchans;
    header->def->fsample   = fsample;
    header->def->nsamples  = 0;
    header->def->nevents   = 0;
    header->def->data_type = DATATYPE_FLOAT32;
    header->def->bufsize   = 0;

    /* FIXME add the channel names */
    labelSize = 0; /* count the number of bytes required */
    if (ISTRUE (config.enable_chan1))
        labelSize += strlen (config.label_chan1) + 1;
    if (ISTRUE (config.enable_chan2))
        labelSize += strlen (config.label_chan2) + 1;
    if (ISTRUE (config.enable_chan3))
        labelSize += strlen (config.label_chan3) + 1;
    if (ISTRUE (config.enable_chan4))
        labelSize += strlen (config.label_chan4) + 1;
    if (ISTRUE (config.enable_chan5))
        labelSize += strlen (config.label_chan5) + 1;
    if (ISTRUE (config.enable_chan6))
        labelSize += strlen (config.label_chan6) + 1;
    if (ISTRUE (config.enable_chan7))
        labelSize += strlen (config.label_chan7) + 1;
    if (ISTRUE (config.enable_chan8))
        labelSize += strlen (config.label_chan8) + 1;
    if (ISTRUE (config.enable_chan9))
        labelSize += strlen (config.label_chan9) + 1;
    if (ISTRUE (config.enable_chan10))
        labelSize += strlen (config.label_chan10) + 1;
    if (ISTRUE (config.enable_chan11))
        labelSize += strlen (config.label_chan11) + 1;
    if (ISTRUE (config.timestamp))
        labelSize += strlen (config.label_chan12) + 1;

    if (verbose > 0)
        fprintf (stderr, "openbci2ft: labelSize = %d\n", labelSize);

    /* go over all channels for a 2nd time, now copying the strings to the destination */
    labelString = (char *) malloc (labelSize * sizeof(char));
    labelSize   = 0; 
    if (ISTRUE (config.enable_chan1)) {
        strcpy (labelString+labelSize, config.label_chan1);
        labelSize += strlen (config.label_chan1) + 1;
    }
    if (ISTRUE (config.enable_chan2)) {
        strcpy (labelString+labelSize, config.label_chan2);
        labelSize += strlen (config.label_chan2) + 1;
    }
    if (ISTRUE (config.enable_chan3)) {
        strcpy (labelString+labelSize, config.label_chan3);
        labelSize += strlen (config.label_chan3) + 1;
    }
    if (ISTRUE (config.enable_chan4)) {
        strcpy (labelString+labelSize, config.label_chan4);
        labelSize += strlen (config.label_chan4) + 1;
    }
    if (ISTRUE (config.enable_chan5)) {
        strcpy (labelString+labelSize, config.label_chan5);
        labelSize += strlen (config.label_chan5) + 1;
    }
    if (ISTRUE (config.enable_chan6)) {
        strcpy (labelString+labelSize, config.label_chan6);
        labelSize += strlen (config.label_chan6) + 1;
    }
    if (ISTRUE (config.enable_chan7)) {
        strcpy (labelString+labelSize, config.label_chan7);
        labelSize += strlen (config.label_chan7) + 1;
    }
    if (ISTRUE (config.enable_chan8)) {
        strcpy (labelString+labelSize, config.label_chan8);
        labelSize += strlen (config.label_chan8) + 1;
    }
    if (ISTRUE (config.enable_chan9)) {
        strcpy (labelString+labelSize, config.label_chan9);
        labelSize += strlen (config.label_chan9) + 1;
    }
    if (ISTRUE (config.enable_chan10)) {
        strcpy (labelString+labelSize, config.label_chan10);
        labelSize += strlen (config.label_chan10) + 1;
    }
    if (ISTRUE (config.enable_chan11)) {
        strcpy (labelString+labelSize, config.label_chan11);
        labelSize += strlen (config.label_chan11) + 1;
    }
    if (ISTRUE (config.timestamp)) {
        strcpy (labelString+labelSize, config.label_chan12);
        labelSize += strlen (config.label_chan12) + 1;
    }

    /* add the channel label chunk to the header */
    label = (ft_chunkdef_t *) malloc (sizeof (ft_chunkdef_t));
    label->type = FT_CHUNK_CHANNEL_NAMES;
    label->size = labelSize;
    header->def->bufsize = append (&header->buf, header->def->bufsize, label, sizeof (ft_chunkdef_t));
    header->def->bufsize = append (&header->buf, header->def->bufsize, labelString, labelSize);
    FREE (label);
    FREE (labelString);

    /* define the constant part of the data and allocate space for the variable part */
    data->def->nchans = nchans;
    data->def->nsamples = config.blocksize;
    data->def->data_type = DATATYPE_FLOAT32;
    data->def->bufsize = WORDSIZE_FLOAT32 * nchans * config.blocksize;
    data->buf = malloc (data->def->bufsize);

    /* initialization phase, send the header */
    request->def->command = PUT_HDR;
    request->def->bufsize = append (&request->buf, request->def->bufsize, header->def, sizeof (headerdef_t));
    request->def->bufsize = append (&request->buf, request->def->bufsize, header->buf, header->def->bufsize);

    /* this is not needed any more */
    cleanup_header (&header);

    status = clientrequest (ftSocket, request, &response);
    if (verbose > 0)
        fprintf (stderr, "openbci2ft: clientrequest returned %d\n", status);
    if (status)
    {
        fprintf (stderr, "openbci2ft: could not send request to buffer\n");
        exit (1);
    }

    if (status || response == NULL || response->def == NULL)
    {
        fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                __LINE__);
        exit (1);
    }

    cleanup_message (&request);

    if (response->def->command != PUT_OK)
    {
        fprintf (stderr, "openbci2ft: error in 'put header' request.\n");
        exit (1);
    }

    cleanup_message (&response);

    /* open the serial port */
    fprintf (stderr, "openbci2ft: opening serial port ...\n");
    if (!serialOpenByName (&SP, config.serial))
    {
        fprintf (stderr, "Could not open serial port %s\n", config.serial);
        return 1;
    }

    if (!serialSetParameters (&SP, 115200, 8, 0, 0, 0))
    {
        fprintf (stderr, "Could not modify serial port parameters\n");
        return 1;
    }

    fprintf (stderr, "openbci2ft: opening serial port ... ok\n");

    /* 8-bit board will always be initialized upon opening serial port, 32-bit board needs explicit initialization */

    fprintf (stderr, "openbci2ft: initializing ...\n");
    fprintf (stderr,
            "openbci2ft: press reset on the OpenBCI board if this takes too long\n");

    if (ISTRUE (config.reset))
        serialWrite (&SP, 1, "v");	/* soft reset, this will return $$$ */
    else
        serialWrite (&SP, 1, "D");	/* query default channel settings, this will also return $$$ */

    /* wait for '$$$' which indicates that the OpenBCI has been initialized */
    c = 0;
    while (c != 3)
    {
        usleep (1000);
        n = serialRead (&SP, 1, &byte);
        if (n == 1)
        {
            if (byte == '$')
                c++;
            else
                c = 0;
        }
    }				/* while waiting for '$$$' */

    if (strcasecmp (config.datalog, "14s") == 0)
        serialWrite (&SP, 1, "a");
    else if (strcasecmp (config.datalog, "5min") == 0)
        serialWrite (&SP, 1, "A");
    else if (strcasecmp (config.datalog, "15min") == 0)
        serialWrite (&SP, 1, "S");
    else if (strcasecmp (config.datalog, "30min") == 0)
        serialWrite (&SP, 1, "F");
    else if (strcasecmp (config.datalog, "1hr") == 0)
        serialWrite (&SP, 1, "G");
    else if (strcasecmp (config.datalog, "2hr") == 0)
        serialWrite (&SP, 1, "H");
    else if (strcasecmp (config.datalog, "4hr") == 0)
        serialWrite (&SP, 1, "J");
    else if (strcasecmp (config.datalog, "12hr") == 0)
        serialWrite (&SP, 1, "K");
    else if (strcasecmp (config.datalog, "24hr") == 0)
        serialWrite (&SP, 1, "L");
    else if (strcasecmp (config.datalog, "off") != 0)
    {
        fprintf (stderr, "Incorrect specification of datalog\n");
        return 1;
    }

    serialWriteSlow (&SP, strlen (config.setting_chan1), config.setting_chan1);
    serialWriteSlow (&SP, strlen (config.setting_chan2), config.setting_chan2);
    serialWriteSlow (&SP, strlen (config.setting_chan3), config.setting_chan3);
    serialWriteSlow (&SP, strlen (config.setting_chan4), config.setting_chan4);
    serialWriteSlow (&SP, strlen (config.setting_chan5), config.setting_chan5);
    serialWriteSlow (&SP, strlen (config.setting_chan6), config.setting_chan6);
    serialWriteSlow (&SP, strlen (config.setting_chan7), config.setting_chan7);
    serialWriteSlow (&SP, strlen (config.setting_chan8), config.setting_chan8);

    if (strcasecmp (config.testsignal, "gnd") == 0)
        serialWrite (&SP, 1, "0");
    else if (strcasecmp (config.testsignal, "dc") == 0)
        serialWrite (&SP, 1, "-");
    else if (strcasecmp (config.testsignal, "1xSlow") == 0)
        serialWrite (&SP, 1, "=");
    else if (strcasecmp (config.testsignal, "1xFast") == 0)
        serialWrite (&SP, 1, "p");
    else if (strcasecmp (config.testsignal, "2xSlow") == 0)
        serialWrite (&SP, 1, "[");
    else if (strcasecmp (config.testsignal, "2xFast") == 0)
        serialWrite (&SP, 1, "]");
    else if (strcasecmp (config.testsignal, "off") != 0)
    {
        fprintf (stderr, "Incorrect specification of testsignal\n");
        return 1;
    }

    fprintf (stderr, "openbci2ft: initializing ... ok\n");

    printf ("Starting to listen - press CTRL-C to quit\n");

    /* register CTRL-C handler */
    signal (SIGINT, abortHandler);

    /* start streaming data */
    serialWrite (&SP, 1, "b");

    /* determine the reference time for the timestamps */
    if (strcasecmp (config.timeref, "start") == 0)
    {
        /* since the start of the acquisition */
        get_monotonic_time (&tic, TIMESTAMP_REF_BOOT);
    }
    else if (strcasecmp (config.timeref, "boot") == 0)
    {
        /* since the start of the day */
        tic.tv_sec = 0;
        tic.tv_nsec = 0;
    }
    else if (strcasecmp (config.timeref, "epoch") == 0)
    {
        /* since the start of the epoch, i.e. 1-1-1970 */
        tic.tv_sec = 0;
        tic.tv_nsec = 0;
    }
    else
    {
        fprintf (stderr,
                "Incorrect specification of timeref, should be 'start', 'day' or 'epoch'\n");
        return 1;
    }

    while (keepRunning)
    {

        sample = 0;
        while (sample < config.blocksize)
        {
            /* wait for the first byte of the following packet */
            buf[0] = 0;
            while (buf[0] != 0xA0)
            {
                if (serialInputPending (&SP))
                    n = serialRead (&SP, 1, buf);
                else
                    usleep (1000);
            }			/* while */

            /*
             * Header
             *   Byte 1: 0xA0
             *   Byte 2: Sample Number
             *
             * EEG Data
             * Note: values are 24-bit signed, MSB first
             *   Bytes 3-5: Data value for EEG channel 1
             *   Bytes 6-8: Data value for EEG channel 2
             *   Bytes 9-11: Data value for EEG channel 3
             *   Bytes 12-14: Data value for EEG channel 4
             *   Bytes 15-17: Data value for EEG channel 5
             *   Bytes 18-20: Data value for EEG channel 6
             *   Bytes 21-23: Data value for EEG channel 6
             *   Bytes 24-26: Data value for EEG channel 8
             *
             * Accelerometer Data
             * Note: values are 16-bit signed, MSB first
             *   Bytes 27-28: Data value for accelerometer channel X
             *   Bytes 29-30: Data value for accelerometer channel Y
             *   Bytes 31-32: Data value for accelerometer channel Z
             *
             * Footer
             *   Byte 33: 0xC0
             */

            /* read the remaining 32 bytes of the packet */
            while (n < OPENBCI_BUFLEN)
                if (serialInputPending (&SP))
                    n += serialRead (&SP, (OPENBCI_BUFLEN - n), buf + n);
                else
                    usleep (1000);

            if (verbose > 1)
            {
                for (i = 0; i < OPENBCI_BUFLEN; i++)
                    printf ("%02x ", buf[i]);
                printf ("\n");
            }

            chan = 0;
            if (ISTRUE (config.enable_chan1))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[2] << 24 | buf[3] << 16 | buf[4] << 8) /
                    255;
            if (ISTRUE (config.enable_chan2))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[5] << 24 | buf[6] << 16 | buf[7] << 8) /
                    255;
            if (ISTRUE (config.enable_chan3))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[8] << 24 | buf[9] << 16 | buf[10] << 8) /
                    255;
            if (ISTRUE (config.enable_chan4))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[11] << 24 | buf[12] << 16 | buf[13] << 8) /
                    255;
            if (ISTRUE (config.enable_chan5))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[14] << 24 | buf[15] << 16 | buf[16] << 8) /
                    255;
            if (ISTRUE (config.enable_chan6))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[17] << 24 | buf[18] << 16 | buf[19] << 8) /
                    255;
            if (ISTRUE (config.enable_chan7))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[20] << 24 | buf[21] << 16 | buf[22] << 8) /
                    255;
            if (ISTRUE (config.enable_chan8))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[23] << 24 | buf[24] << 16 | buf[25] << 8) /
                    255;

            if (ISTRUE (config.enable_chan9))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[26] << 24 | buf[27] << 16) / 32767;
            if (ISTRUE (config.enable_chan10))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[28] << 24 | buf[29] << 16) / 32767;
            if (ISTRUE (config.enable_chan11))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[28] << 24 | buf[31] << 16) / 32767;

            if (ISTRUE (config.timestamp))
            {
                if (strcasecmp (config.timeref, "start") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_BOOT);
                else if (strcasecmp (config.timeref, "boot") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_BOOT);
                else if (strcasecmp (config.timeref, "epoch") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_EPOCH);
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    get_elapsed_time (&tic, &toc);
            }

            sample++;
        }				/* while c<config.blocksize */

        count += sample;
        printf ("openbci2ft: sample count = %i\n", count);

        /* create the request */
        request = malloc (sizeof (message_t));
        request->def = malloc (sizeof (messagedef_t));
        request->buf = NULL;
        request->def->version = VERSION;
        request->def->bufsize = 0;
        request->def->command = PUT_DAT;

        request->def->bufsize = append (&request->buf, request->def->bufsize, data->def, sizeof (datadef_t));
        request->def->bufsize = append (&request->buf, request->def->bufsize, data->buf, data->def->bufsize);

        status = clientrequest (ftSocket, request, &response);
        if (verbose > 0)
            fprintf (stderr, "openbci2ft: clientrequest returned %d\n", status);
        if (status)
        {
            fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                    __LINE__);
            exit (1);
        }

        if (status)
        {
            fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                    __LINE__);
            exit (1);
        }

        /* FIXME do someting with the response, i.e. check that it is OK */
        cleanup_message (&request);

        if (response == NULL || response->def == NULL
                || response->def->command != PUT_OK)
        {
            fprintf (stderr, "Error when writing samples.\n");
        }
        cleanup_message (&response);

    }				/* while keepRunning */

    /* stop streaming data */
    serialWrite (&SP, 1, "s");

    cleanup_data (&data);

    if (ftSocket > 0)
    {
        close_connection (ftSocket);
    }
    else
    {
        ft_stop_buffer_server (ftServer);
    }

    return 0;
}				/* main */
void ProcessRelationTags(TagList *tags,int64_t relation_id,int mode)
{
 transports_t routes=Transports_None;
 transports_t except=Transports_None;
 int relation_turn_restriction=0;
 TurnRestriction restriction=TurnRestrict_None;
 relation_t id;
 int i;

 /* Convert id */

 id=(relation_t)relation_id;
 logassert((int64_t)id==relation_id,"Relation ID too large (change relation_t to 64-bits?)"); /* check relation id can be stored in relation_t data type. */

 /* Delete */

 if(mode==MODE_DELETE || mode==MODE_MODIFY)
   {
    AppendRouteRelationList(relations,id,RELATION_DELETED,
                            relation_nodes,relation_nnodes,
                            relation_ways,relation_nways,
                            relation_relations,relation_nrelations);

    AppendTurnRelationList(relations,id,
                           relation_from,relation_to,relation_via,
                           restriction,RELATION_DELETED);
   }

 if(mode==MODE_DELETE)
    return;

 /* Sanity check */

 if(relation_nnodes==0 && relation_nways==0 && relation_nrelations==0)
   {
    logerror("Relation %"Prelation_t" has no nodes, ways or relations.\n",logerror_relation(id));
    return;
   }

 /* Parse the tags */

 for(i=0;i<tags->ntags;i++)
   {
    int recognised=0;
    char *k=tags->k[i];
    char *v=tags->v[i];

    switch(*k)
      {
      case 'b':
       if(!strcmp(k,"bicycleroute"))
         {
          if(ISTRUE(v))
             routes|=Transports_Bicycle;
          else if(!ISFALSE(v))
             logerror("Relation %"Prelation_t" has an unrecognised tag 'bicycleroute' = '%s' (after tagging rules); using 'no'.\n",logerror_relation(id),v);
          recognised=1; break;
         }

       break;

      case 'e':
       if(!strcmp(k,"except"))
         {
          for(i=1;i<Transport_Count;i++)
             if(strstr(v,TransportName(i)))
                except|=TRANSPORTS(i);

          if(except==Transports_None)
             logerror("Relation %"Prelation_t" has an unrecognised tag 'except' = '%s' (after tagging rules); ignoring it.\n",logerror_relation(id),v);

          recognised=1; break;
         }

       break;

      case 'f':
       if(!strcmp(k,"footroute"))
         {
          if(ISTRUE(v))
             routes|=Transports_Foot;
          else if(!ISFALSE(v))
             logerror("Relation %"Prelation_t" has an unrecognised tag 'footroute' = '%s' (after tagging rules); using 'no'.\n",logerror_relation(id),v);
          recognised=1; break;
         }

       break;

      case 'r':
       if(!strcmp(k,"restriction"))
         {
          if(!strcmp(v,"no_right_turn"   )) restriction=TurnRestrict_no_right_turn;
          if(!strcmp(v,"no_left_turn"    )) restriction=TurnRestrict_no_left_turn;
          if(!strcmp(v,"no_u_turn"       )) restriction=TurnRestrict_no_u_turn;
          if(!strcmp(v,"no_straight_on"  )) restriction=TurnRestrict_no_straight_on;
          if(!strcmp(v,"only_right_turn" )) restriction=TurnRestrict_only_right_turn;
          if(!strcmp(v,"only_left_turn"  )) restriction=TurnRestrict_only_left_turn;
          if(!strcmp(v,"only_straight_on")) restriction=TurnRestrict_only_straight_on;

          if(restriction==TurnRestrict_None)
             logerror("Relation %"Prelation_t" has an unrecognised tag 'restriction' = '%s' (after tagging rules); ignoring it.\n",logerror_relation(id),v);

          recognised=1; break;
         }

       break;

      case 't':
       if(!strcmp(k,"type"))
         {
          if(!strcmp(v,"restriction"))
             relation_turn_restriction=1;

          /* Don't log an error for relations of types that we don't handle - there are so many */
          recognised=1; break;
         }

       break;

      default:
       break;
      }

    if(!recognised)
       logerror("Relation %"Prelation_t" has an unrecognised tag '%s' = '%s' (after tagging rules); ignoring it.\n",logerror_relation(id),k,v);
   }

 /* Create the route relation (must store all relations that have ways or
    relations even if they are not routes because they might be referenced by
    other relations that are routes) */

 if((relation_nways || relation_nrelations) && !relation_turn_restriction)
    AppendRouteRelationList(relations,id,routes,
                            relation_nodes,relation_nnodes,
                            relation_ways,relation_nways,
                            relation_relations,relation_nrelations);

 /* Create the turn restriction relation. */

 if(relation_turn_restriction && restriction!=TurnRestrict_None)
   {
    if(relation_from==NO_WAY_ID)
      {
       /* Extra logerror information since relation isn't stored */
       if(relation_to!=NO_WAY_ID) logerror_way(relation_to);
       if(relation_via!=NO_NODE_ID) logerror_node(relation_via);
       logerror("Relation %"Prelation_t" is a turn restriction but has no 'from' way.\n",logerror_relation(id));
      }
    if(relation_to==NO_WAY_ID)
      {
       /* Extra logerror information since relation isn't stored */
       if(relation_via!=NO_NODE_ID) logerror_node(relation_via);
       if(relation_from!=NO_WAY_ID) logerror_way(relation_from);
       logerror("Relation %"Prelation_t" is a turn restriction but has no 'to' way.\n",logerror_relation(id));
      }
    if(relation_via==NO_NODE_ID)
      {
       /* Extra logerror information since relation isn't stored */
       if(relation_to!=NO_WAY_ID) logerror_way(relation_to);
       if(relation_from!=NO_WAY_ID) logerror_way(relation_from);
       logerror("Relation %"Prelation_t" is a turn restriction but has no 'via' node.\n",logerror_relation(id));
      }

    if(relation_from!=NO_WAY_ID && relation_to!=NO_WAY_ID && relation_via!=NO_NODE_ID)
       AppendTurnRelationList(relations,id,
                              relation_from,relation_to,relation_via,
                              restriction,except);
   }
}
void ProcessWayTags(TagList *tags,int64_t way_id,int mode)
{
 Way way={0};
 int oneway=0,area=0;
 int roundabout=0,lanes=0;
 char *name=NULL,*ref=NULL,*refname=NULL;
 way_t id;
 int i;

 /* Convert id */

 id=(way_t)way_id;
 logassert((int64_t)id==way_id,"Way ID too large (change way_t to 64-bits?)"); /* check way id can be stored in way_t data type. */

 /* Delete */

 if(mode==MODE_DELETE || mode==MODE_MODIFY)
   {
    way.type=WAY_DELETED;

    AppendWayList(ways,id,&way,way_nodes,way_nnodes,"");
   }

 if(mode==MODE_DELETE)
    return;

 /* Sanity check */

 if(way_nnodes==0)
   {
    logerror("Way %"Pway_t" has no nodes.\n",logerror_way(id));
    return;
   }

 if(way_nnodes==1)
   {
    logerror_node(way_nodes[0]); /* Extra logerror information since way isn't stored */
    logerror("Way %"Pway_t" has only one node.\n",logerror_way(id));
    return;
   }

 /* Parse the tags - just look for highway */

 for(i=0;i<tags->ntags;i++)
   {
    char *k=tags->k[i];
    char *v=tags->v[i];

    if(!strcmp(k,"highway"))
      {
       way.type=HighwayType(v);

       if(way.type==Highway_None)
          logerror("Way %"Pway_t" has an unrecognised highway type '%s' (after tagging rules); ignoring it.\n",logerror_way(id),v);

       break;
      }
   }

 /* Don't continue if this is not a highway (bypass error logging) */

 if(way.type==Highway_None)
    return;

 /* Parse the tags - look for the others */

 for(i=0;i<tags->ntags;i++)
   {
    int recognised=0;
    char *k=tags->k[i];
    char *v=tags->v[i];

    switch(*k)
      {
      case 'a':
       if(!strcmp(k,"area"))
         {
          if(ISTRUE(v))
             area=1;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'area' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'b':
       if(!strcmp(k,"bicycle"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Bicycle;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'bicycle' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"bicycleroute"))
         {
          if(ISTRUE(v))
             way.props|=Properties_BicycleRoute;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'bicycleroute' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"bridge"))
         {
          if(ISTRUE(v))
             way.props|=Properties_Bridge;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'bridge' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

	  case 'c':
       if(!strcmp(k,"cycleway"))
         {
          if(!strcmp(v,"opposite_lane"))
             way.props|=Properties_DoubleSens;
           recognised=1; break;
         }
	    break;
	   
      case 'f':
       if(!strcmp(k,"foot"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Foot;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'foot' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"footroute"))
         {
          if(ISTRUE(v))
             way.props|=Properties_FootRoute;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'footroute' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'g':
       if(!strcmp(k,"goods"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Goods;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'goods' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'h':
       if(!strcmp(k,"highway"))
         {recognised=1; break;}

       if(!strcmp(k,"horse"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Horse;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'horse' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"hgv"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_HGV;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'hgv' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

	  case 'i':
       if(!strcmp(k,"incline"))
         {
/* logerror("Way %"Pway_t" has an 'incline' = '%s' \n",logerror_way(id),v); */
         way.incline=pourcent_to_incline(parse_incline(id,k,v));
          recognised=1; break;
		 }
	    break;


      case 'l':
       if(!strcmp(k,"lanes"))
         {
          int en=0;
          float lanesf;
          if(sscanf(v,"%f%n",&lanesf,&en)==1 && en && !v[en])
             lanes=(int)lanesf;
          else
             logerror("Way %"Pway_t" has an unrecognised tag 'lanes' = '%s' (after tagging rules); ignoring it.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'm':
       if(!strncmp(k,"max",3))
         {
          if(!strcmp(k+3,"speed"))
            {
             way.speed=kph_to_speed(parse_speed(id,k,v));
             recognised=1; break;
            }

          if(!strcmp(k+3,"weight"))
            {
             way.weight=tonnes_to_weight(parse_weight(id,k,v));
             recognised=1; break;
            }

          if(!strcmp(k+3,"height"))
            {
             way.height=metres_to_height(parse_length(id,k,v));
             recognised=1; break;
            }

          if(!strcmp(k+3,"width"))
            {
             way.width=metres_to_height(parse_length(id,k,v));
             recognised=1; break;
            }

          if(!strcmp(k+3,"length"))
            {
             way.length=metres_to_height(parse_length(id,k,v));
             recognised=1; break;
            }
         }

       if(!strcmp(k,"moped"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Moped;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'moped' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"motorcycle"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Motorcycle;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'motorcycle' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"motorcar"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Motorcar;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'motorcar' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"multilane"))
         {
          if(ISTRUE(v))
             way.props|=Properties_Multilane;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'multilane' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'n':
       if(!strcmp(k,"name"))
         {
          name=v;
          recognised=1; break;
         }

       break;

      case 'o':
       if(!strcmp(k,"oneway"))
         {
          if(ISTRUE(v))
             oneway=1;
          else if(!strcmp(v,"-1"))
             oneway=-1;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'oneway' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'p':
       if(!strcmp(k,"paved"))
         {
          if(ISTRUE(v))
             way.props|=Properties_Paved;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'paved' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"psv"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_PSV;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'psv' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'r':
       if(!strcmp(k,"ref"))
         {
          ref=v;
          recognised=1; break;
         }

       if(!strcmp(k,"roundabout"))
         {
          if(ISTRUE(v))
             roundabout=1;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'roundabout' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 't':
       if(!strcmp(k,"tunnel"))
         {
          if(ISTRUE(v))
             way.props|=Properties_Tunnel;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'tunnel' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      case 'w':
       if(!strcmp(k,"wheelchair"))
         {
          if(ISTRUE(v))
             way.allow|=Transports_Wheelchair;
          else if(!ISFALSE(v))
             logerror("Way %"Pway_t" has an unrecognised tag 'wheelchair' = '%s' (after tagging rules); using 'no'.\n",logerror_way(id),v);
          recognised=1; break;
         }

       break;

      default:
       break;
      }

    if(!recognised)
       logerror("Way %"Pway_t" has an unrecognised tag '%s' = '%s' (after tagging rules); ignoring it.\n",logerror_way(id),k,v);
   }

 /* Create the way */

 if(area && oneway)
   {
    logerror("Way %"Pway_t" is an area and oneway; ignoring area tagging.\n",logerror_way(id));
    area=0;
   }

 if(!way.allow)
    return;

 if(oneway)
   {
    way.type|=Highway_OneWay;

    if(oneway==-1)
       for(i=0;i<way_nnodes/2;i++)
         {
          node_t temp;

          temp=way_nodes[i];
          way_nodes[i]=way_nodes[way_nnodes-i-1];
          way_nodes[way_nnodes-i-1]=temp;
         }
   }

 if(roundabout)
    way.type|=Highway_Roundabout;

 if(area)
   {
    way.type|=Highway_Area;

    if(way_nodes[0]!=way_nodes[way_nnodes-1])
       logerror("Way %"Pway_t" is an area but not closed.\n",logerror_way(id));
   }

 if(lanes)
   {
    if(oneway || (lanes/2)>1)
       way.props|=Properties_Multilane;

    if(oneway && lanes==1)
       way.props&=~Properties_Multilane;
   }

 if(ref && name)
   {
    refname=(char*)malloc(strlen(ref)+strlen(name)+4);
    sprintf(refname,"%s (%s)",name,ref);
   }
 else if(ref && !name)
    refname=ref;
 else if(!ref && name)
    refname=name;
 else /* if(!ref && !name) */
    refname="";

 AppendWayList(ways,id,&way,way_nodes,way_nnodes,refname);

 if(ref && name)
    free(refname);
}
void ProcessNodeTags(TagList *tags,int64_t node_id,double latitude,double longitude,int mode)
{
 transports_t allow=Transports_ALL;
 nodeflags_t flags=0;
 node_t id;
 int i;

 /* Convert id */

 id=(node_t)node_id;
 logassert((int64_t)id==node_id,"Node ID too large (change node_t to 64-bits?)"); /* check node id can be stored in node_t data type. */

 /* Delete */

 if(mode==MODE_DELETE)
   {
    AppendNodeList(nodes,id,degrees_to_radians(latitude),degrees_to_radians(longitude),allow,NODE_DELETED);

    return;
   }

 /* Parse the tags */

 for(i=0;i<tags->ntags;i++)
   {
    int recognised=0;
    char *k=tags->k[i];
    char *v=tags->v[i];

    switch(*k)
      {
      case 'b':
       if(!strcmp(k,"bicycle"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Bicycle;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'bicycle' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'f':
       if(!strcmp(k,"foot"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Foot;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'foot' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'g':
       if(!strcmp(k,"goods"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Goods;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'goods' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'h':
       if(!strcmp(k,"horse"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Horse;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'horse' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"hgv"))
         {
          if(ISFALSE(v))
             allow&=~Transports_HGV;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'hgv' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'm':
       if(!strcmp(k,"moped"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Moped;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'moped' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"motorcycle"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Motorcycle;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'motorcycle' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       if(!strcmp(k,"motorcar"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Motorcar;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'motorcar' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'p':
       if(!strcmp(k,"psv"))
         {
          if(ISFALSE(v))
             allow&=~Transports_PSV;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'psv' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      case 'r':
       if(!strcmp(k,"roundabout"))
         {
          if(ISTRUE(v))
             flags|=NODE_MINIRNDBT;
          else
             logerror("Node %"Pnode_t" has an unrecognised tag 'roundabout' = '%s' (after tagging rules); using 'no'.\n",id,v);
          recognised=1; break;
         }

       break;

      case 'w':
       if(!strcmp(k,"wheelchair"))
         {
          if(ISFALSE(v))
             allow&=~Transports_Wheelchair;
          else if(!ISTRUE(v))
             logerror("Node %"Pnode_t" has an unrecognised tag 'wheelchair' = '%s' (after tagging rules); using 'yes'.\n",logerror_node(id),v);
          recognised=1; break;
         }

       break;

      default:
       break;
      }

    if(!recognised)
       logerror("Node %"Pnode_t" has an unrecognised tag '%s' = '%s' (after tagging rules); ignoring it.\n",logerror_node(id),k,v);
   }

 /* Create the node */

 AppendNodeList(nodes,id,degrees_to_radians(latitude),degrees_to_radians(longitude),allow,flags);
}
BOOL CDisplayAdapterHelper::InjectSpecificDllAndProcessByIdInner(DWORD dwProcessID, LPSTR lpDllName, BOOL bInjectSafeMode)
{
#if defined _M_X64 && _MSC_VER == 1800
	//workaround AVX2 bug in VS2013, http://connect.microsoft.com/VisualStudio/feedback/details/811093
	_set_FMA3_enable(0);
#endif
	
	assert(dwProcessID != 0);
	if (ISZERO(dwProcessID))
	{
		DOLOG("id of target process can't be zero !");
		return FALSE;
	}
	assert(ISNOTNULL(lpDllName));
	if(ISNULL(lpDllName))
	{
		DOLOG("name of dll can't not be null !");
		return FALSE;
	}

	CHAR cbDllPath[MAX_PATH] = { 0 };
	//if (ISZERO(GetCurrentDirectoryA(dirLen, cbDllPath)))
	if(ISZERO(GetModuleFileNameA(GetModuleHandle(NULL), cbDllPath, MAX_PATH)))
	{
		DOLOG("GetCurrentDirectory Failed ! " + GetLastError());
		return FALSE;
	}
	CHAR* lpFullPath = strrchr(cbDllPath, '\\');
	lpFullPath[1] = '\0';
	UINT dirLen = strlen(cbDllPath);
	const size_t fileNameLen = strlen(lpDllName);
	size_t len = dirLen + fileNameLen + 1;
	cbDllPath[dirLen - 1] = '\\';
	strncpy_s(cbDllPath + dirLen, len - dirLen, lpDllName, fileNameLen);

	BOOL result = TRUE;
	LoadSeDebugPrivilege();
	
	CNameEvent nameEvent;
	nameEvent.Init(EVENTNAME, TRUE);
	CNameShareMemory shareMemInst;

	shareMemInst.Init(SHAREMEMNAME, MAX_PATH, TRUE);
	char* lpInfo = shareMemInst.GetBuffer();
	ZeroMemory(lpInfo, MAX_PATH);

	if (!bInjectSafeMode)
	{
		OPPROC pOpenProcess;
		HANDLE hProcess;
		char pOPStr[12];
		int i;

		memcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated
		for (i = 0; i<11; i++) pOPStr[i] ^= i ^ 1;

		pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr);

		if (ISNULL(pOpenProcess))
		{
			DOLOG("GetProcAddress failed ! " + GetLastError());
			return FALSE;
		}

		hProcess = (*pOpenProcess)(PROCESS_ALL_ACCESS, FALSE, dwProcessID);

		if (ISNULL(hProcess))
		{
			DOLOG("OpenProcess Failed ! " + GetLastError());
			return FALSE;
		}
		if (ISFALSE(AdjustDllforProcess(hProcess, cbDllPath)))
		{
			DOLOG("AdjustDllforProcess Failed ! " + GetLastError());
			return FALSE;
		}

		if (ISNOTTRUE(InjectLibraryA(hProcess, cbDllPath, (DWORD)(len - 1))))
		{
			result = FALSE;
			DOLOG("Inject Library failed ! " + GetLastError());
		}

		CloseHandle(hProcess);
	}
	else
	{

#ifdef _WIN64
		CHAR cbTempDllPath[MAX_PATH] = { 0 };
		if (ISTRUE(AdjustDllfor64bit(cbTempDllPath, MAX_PATH, cbDllPath)))
		{
			memcpy(cbDllPath, cbTempDllPath, strlen(cbTempDllPath) + 1);
		}
#endif
		if (!InjectLibrarySafeA(dwProcessID, cbDllPath, (DWORD)(len - 1)))
		{
			DOLOG("InjectLibrarySafeA failed ! "+ GetLastError());
			result = FALSE;
		}
	}

	if(ISTRUE(nameEvent.Wait()))
	{
		lpInfo = shareMemInst.GetBuffer();
		if (ISNOTNULL(lpInfo))
		{
			DOLOG(" 得到的信息是>>>>>>" + lpInfo);
			strcpy(m_cbVideoAdapterName, lpInfo);
		}
	}
	nameEvent.Close();
	shareMemInst.Close();

	return result ;
}