xsltWithParamComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
    xsltStyleItemWithParamPtr comp;
#else
    xsltStylePreCompPtr comp;
#endif

    if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
	return;

#ifdef XSLT_REFACTORED
    comp = (xsltStyleItemWithParamPtr) xsltNewStylePreComp(style, XSLT_FUNC_WITHPARAM);
#else
    comp = xsltNewStylePreComp(style, XSLT_FUNC_WITHPARAM);
#endif

    if (comp == NULL)
	return;
    inst->psvi = comp;
    comp->inst = inst;

    /*
    * Attribute "name".
    */
    xsltGetQNameProperty(style, inst, BAD_CAST "name",
	1, &(comp->has_name), &(comp->ns), &(comp->name));
    if (comp->ns)
	comp->has_ns = 1;
    /*
    * Attribute "select".
    */
    comp->select = xsltGetCNsProp(style, inst, (const xmlChar *)"select",
	                        XSLT_NAMESPACE);
    if (comp->select != NULL) {
	comp->comp = xsltXPathCompile(style, comp->select);
	if (comp->comp == NULL) {
	    xsltTransformError(NULL, style, inst,
		 "XSLT-with-param: Failed to compile select "
		 "expression '%s'\n", comp->select);
	    style->errors++;
	}
	if (inst->children != NULL) {
	    xsltTransformError(NULL, style, inst,
		"XSLT-with-param: The content should be empty since "
		"the attribute select is present.\n");
	    style->warnings++;
	}
    }
}


xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr node) {
    /*
    * The xsltXSLTElemMarker marker was set beforehand by
    *  the parsing mechanism for all elements in the XSLT namespace.
    */
    if (style == NULL) {
	if ((node != NULL) && (node->type == XML_ELEMENT_NODE))
	    node->psvi = NULL;
	return;
    }
    if (node == NULL)
	return;
    if (! IS_XSLT_ELEM_FAST(node))
	return;

    node->psvi = NULL;
    if (XSLT_CCTXT(style)->inode->type != 0) {
	switch (XSLT_CCTXT(style)->inode->type) {
	    case XSLT_FUNC_APPLYTEMPLATES:
		xsltApplyTemplatesComp(style, node);
		break;
	    case XSLT_FUNC_WITHPARAM:
		xsltWithParamComp(style, node);
		break;
	    case XSLT_FUNC_VALUEOF:
		xsltValueOfComp(style, node);
		break;
	    case XSLT_FUNC_COPY:
		xsltCopyComp(style, node);
		break;
	    case XSLT_FUNC_COPYOF:
		xsltCopyOfComp(style, node);
		break;
	    case XSLT_FUNC_IF:
		xsltIfComp(style, node);
		break;
	    case XSLT_FUNC_CHOOSE:
		xsltChooseComp(style, node);
		break;
	    case XSLT_FUNC_WHEN:
		xsltWhenComp(style, node);
		break;
	    case XSLT_FUNC_OTHERWISE:
		/* NOP yet */
		return;
	    case XSLT_FUNC_FOREACH:
		xsltForEachComp(style, node);
		break;
	    case XSLT_FUNC_APPLYIMPORTS:
		xsltApplyImportsComp(style, node);
		break;
	    case XSLT_FUNC_ATTRIBUTE:
		xsltAttributeComp(style, node);
		break;
	    case XSLT_FUNC_ELEMENT:
		xsltElementComp(style, node);
		break;
	    case XSLT_FUNC_SORT:
		xsltSortComp(style, node);
		break;
	    case XSLT_FUNC_COMMENT:
		xsltCommentComp(style, node);
		break;
	    case XSLT_FUNC_NUMBER:
		xsltNumberComp(style, node);
		break;
	    case XSLT_FUNC_PI:
		xsltProcessingInstructionComp(style, node);
		break;
	    case XSLT_FUNC_CALLTEMPLATE:
		xsltCallTemplateComp(style, node);
		break;
	    case XSLT_FUNC_PARAM:
		xsltParamComp(style, node);
		break;
	    case XSLT_FUNC_VARIABLE:
		xsltVariableComp(style, node);
		break;
	    case XSLT_FUNC_FALLBACK:
		/* NOP yet */
		return;
	    case XSLT_FUNC_DOCUMENT:
		/* The extra one */
		node->psvi = (void *) xsltDocumentComp(style, node,
		    (xsltTransformFunction) xsltDocumentElem);
		break;
	    case XSLT_FUNC_MESSAGE:
		/* NOP yet */
		return;
	    default:
		/*
		* NOTE that xsl:text, xsl:template, xsl:stylesheet,
		*  xsl:transform, xsl:import, xsl:include are not expected
		*  to be handed over to this function.
		*/
		xsltTransformError(NULL, style, node,
		    "Internal error: (xsltStylePreCompute) cannot handle "
		    "the XSLT element '%s'.\n", node->name);
		style->errors++;
		return;
	}
    } else {
	/*
	* Fallback to string comparison.
	*/
	if (IS_XSLT_NAME(node, "apply-templates")) {
	    xsltApplyTemplatesComp(style, node);
	} else if (IS_XSLT_NAME(node, "with-param")) {
	    xsltWithParamComp(style, node);
	} else if (IS_XSLT_NAME(node, "value-of")) {
	    xsltValueOfComp(style, node);
	} else if (IS_XSLT_NAME(node, "copy")) {
	    xsltCopyComp(style, node);
	} else if (IS_XSLT_NAME(node, "copy-of")) {
	    xsltCopyOfComp(style, node);
	} else if (IS_XSLT_NAME(node, "if")) {
	    xsltIfComp(style, node);
	} else if (IS_XSLT_NAME(node, "choose")) {
	    xsltChooseComp(style, node);
	} else if (IS_XSLT_NAME(node, "when")) {
	    xsltWhenComp(style, node);
	} else if (IS_XSLT_NAME(node, "otherwise")) {
	    /* NOP yet */
	    return;
	} else if (IS_XSLT_NAME(node, "for-each")) {
	    xsltForEachComp(style, node);
	} else if (IS_XSLT_NAME(node, "apply-imports")) {
	    xsltApplyImportsComp(style, node);
	} else if (IS_XSLT_NAME(node, "attribute")) {
	    xsltAttributeComp(style, node);
	} else if (IS_XSLT_NAME(node, "element")) {
	    xsltElementComp(style, node);
	} else if (IS_XSLT_NAME(node, "sort")) {
	    xsltSortComp(style, node);
	} else if (IS_XSLT_NAME(node, "comment")) {
	    xsltCommentComp(style, node);
	} else if (IS_XSLT_NAME(node, "number")) {
	    xsltNumberComp(style, node);
	} else if (IS_XSLT_NAME(node, "processing-instruction")) {
	    xsltProcessingInstructionComp(style, node);
	} else if (IS_XSLT_NAME(node, "call-template")) {
	    xsltCallTemplateComp(style, node);
	} else if (IS_XSLT_NAME(node, "param")) {
	    xsltParamComp(style, node);
	} else if (IS_XSLT_NAME(node, "variable")) {
	    xsltVariableComp(style, node);
	} else if (IS_XSLT_NAME(node, "fallback")) {
	    /* NOP yet */
	    return;
	} else if (IS_XSLT_NAME(node, "document")) {
	    /* The extra one */
	    node->psvi = (void *) xsltDocumentComp(style, node,
		(xsltTransformFunction) xsltDocumentElem);
	} else if (IS_XSLT_NAME(node, "output")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "preserve-space")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "strip-space")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "key")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "message")) {
	    return;
	} else if (IS_XSLT_NAME(node, "attribute-set")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "namespace-alias")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "decimal-format")) {
	    /* Top-level */
	    return;
	} else if (IS_XSLT_NAME(node, "include")) {
	    /* Top-level */
	} else {
	    /*
	    * NOTE that xsl:text, xsl:template, xsl:stylesheet,
	    *  xsl:transform, xsl:import, xsl:include are not expected
	    *  to be handed over to this function.
	    */
	    xsltTransformError(NULL, style, node,
		"Internal error: (xsltStylePreCompute) cannot handle "
		"the XSLT element '%s'.\n", node->name);
		style->errors++;
	    return;
	}
    }
    /*
    * Assign the current list of in-scope namespaces to the
    * item. This is needed for XPath expressions.
    */
    if (node->psvi != NULL) {
	((xsltStylePreCompPtr) node->psvi)->inScopeNs =
	    XSLT_CCTXT(style)->inode->inScopeNs;
    }
}


static void Report(char *fmt, int n1, int n2)
{
	int len;
	char rbuf[40];		/* enough room for all replys */

	sprintf(rbuf, fmt, n1, n2);
	len = strlen(rbuf);

	if (W_UWP(curr)) {
		if ((unsigned)(curr->w_pwin->p_inlen + len) <= sizeof(curr->w_pwin->p_inbuf)) {
			memmove(curr->w_pwin->p_inbuf + curr->w_pwin->p_inlen, rbuf, len);
			curr->w_pwin->p_inlen += len;
		}
	} else {
		if ((unsigned)(curr->w_inlen + len) <= sizeof(curr->w_inbuf)) {
			memmove(curr->w_inbuf + curr->w_inlen, rbuf, len);
			curr->w_inlen += len;
		}
	}
}


static void MScrollH(Window *p, int n, int y, int xs, int xe, int bce)
{
	struct mline *ml;

	if (n == 0)
		return;
	ml = &p->w_mlines[y];
	MKillDwRight(p, ml, xs);
	MKillDwLeft(p, ml, xe);
	if (n > 0) {
		if (xe - xs + 1 > n) {
			MKillDwRight(p, ml, xs + n);
			copy_mline(ml, xs + n, xs, xe + 1 - xs - n);
		} else
			n = xe - xs + 1;
		clear_mline(ml, xe + 1 - n, n);
		if (bce)
			MBceLine(p, y, xe + 1 - n, n, bce);
	} else {
		n = -n;
		if (xe - xs + 1 > n) {
			MKillDwLeft(p, ml, xe - n);
			copy_mline(ml, xs, xs + n, xe + 1 - xs - n);
		} else
			n = xe - xs + 1;
		clear_mline(ml, xs, n);
		if (bce)
			MBceLine(p, y, xs, n, bce);
	}
}


static void MPutChar(Window *p, struct mchar *c, int x, int y)
{
	struct mline *ml;

	MFixLine(p, y, c);
	ml = &p->w_mlines[y];
	MKillDwRight(p, ml, x);
	MKillDwLeft(p, ml, x);
	copy_mchar2mline(c, ml, x);
	if (c->mbcs) {
		MKillDwLeft(p, ml, x + 1);
		copy_mchar2mline(c, ml, x + 1);
		ml->image[x + 1] = c->mbcs;
		if (p->w_encoding != UTF8)
			ml->font[x + 1] |= 0x80;
		else if (p->w_encoding == UTF8 && c->mbcs) {
			ml->font[x + 1] = c->mbcs;
			ml->fontx[x + 1] = 0;
		}
	}
}


void WNewAutoFlow(Window *window, int on)
{
	if (window->w_flow & FLOW_AUTOFLAG)
		window->w_flow = FLOW_AUTOFLAG | (FLOW_AUTO | FLOW_NOW) * on;
	else
		window->w_flow = (window->w_flow & ~FLOW_AUTO) | FLOW_AUTO * on;
	LSetFlow(&window->w_layer, window->w_flow & FLOW_NOW);
}


static void Return()
{
	if (curr->w_x == 0)
		return;
	curr->w_x = 0;
	LGotoPos(&curr->w_layer, curr->w_x, curr->w_y);
}


PHPAPI void php_var_export(zval **struc, int level TSRMLS_DC) /* {{{ */
{
	smart_str buf = {0};
	php_var_export_ex(struc, level, &buf TSRMLS_CC);
	smart_str_0 (&buf);
	PHPWRITE(buf.c, buf.len);
	smart_str_free(&buf);
}


static PHP_FUNCTION(session_set_save_handler)
{
	zval ***args = NULL;
	int i, num_args, argc = ZEND_NUM_ARGS();
	char *name;

	if (PS(session_status) != php_session_none) {
		RETURN_FALSE;
	}

	if (argc != 1 && argc != 2 && argc != 6) {
		WRONG_PARAM_COUNT;
	}

	if (argc <= 2) {
		zval *obj = NULL, *callback = NULL;
		zend_uint func_name_len;
		char *func_name;
		HashPosition pos;
		zend_function *default_mptr, *current_mptr;
		ulong func_index;
		php_shutdown_function_entry shutdown_function_entry;
		zend_bool register_shutdown = 1;

		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &obj, php_session_iface_entry, &register_shutdown) == FAILURE) {
			RETURN_FALSE;
		}

		/* Find implemented methods */
		zend_hash_internal_pointer_reset_ex(&php_session_class_entry->function_table, &pos);
		i = 0;
		while (zend_hash_get_current_data_ex(&php_session_class_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
			zend_hash_get_current_key_ex(&php_session_class_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);

			if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)&current_mptr) == SUCCESS) {
				if (PS(mod_user_names).names[i] != NULL) {
					zval_ptr_dtor(&PS(mod_user_names).names[i]);
				}

				MAKE_STD_ZVAL(callback);
				array_init_size(callback, 2);
				Z_ADDREF_P(obj);
				add_next_index_zval(callback, obj);
				add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
				PS(mod_user_names).names[i] = callback;
			} else {
				php_error_docref(NULL TSRMLS_CC, E_ERROR, "Session handler's function table is corrupt");
				RETURN_FALSE;
			}

			zend_hash_move_forward_ex(&php_session_class_entry->function_table, &pos);
			++i;
		}

		if (register_shutdown) {
			/* create shutdown function */
			shutdown_function_entry.arg_count = 1;
			shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);

			MAKE_STD_ZVAL(callback);
			ZVAL_STRING(callback, "session_register_shutdown", 1);
			shutdown_function_entry.arguments[0] = callback;

			/* add shutdown function, removing the old one if it exists */
			if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown"), &shutdown_function_entry TSRMLS_CC)) {
				zval_ptr_dtor(&callback);
				efree(shutdown_function_entry.arguments);
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session shutdown function");
				RETURN_FALSE;
			}
		} else {
			/* remove shutdown function */
			remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
		}

		if (PS(mod) && PS(session_status) == php_session_none && PS(mod) != &ps_mod_user) {
			zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
		}

		RETURN_TRUE;
	}

	if (zend_parse_parameters(argc TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
		return;
	}

	/* remove shutdown function */
	remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);

	for (i = 0; i < 6; i++) {
		if (!zend_is_callable(*args[i], 0, &name TSRMLS_CC)) {
			efree(args);
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument %d is not a valid callback", i+1);
			efree(name);
			RETURN_FALSE;
		}
		efree(name);
	}

	if (PS(mod) && PS(mod) != &ps_mod_user) {
		zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
	}

	for (i = 0; i < 6; i++) {
		if (PS(mod_user_names).names[i] != NULL) {
			zval_ptr_dtor(&PS(mod_user_names).names[i]);
		}
		Z_ADDREF_PP(args[i]);
		PS(mod_user_names).names[i] = *args[i];
	}

	efree(args);
	RETURN_TRUE;
}


PHP_HASH_API void PHP_HAVAL224Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
	unsigned char bits[10];
	unsigned int index, padLen;

	/* Version, Passes, and Digest Length */
	bits[0] =	(PHP_HASH_HAVAL_VERSION & 0x07) |
				((context->passes & 0x07) << 3) |
				((context->output & 0x03) << 6);
	bits[1] = (context->output >> 2);

	/* Save number of bits */
	Encode(bits + 2, context->count, 8);

	/* Pad out to 118 mod 128.
	 */
	index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
	padLen = (index < 118) ? (118 - index) : (246 - index);
	PHP_HAVALUpdate(context, PADDING, padLen);

	/* Append version, passes, digest length, and message length */
	PHP_HAVALUpdate(context, bits, 10);

	/* Store state in digest */
	context->state[6] +=  context->state[7]        & 0x0000000F;
	context->state[5] += (context->state[7] >>  4) & 0x0000001F;
	context->state[4] += (context->state[7] >>  9) & 0x0000000F;
	context->state[3] += (context->state[7] >> 13) & 0x0000001F;
	context->state[2] += (context->state[7] >> 18) & 0x0000000F;
	context->state[1] += (context->state[7] >> 22) & 0x0000001F;
	context->state[0] += (context->state[7] >> 27) & 0x0000001F;
	Encode(digest, context->state, 28);

	/* Zeroize sensitive information.
	 */
	memset((unsigned char*) context, 0, sizeof(*context));
}


PHPAPI void  php_pcre_grep_impl(pcre_cache_entry *pce, zval *input, zval *return_value, long flags TSRMLS_DC) /* {{{ */
{
	zval		   **entry;				/* An entry in the input array */
	pcre_extra		*extra = pce->extra;/* Holds results of studying */
	pcre_extra		 extra_data;		/* Used locally for exec options */
	int				*offsets;			/* Array of subpattern offsets */
	int				 size_offsets;		/* Size of the offsets array */
	int				 count = 0;			/* Count of matched subpatterns */
	char			*string_key;
	ulong			 num_key;
	zend_bool		 invert;			/* Whether to return non-matching
										   entries */
	int				 rc;

	invert = flags & PREG_GREP_INVERT ? 1 : 0;

	if (extra == NULL) {
		extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
		extra = &extra_data;
	}
	extra->match_limit = PCRE_G(backtrack_limit);
	extra->match_limit_recursion = PCRE_G(recursion_limit);

	/* Calculate the size of the offsets array, and allocate memory for it. */
	rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &size_offsets);
	if (rc < 0) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
		RETURN_FALSE;
	}
	size_offsets = (size_offsets + 1) * 3;
	offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);

	/* Initialize return array */
	array_init(return_value);

	PCRE_G(error_code) = PHP_PCRE_NO_ERROR;

	/* Go through the input array */
	zend_hash_internal_pointer_reset(Z_ARRVAL_P(input));
	while (zend_hash_get_current_data(Z_ARRVAL_P(input), (void **)&entry) == SUCCESS) {
		zval subject = **entry;

		if (Z_TYPE_PP(entry) != IS_STRING) {
			zval_copy_ctor(&subject);
			convert_to_string(&subject);
		}

		/* Perform the match */
		count = pcre_exec(pce->re, extra, Z_STRVAL(subject),
						  Z_STRLEN(subject), 0,
						  0, offsets, size_offsets);

		/* Check for too many substrings condition. */
		if (count == 0) {
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings");
			count = size_offsets/3;
		} else if (count < 0 && count != PCRE_ERROR_NOMATCH) {
			pcre_handle_exec_error(count TSRMLS_CC);
			break;
		}

		/* If the entry fits our requirements */
		if ((count > 0 && !invert) || (count == PCRE_ERROR_NOMATCH && invert)) {

			Z_ADDREF_PP(entry);

			/* Add to return array */
			switch (zend_hash_get_current_key(Z_ARRVAL_P(input), &string_key, &num_key, 0))
			{
				case HASH_KEY_IS_STRING:
					zend_hash_update(Z_ARRVAL_P(return_value), string_key,
									 strlen(string_key)+1, entry, sizeof(zval *), NULL);
					break;

				case HASH_KEY_IS_LONG:
					zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry,
										   sizeof(zval *), NULL);
					break;
			}
		}

		if (Z_TYPE_PP(entry) != IS_STRING) {
			zval_dtor(&subject);
		}

		zend_hash_move_forward(Z_ARRVAL_P(input));
	}
	zend_hash_internal_pointer_reset(Z_ARRVAL_P(input));
	/* Clean up */
	efree(offsets);
}


static PHP_FUNCTION(preg_grep)
{
	char				*regex;			/* Regular expression */
	int				 	 regex_len;
	zval				*input;			/* Input array */
	long				 flags = 0;		/* Match control flags */
	pcre_cache_entry	*pce;			/* Compiled regular expression */

	/* Get arguments and do error checking */
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sa|l", &regex, &regex_len,
							  &input, &flags) == FAILURE) {
		return;
	}

	/* Compile regex or get it from cache. */
	if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
		RETURN_FALSE;
	}

	php_pcre_grep_impl(pce, input, return_value, flags TSRMLS_CC);
}


PHP_METHOD(SoapServer, getFunctions)
{
	soapServicePtr  service;
	HashTable      *ft = NULL;

	SOAP_SERVER_BEGIN_CODE();

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	FETCH_THIS_SERVICE(service);

	array_init(return_value);
	if (service->type == SOAP_OBJECT) {
		ft = &(Z_OBJCE_P(service->soap_object)->function_table);
	} else if (service->type == SOAP_CLASS) {
		ft = &service->soap_class.ce->function_table;
	} else if (service->soap_functions.functions_all == TRUE) {
		ft = EG(function_table);
	} else if (service->soap_functions.ft != NULL) {
		zval **name;
		HashPosition pos;

		zend_hash_internal_pointer_reset_ex(service->soap_functions.ft, &pos);
		while (zend_hash_get_current_data_ex(service->soap_functions.ft, (void **)&name, &pos) != FAILURE) {
			add_next_index_string(return_value, Z_STRVAL_PP(name), 1);
			zend_hash_move_forward_ex(service->soap_functions.ft, &pos);
		}
	}
	if (ft != NULL) {
		zend_function *f;
		HashPosition pos;
		zend_hash_internal_pointer_reset_ex(ft, &pos);
		while (zend_hash_get_current_data_ex(ft, (void **)&f, &pos) != FAILURE) {
			if ((service->type != SOAP_OBJECT && service->type != SOAP_CLASS) || (f->common.fn_flags & ZEND_ACC_PUBLIC)) {
				add_next_index_string(return_value, f->common.function_name, 1);
			}
			zend_hash_move_forward_ex(ft, &pos);
		}
	}

	SOAP_SERVER_END_CODE();
}


PHP_FUNCTION(xsl_xsltprocessor_import_stylesheet)
{
	zval *id, *docp = NULL;
	xmlDoc *doc = NULL, *newdoc = NULL;
	xsltStylesheetPtr sheetp, oldsheetp;
	xsl_object *intern;
	int prevSubstValue, prevExtDtdValue, clone_docu = 0;
	xmlNode *nodep = NULL;
	zend_object_handlers *std_hnd;
	zval *cloneDocu, *member;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oo", &id, xsl_xsltprocessor_class_entry, &docp) == FAILURE) {
		RETURN_FALSE;
	}

	nodep = php_libxml_import_node(docp TSRMLS_CC);

	if (nodep) {
		doc = nodep->doc;
	}
	if (doc == NULL) {
		php_error(E_WARNING, "Invalid Document");
		RETURN_FALSE;
	}

	/* libxslt uses _private, so we must copy the imported
	stylesheet document otherwise the node proxies will be a mess */
	newdoc = xmlCopyDoc(doc, 1);
	xmlNodeSetBase((xmlNodePtr) newdoc, (xmlChar *)doc->URL);
	prevSubstValue = xmlSubstituteEntitiesDefault(1);
	prevExtDtdValue = xmlLoadExtDtdDefaultValue;
	xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;

	sheetp = xsltParseStylesheetDoc(newdoc);
	xmlSubstituteEntitiesDefault(prevSubstValue);
	xmlLoadExtDtdDefaultValue = prevExtDtdValue;

	if (!sheetp) {
		xmlFreeDoc(newdoc);
		RETURN_FALSE;
	}

	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);

	std_hnd = zend_get_std_object_handlers();
	MAKE_STD_ZVAL(member);
	ZVAL_STRING(member, "cloneDocument", 0);
	cloneDocu = std_hnd->read_property(id, member, BP_VAR_IS, NULL TSRMLS_CC);
	if (Z_TYPE_P(cloneDocu) != IS_NULL) {
		convert_to_long(cloneDocu);
		clone_docu = Z_LVAL_P(cloneDocu);
	}
	efree(member);
	if (clone_docu == 0) {
		/* check if the stylesheet is using xsl:key, if yes, we have to clone the document _always_ before a transformation */
		nodep = xmlDocGetRootElement(sheetp->doc);
		if (nodep && (nodep = nodep->children)) {
			while (nodep) {
				if (nodep->type == XML_ELEMENT_NODE && xmlStrEqual(nodep->name, "key") && xmlStrEqual(nodep->ns->href, XSLT_NAMESPACE)) {
					intern->hasKeys = 1;
					break;
				}
				nodep = nodep->next;
			}
		}
	} else {
		intern->hasKeys = clone_docu;
	}

	if ((oldsheetp = (xsltStylesheetPtr)intern->ptr)) {
		/* free wrapper */
		if (((xsltStylesheetPtr) intern->ptr)->_private != NULL) {
			((xsltStylesheetPtr) intern->ptr)->_private = NULL;
		}
		xsltFreeStylesheet((xsltStylesheetPtr) intern->ptr);
		intern->ptr = NULL;
	}

	php_xsl_set_object(id, sheetp TSRMLS_CC);
	RETVAL_TRUE;
}


 */
void
xmlXPathEvalExpr(xmlXPathParserContextPtr ctxt) {
#ifdef XPATH_STREAMING
    xmlXPathCompExprPtr comp;
#endif

    if (ctxt == NULL) return;

#ifdef XPATH_STREAMING
    comp = xmlXPathTryStreamCompile(ctxt->context, ctxt->base);
    if (comp != NULL) {
        if (ctxt->comp != NULL)
	    xmlXPathFreeCompExpr(ctxt->comp);
        ctxt->comp = comp;
	if (ctxt->cur != NULL)
	    while (*ctxt->cur != 0) ctxt->cur++;
    } else
#endif
    {
	xmlXPathCompileExpr(ctxt, 1);
	if ((ctxt->error == XPATH_EXPRESSION_OK) &&
	    (ctxt->comp != NULL) &&
	    (ctxt->comp->nbStep > 1) &&
	    (ctxt->comp->last >= 0))
	{
	    xmlXPathOptimizeExpression(ctxt->comp,
		&ctxt->comp->steps[ctxt->comp->last]);
	}
    }
    CHECK_ERROR;


xmlXPathNodeLeadingSorted (xmlNodeSetPtr nodes, xmlNodePtr node) {
    int i, l;
    xmlNodePtr cur;
    xmlNodeSetPtr ret;

    if (node == NULL)
	return(nodes);

    ret = xmlXPathNodeSetCreate(NULL);
    if (ret == NULL)
        return(ret);
    if (xmlXPathNodeSetIsEmpty(nodes) ||
	(!xmlXPathNodeSetContains(nodes, node)))
	return(ret);

    l = xmlXPathNodeSetGetLength(nodes);
    for (i = 0; i < l; i++) {
	cur = xmlXPathNodeSetItem(nodes, i);
	if (cur == node)
	    break;
	if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
	    break;
    }
    return(ret);
}


 */
static void
xmlXPathEscapeUriFunction(xmlXPathParserContextPtr ctxt, int nargs) {
    xmlXPathObjectPtr str;
    int escape_reserved;
    xmlBufPtr target;
    xmlChar *cptr;
    xmlChar escape[4];

    CHECK_ARITY(2);

    escape_reserved = xmlXPathPopBoolean(ctxt);

    CAST_TO_STRING;
    str = valuePop(ctxt);

    target = xmlBufCreate();

    escape[0] = '%';
    escape[3] = 0;

    if (target) {
	for (cptr = str->stringval; *cptr; cptr++) {
	    if ((*cptr >= 'A' && *cptr <= 'Z') ||
		(*cptr >= 'a' && *cptr <= 'z') ||
		(*cptr >= '0' && *cptr <= '9') ||
		*cptr == '-' || *cptr == '_' || *cptr == '.' ||
		*cptr == '!' || *cptr == '~' || *cptr == '*' ||
		*cptr == '\''|| *cptr == '(' || *cptr == ')' ||
		(*cptr == '%' &&
		 ((cptr[1] >= 'A' && cptr[1] <= 'F') ||
		  (cptr[1] >= 'a' && cptr[1] <= 'f') ||
		  (cptr[1] >= '0' && cptr[1] <= '9')) &&
		 ((cptr[2] >= 'A' && cptr[2] <= 'F') ||
		  (cptr[2] >= 'a' && cptr[2] <= 'f') ||
		  (cptr[2] >= '0' && cptr[2] <= '9'))) ||
		(!escape_reserved &&
		 (*cptr == ';' || *cptr == '/' || *cptr == '?' ||
		  *cptr == ':' || *cptr == '@' || *cptr == '&' ||
		  *cptr == '=' || *cptr == '+' || *cptr == '$' ||
		  *cptr == ','))) {
		xmlBufAdd(target, cptr, 1);
	    } else {
		if ((*cptr >> 4) < 10)
		    escape[1] = '0' + (*cptr >> 4);
		else
		    escape[1] = 'A' - 10 + (*cptr >> 4);
		if ((*cptr & 0xF) < 10)
		    escape[2] = '0' + (*cptr & 0xF);
		else
		    escape[2] = 'A' - 10 + (*cptr & 0xF);

		xmlBufAdd(target, &escape[0], 3);
	    }
	}
    }
    valuePush(ctxt, xmlXPathCacheNewString(ctxt->context,
	xmlBufContent(target)));
    xmlBufFree(target);


   Adds an interval to the current date in object.
*/
PHP_FUNCTION(date_add)
{
	zval *object, *interval;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) {
		RETURN_FALSE;
	}

	php_date_add(object, interval, return_value TSRMLS_CC);


   Sets the time.
*/
PHP_FUNCTION(date_time_set)
{
	zval *object;
	long  h, i, s = 0;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) {
		RETURN_FALSE;
	}

	php_date_time_set(object, h, i, s, return_value TSRMLS_CC);


}

timelib_tzinfo *php_date_parse_tzfile_wrapper(char *formal_tzname, const timelib_tzdb *tzdb)
{
	TSRMLS_FETCH();


/* }}} */

static void php_date_date_set(zval *object, long y, long m, long d, zval *return_value TSRMLS_DC)
{
	php_date_obj *dateobj;

	dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC);
	DATE_CHECK_INITIALIZED(dateobj->time, DateTime);
	dateobj->time->y = y;
	dateobj->time->m = m;
	dateobj->time->d = d;


/* Callback to check the date.timezone only when changed increases performance */
/* {{{ static PHP_INI_MH(OnUpdate_date_timezone) */
static PHP_INI_MH(OnUpdate_date_timezone)
{
	if (OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC) == FAILURE) {
		return FAILURE;
	}

	DATEG(timezone_valid) = 0;
	if (stage == PHP_INI_STAGE_RUNTIME) {
		if (!timelib_timezone_id_is_valid(DATEG(default_timezone), DATE_TIMEZONEDB)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG);
		} else {
			DATEG(timezone_valid) = 1;
		}
	}


/* {{{ proto bool checkdate(int month, int day, int year)
   Returns true(1) if it is a valid date in gregorian calendar */
PHP_FUNCTION(checkdate)
{
	long m, d, y;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) {
		RETURN_FALSE;
	}

	if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) {
		RETURN_FALSE;
	}


/* {{{ date_period_it_current_key */
static void date_period_it_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC)
{
	date_period_it *iterator = (date_period_it *)iter;


static void _php_date_tzinfo_dtor(void *tzinfo)
{
	timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo;


/* {{{ Helper functions */
static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC)
{
	/* Checking configure timezone */
	if (DATEG(timezone) && (strlen(DATEG(timezone))) > 0) {
		return DATEG(timezone);
	}
	/* Check config setting for default timezone */
	if (!DATEG(default_timezone)) {
		/* Special case: ext/date wasn't initialized yet */
		zval ztz;

		if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz)
			&& Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) {
			return Z_STRVAL(ztz);
		}
	} else if (*DATEG(default_timezone)) {
		if (DATEG(timezone_valid) == 1) {
			return DATEG(default_timezone);
		}

		if (!timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid date.timezone value '%s', we selected the timezone 'UTC' for now.", DATEG(default_timezone));
			return "UTC";
		}

		DATEG(timezone_valid) = 1;
		return DATEG(default_timezone);
	}
	/* Fallback to UTC */
	php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.");


zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
	date_period_it  *iterator = emalloc(sizeof(date_period_it));
	php_period_obj  *dpobj    = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC);

	if (by_ref) {
		zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
	}

	Z_ADDREF_P(object);
	iterator->intern.data = (void*) dpobj;
	iterator->intern.funcs = &date_period_it_funcs;
	iterator->date_period_zval = object;
	iterator->object = dpobj;
	iterator->current = NULL;


   Sets the ISO date.
*/
PHP_FUNCTION(date_isodate_set)
{
	zval *object;
	long  y, w, d = 1;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) {
		RETURN_FALSE;
	}

	php_date_isodate_set(object, y, w, d, return_value TSRMLS_CC);


   Creates new DateTimeImmutable object from an existing mutable DateTime object.
*/
PHP_METHOD(DateTimeImmutable, createFromMutable)
{
	zval *datetime_object = NULL;
	php_date_obj *new_obj = NULL;
	php_date_obj *old_obj = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!", &datetime_object, date_ce_date) == FAILURE) {
		return;
	}

	php_date_instantiate(date_ce_immutable, return_value TSRMLS_CC);
	old_obj = (php_date_obj *) zend_object_store_get_object(datetime_object TSRMLS_CC);
	new_obj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC);

	new_obj->time = timelib_time_ctor();
	*new_obj->time = *old_obj->time;
	if (old_obj->time->tz_abbr) {
		new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr);
	}
	if (old_obj->time->tz_info) {
		new_obj->time->tz_info = old_obj->time->tz_info;


}

static int implement_date_interface_handler(zend_class_entry *interface, zend_class_entry *implementor TSRMLS_DC)
{
	if (implementor->type == ZEND_USER_CLASS &&
		!instanceof_function(implementor, date_ce_date TSRMLS_CC) &&
		!instanceof_function(implementor, date_ce_immutable TSRMLS_CC)
	) {
		zend_error(E_ERROR, "DateTimeInterface can't be implemented by user classes");
	}


}

static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime)
{
	char   *format;
	int     format_len;
	long    ts;
	char   *string;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) {
		RETURN_FALSE;
	}
	if (ZEND_NUM_ARGS() == 1) {
		ts = time(NULL);
	}

	string = php_format_date(format, format_len, ts, localtime TSRMLS_CC);


 Return all registered __autoload() functionns */
PHP_FUNCTION(spl_autoload_functions)
{
	zend_function *fptr;
	HashPosition function_pos;
	autoload_func_info *alfi;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	if (!EG(autoload_func)) {
		if (zend_hash_find(EG(function_table), ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME), (void **) &fptr) == SUCCESS) {
			array_init(return_value);
			add_next_index_stringl(return_value, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)-1, 1);
			return;
		}
		RETURN_FALSE;
	}

	zend_hash_find(EG(function_table), "spl_autoload_call", sizeof("spl_autoload_call"), (void **) &fptr);

	if (EG(autoload_func) == fptr) {
		array_init(return_value);
		zend_hash_internal_pointer_reset_ex(SPL_G(autoload_functions), &function_pos);
		while(zend_hash_has_more_elements_ex(SPL_G(autoload_functions), &function_pos) == SUCCESS) {
			zend_hash_get_current_data_ex(SPL_G(autoload_functions), (void **) &alfi, &function_pos);
			if (alfi->closure) {
				Z_ADDREF_P(alfi->closure);
				add_next_index_zval(return_value, alfi->closure);
			} else if (alfi->func_ptr->common.scope) {
				zval *tmp;
				MAKE_STD_ZVAL(tmp);
				array_init(tmp);

				if (alfi->obj) {
					Z_ADDREF_P(alfi->obj);
					add_next_index_zval(tmp, alfi->obj);
				} else {
					add_next_index_string(tmp, alfi->ce->name, 1);
				}
				add_next_index_string(tmp, alfi->func_ptr->common.function_name, 1);
				add_next_index_zval(return_value, tmp);
			} else {
				if (strncmp(alfi->func_ptr->common.function_name, "__lambda_func", sizeof("__lambda_func") - 1)) {
					add_next_index_string(return_value, alfi->func_ptr->common.function_name, 1);
				} else {
				   char *key;
				   uint len;
				   long dummy;
				   zend_hash_get_current_key_ex(SPL_G(autoload_functions), &key, &len, &dummy, 0, &function_pos);
				   add_next_index_stringl(return_value, key, len - 1, 1);
				}
			}

			zend_hash_move_forward_ex(SPL_G(autoload_functions), &function_pos);
		}
		return;
	}

	array_init(return_value);
	add_next_index_string(return_value, EG(autoload_func)->common.function_name, 1);


 Register given function as __autoload() implementation */
PHP_FUNCTION(spl_autoload_register)
{
	char *func_name, *error = NULL;
	int  func_name_len;
	char *lc_name = NULL;
	zval *zcallable = NULL;
	zend_bool do_throw = 1;
	zend_bool prepend  = 0;
	zend_function *spl_func_ptr;
	autoload_func_info alfi;
	zval *obj_ptr;
	zend_fcall_info_cache fcc;

	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "|zbb", &zcallable, &do_throw, &prepend) == FAILURE) {
		return;
	}

	if (ZEND_NUM_ARGS()) {
		if (Z_TYPE_P(zcallable) == IS_STRING) {
			if (Z_STRLEN_P(zcallable) == sizeof("spl_autoload_call") - 1) {
				if (!zend_binary_strcasecmp(Z_STRVAL_P(zcallable), sizeof("spl_autoload_call"), "spl_autoload_call", sizeof("spl_autoload_call"))) {
					if (do_throw) {
						zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Function spl_autoload_call() cannot be registered");
					}
					RETURN_FALSE;
				}
			}
		}

		if (!zend_is_callable_ex(zcallable, NULL, IS_CALLABLE_STRICT, &func_name, &func_name_len, &fcc, &error TSRMLS_CC)) {
			alfi.ce = fcc.calling_scope;
			alfi.func_ptr = fcc.function_handler;
			obj_ptr = fcc.object_ptr;
			if (Z_TYPE_P(zcallable) == IS_ARRAY) {
				if (!obj_ptr && alfi.func_ptr && !(alfi.func_ptr->common.fn_flags & ZEND_ACC_STATIC)) {
					if (do_throw) {
						zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Passed array specifies a non static method but no object (%s)", error);
					}
					if (error) {
						efree(error);
					}
					efree(func_name);
					RETURN_FALSE;
				}
				else if (do_throw) {
					zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Passed array does not specify %s %smethod (%s)", alfi.func_ptr ? "a callable" : "an existing", !obj_ptr ? "static " : "", error);
				}
				if (error) {
					efree(error);
				}
				efree(func_name);
				RETURN_FALSE;
			} else if (Z_TYPE_P(zcallable) == IS_STRING) {
				if (do_throw) {
					zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Function '%s' not %s (%s)", func_name, alfi.func_ptr ? "callable" : "found", error);
				}
				if (error) {
					efree(error);
				}
				efree(func_name);
				RETURN_FALSE;
			} else {
				if (do_throw) {
					zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Illegal value passed (%s)", error);
				}
				if (error) {
					efree(error);
				}
				efree(func_name);
				RETURN_FALSE;
			}
		}
		alfi.closure = NULL;
		alfi.ce = fcc.calling_scope;
		alfi.func_ptr = fcc.function_handler;
		obj_ptr = fcc.object_ptr;
		if (error) {
			efree(error);
		}

		lc_name = safe_emalloc(func_name_len, 1, sizeof(long) + 1);
		zend_str_tolower_copy(lc_name, func_name, func_name_len);
		efree(func_name);

		if (Z_TYPE_P(zcallable) == IS_OBJECT) {
			alfi.closure = zcallable;
			Z_ADDREF_P(zcallable);

			lc_name = erealloc(lc_name, func_name_len + 2 + sizeof(zend_object_handle));
			memcpy(lc_name + func_name_len, &Z_OBJ_HANDLE_P(zcallable),
				sizeof(zend_object_handle));
			func_name_len += sizeof(zend_object_handle);
			lc_name[func_name_len] = '\0';
		}

		if (SPL_G(autoload_functions) && zend_hash_exists(SPL_G(autoload_functions), (char*)lc_name, func_name_len+1)) {
			if (alfi.closure) {
				Z_DELREF_P(zcallable);
			}
			goto skip;
		}

		if (obj_ptr && !(alfi.func_ptr->common.fn_flags & ZEND_ACC_STATIC)) {
			/* add object id to the hash to ensure uniqueness, for more reference look at bug #40091 */
			lc_name = erealloc(lc_name, func_name_len + 2 + sizeof(zend_object_handle));
			memcpy(lc_name + func_name_len, &Z_OBJ_HANDLE_P(obj_ptr), sizeof(zend_object_handle));
			func_name_len += sizeof(zend_object_handle);
			lc_name[func_name_len] = '\0';
			alfi.obj = obj_ptr;
			Z_ADDREF_P(alfi.obj);
		} else {
			alfi.obj = NULL;
		}

		if (!SPL_G(autoload_functions)) {
			ALLOC_HASHTABLE(SPL_G(autoload_functions));
			zend_hash_init(SPL_G(autoload_functions), 1, NULL, (dtor_func_t) autoload_func_info_dtor, 0);
		}

		zend_hash_find(EG(function_table), "spl_autoload", sizeof("spl_autoload"), (void **) &spl_func_ptr);

		if (EG(autoload_func) == spl_func_ptr) { /* registered already, so we insert that first */
			autoload_func_info spl_alfi;

			spl_alfi.func_ptr = spl_func_ptr;
			spl_alfi.obj = NULL;
			spl_alfi.ce = NULL;
			spl_alfi.closure = NULL;
			zend_hash_add(SPL_G(autoload_functions), "spl_autoload", sizeof("spl_autoload"), &spl_alfi, sizeof(autoload_func_info), NULL);
			if (prepend && SPL_G(autoload_functions)->nNumOfElements > 1) {
				/* Move the newly created element to the head of the hashtable */
				HT_MOVE_TAIL_TO_HEAD(SPL_G(autoload_functions));
			}
		}

		if (zend_hash_add(SPL_G(autoload_functions), lc_name, func_name_len+1, &alfi.func_ptr, sizeof(autoload_func_info), NULL) == FAILURE) {
			if (obj_ptr && !(alfi.func_ptr->common.fn_flags & ZEND_ACC_STATIC)) {
				Z_DELREF_P(alfi.obj);
			}
			if (alfi.closure) {
				Z_DELREF_P(alfi.closure);
			}
		}
		if (prepend && SPL_G(autoload_functions)->nNumOfElements > 1) {
			/* Move the newly created element to the head of the hashtable */
			HT_MOVE_TAIL_TO_HEAD(SPL_G(autoload_functions));
		}
skip:
		efree(lc_name);
	}

	if (SPL_G(autoload_functions)) {
		zend_hash_find(EG(function_table), "spl_autoload_call", sizeof("spl_autoload_call"), (void **) &EG(autoload_func));
	} else {
		zend_hash_find(EG(function_table), "spl_autoload", sizeof("spl_autoload"), (void **) &EG(autoload_func));
	}
	RETURN_TRUE;


static struct gfxinfo *php_handle_xbm(php_stream * stream TSRMLS_DC)
{
	struct gfxinfo *result;
	php_get_xbm(stream, &result TSRMLS_CC);
	return result;
}


static unsigned int php_read4(php_stream * stream TSRMLS_DC)
{
	unsigned char a[4];

	/* just return 0 if we hit the end-of-file */
	if ((php_stream_read(stream, a, sizeof(a))) != sizeof(a)) return 0;

	return (((unsigned int)a[0]) << 24)
	     + (((unsigned int)a[1]) << 16)
	     + (((unsigned int)a[2]) <<  8)
	     + (((unsigned int)a[3]));
}


ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file,
                   bool force_full_retrieve)
{
  int count, orig_lp;
  wgint restval, len = 0, qtyread = 0;
  char *tms, *locf;
  const char *tmrate = NULL;
  uerr_t err;
  struct_stat st;

  /* Declare WARC variables. */
  bool warc_enabled = (opt.warc_filename != NULL);
  FILE *warc_tmp = NULL;
  ip_address *warc_ip = NULL;
  wgint last_expected_bytes = 0;

  /* Get the target, and set the name for the message accordingly. */
  if ((f == NULL) && (con->target))
    {
      /* Explicit file (like ".listing"). */
      locf = con->target;
    }
  else
    {
      /* URL-derived file.  Consider "-O file" name. */
      xfree (con->target);
      con->target = url_file_name (u, NULL);
      if (!opt.output_document)
        locf = con->target;
      else
        locf = opt.output_document;
    }

  /* If the output_document was given, then this check was already done and
     the file didn't exist. Hence the !opt.output_document */

  /* If we receive .listing file it is necessary to determine system type of the ftp
     server even if opn.noclobber is given. Thus we must ignore opt.noclobber in
     order to establish connection with the server and get system type. */
  if (opt.noclobber && !opt.output_document && file_exists_p (con->target)
      && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR)))
    {
      logprintf (LOG_VERBOSE,
                 _("File %s already there; not retrieving.\n"), quote (con->target));
      /* If the file is there, we suppose it's retrieved OK.  */
      return RETROK;
    }

  /* Remove it if it's a link.  */
  remove_link (con->target);

  count = 0;

  if (con->st & ON_YOUR_OWN)
    con->st = ON_YOUR_OWN;

  orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0;

  /* THE loop.  */
  do
    {
      /* Increment the pass counter.  */
      ++count;
      sleep_between_retrievals (count);
      if (con->st & ON_YOUR_OWN)
        {
          con->cmd = 0;
          con->cmd |= (DO_RETR | LEAVE_PENDING);
          if (con->csock != -1)
            con->cmd &= ~ (DO_LOGIN | DO_CWD);
          else
            con->cmd |= (DO_LOGIN | DO_CWD);
        }
      else /* not on your own */
        {
          if (con->csock != -1)
            con->cmd &= ~DO_LOGIN;
          else
            con->cmd |= DO_LOGIN;
          if (con->st & DONE_CWD)
            con->cmd &= ~DO_CWD;
          else
            con->cmd |= DO_CWD;
        }

      /* For file RETR requests, we can write a WARC record.
         We record the file contents to a temporary file. */
      if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL)
        {
          warc_tmp = warc_tempfile ();
          if (warc_tmp == NULL)
            return WARC_TMP_FOPENERR;

          if (!con->proxy && con->csock != -1)
            {
              warc_ip = (ip_address *) alloca (sizeof (ip_address));
              socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER);
            }
        }

      /* Decide whether or not to restart.  */
      if (con->cmd & DO_LIST)
        restval = 0;
      else if (force_full_retrieve)
        restval = 0;
      else if (opt.start_pos >= 0)
        restval = opt.start_pos;
      else if (opt.always_rest
          && stat (locf, &st) == 0
          && S_ISREG (st.st_mode))
        /* When -c is used, continue from on-disk size.  (Can't use
           hstat.len even if count>1 because we don't want a failed
           first attempt to clobber existing data.)  */
        restval = st.st_size;
      else if (count > 1)
        restval = qtyread;          /* start where the previous run left off */
      else
        restval = 0;

      /* Get the current time string.  */
      tms = datetime_str (time (NULL));
      /* Print fetch message, if opt.verbose.  */
      if (opt.verbose)
        {
          char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD);
          char tmp[256];
          strcpy (tmp, "        ");
          if (count > 1)
            sprintf (tmp, _("(try:%2d)"), count);
          logprintf (LOG_VERBOSE, "--%s--  %s\n  %s => %s\n",
                     tms, hurl, tmp, quote (locf));
#ifdef WINDOWS
          ws_changetitle (hurl);
#endif
          xfree (hurl);
        }
      /* Send getftp the proper length, if fileinfo was provided.  */
      if (f && f->type != FT_SYMLINK)
        len = f->size;
      else
        len = 0;

      /* If we are working on a WARC record, getftp should also write
         to the warc_tmp file. */
      err = getftp (u, len, &qtyread, restval, con, count, &last_expected_bytes,
                    warc_tmp);

      if (con->csock == -1)
        con->st &= ~DONE_CWD;
      else
        con->st |= DONE_CWD;

      switch (err)
        {
        case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR:
        case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case CONTNOTSUPPORTED:
        case UNLINKERR: case WARC_TMP_FWRITEERR:
          /* Fatal errors, give up.  */
          if (warc_tmp != NULL)
              fclose (warc_tmp);
          return err;
        case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR:
        case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR:
        case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV:
        case FOPEN_EXCL_ERR:
          printwhat (count, opt.ntry);
          /* non-fatal errors */
          if (err == FOPEN_EXCL_ERR)
            {
              /* Re-determine the file name. */
              xfree (con->target);
              con->target = url_file_name (u, NULL);
              locf = con->target;
            }
          continue;
        case FTPRETRINT:
          /* If the control connection was closed, the retrieval
             will be considered OK if f->size == len.  */
          if (!f || qtyread != f->size)
            {
              printwhat (count, opt.ntry);
              continue;
            }
          break;
        case RETRFINISHED:
          /* Great!  */
          break;
        default:
          /* Not as great.  */
          abort ();
        }
      tms = datetime_str (time (NULL));
      if (!opt.spider)
        tmrate = retr_rate (qtyread - restval, con->dltime);

      /* If we get out of the switch above without continue'ing, we've
         successfully downloaded a file.  Remember this fact. */
      downloaded_file (FILE_DOWNLOADED_NORMALLY, locf);

      if (con->st & ON_YOUR_OWN)
        {
          fd_close (con->csock);
          con->csock = -1;
        }
      if (!opt.spider)
        {
          bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document));

          logprintf (LOG_VERBOSE,
                     write_to_stdout
                     ? _("%s (%s) - written to stdout %s[%s]\n\n")
                     : _("%s (%s) - %s saved [%s]\n\n"),
                     tms, tmrate,
                     write_to_stdout ? "" : quote (locf),
                     number_to_static_string (qtyread));
        }
      if (!opt.verbose && !opt.quiet)
        {
          /* Need to hide the password from the URL.  The `if' is here
             so that we don't do the needless allocation every
             time. */
          char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD);
          logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n",
                     tms, hurl, number_to_static_string (qtyread), locf, count);
          xfree (hurl);
        }

      if (warc_enabled && (con->cmd & DO_RETR))
        {
          /* Create and store a WARC resource record for the retrieved file. */
          bool warc_res;

          warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL,
                                                  warc_ip, NULL, warc_tmp, -1);

          if (! warc_res)
            return WARC_ERR;

          /* warc_write_resource_record has also closed warc_tmp. */
          warc_tmp = NULL;
        }

      if (con->cmd & DO_LIST)
        /* This is a directory listing file. */
        {
          if (!opt.remove_listing)
            /* --dont-remove-listing was specified, so do count this towards the
               number of bytes and files downloaded. */
            {
              total_downloaded_bytes += qtyread;
              numurls++;
            }

          /* Deletion of listing files is not controlled by --delete-after, but
             by the more specific option --dont-remove-listing, and the code
             to do this deletion is in another function. */
        }
      else if (!opt.spider)
        /* This is not a directory listing file. */
        {
          /* Unlike directory listing files, don't pretend normal files weren't
             downloaded if they're going to be deleted.  People seeding proxies,
             for instance, may want to know how many bytes and files they've
             downloaded through it. */
          total_downloaded_bytes += qtyread;
          numurls++;

          if (opt.delete_after && !input_file_url (opt.input_filename))
            {
              DEBUGP (("\
Removing file due to --delete-after in ftp_loop_internal():\n"));
              logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf);
              if (unlink (locf))
                logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
            }
        }

      /* Restore the original leave-pendingness.  */
      if (orig_lp)
        con->cmd |= LEAVE_PENDING;
      else
        con->cmd &= ~LEAVE_PENDING;

      if (local_file)
        *local_file = xstrdup (locf);

      if (warc_tmp != NULL)
        fclose (warc_tmp);

      return RETROK;
    } while (!opt.ntry || (count < opt.ntry));

  if (con->csock != -1 && (con->st & ON_YOUR_OWN))
    {
      fd_close (con->csock);
      con->csock = -1;
    }

  if (warc_tmp != NULL)
    fclose (warc_tmp);

  return TRYLIMEXC;
}


void pcnet_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
{
    PCNetState *s = opaque;
    pcnet_poll_timer(s);
#ifdef PCNET_DEBUG_IO
    printf("pcnet_ioport_writew addr=0x%08x val=0x%04x\n", addr, val);
#endif
    if (!BCR_DWIO(s)) {
        switch (addr & 0x0f) {
        case 0x00: /* RDP */
            pcnet_csr_writew(s, s->rap, val);
            break;
        case 0x02:
            s->rap = val & 0x7f;
            break;
        case 0x06:
            pcnet_bcr_writew(s, s->rap, val);
            break;
        }
    }
    pcnet_update_irq(s);
}


static void free_buffer(guchar *pixels, gpointer data)
{
	g_free(pixels);
}


static void write_rle_data(TGAContext *ctx, const TGAColor *color, guint *rle_count)
{
	for (; *rle_count; (*rle_count)--) {
		g_memmove(ctx->pptr, (guchar *) color, ctx->pbuf->n_channels);
		ctx->pptr += ctx->pbuf->n_channels;
		ctx->pbuf_bytes_done += ctx->pbuf->n_channels;
		if (ctx->pbuf_bytes_done == ctx->pbuf_bytes)
			return;
	}
}


OPJ_BOOL opj_j2k_write_com(     opj_j2k_t *p_j2k,
                                                        opj_stream_private_t *p_stream,
                                                        opj_event_mgr_t * p_manager
                            )
{
        OPJ_UINT32 l_comment_size;
        OPJ_UINT32 l_total_com_size;
        const OPJ_CHAR *l_comment;
        OPJ_BYTE * l_current_ptr = 00;

        /* preconditions */
        assert(p_j2k != 00);
        assert(p_stream != 00);
        assert(p_manager != 00);

        l_comment = p_j2k->m_cp.comment;
        l_comment_size = (OPJ_UINT32)strlen(l_comment);
        l_total_com_size = l_comment_size + 6;

        if (l_total_com_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
                OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
                if (! new_header_tile_data) {
                        opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
                        p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
                        p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write the COM marker\n");
                        return OPJ_FALSE;
                }
                p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
                p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
        }

        l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;

        opj_write_bytes(l_current_ptr,J2K_MS_COM , 2);  /* COM */
        l_current_ptr+=2;

        opj_write_bytes(l_current_ptr,l_total_com_size - 2 , 2);        /* L_COM */
        l_current_ptr+=2;

        opj_write_bytes(l_current_ptr,1 , 2);   /* General use (IS 8859-15:1999 (Latin) values) */
        l_current_ptr+=2;

        memcpy( l_current_ptr,l_comment,l_comment_size);

        if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_total_com_size,p_manager) != l_total_com_size) {
                return OPJ_FALSE;
        }

        return OPJ_TRUE;
}


OPJ_BOOL opj_j2k_encoding_validation (  opj_j2k_t * p_j2k,
                                                                            opj_stream_private_t *p_stream,
                                                                            opj_event_mgr_t * p_manager )
{
        OPJ_BOOL l_is_valid = OPJ_TRUE;

        /* preconditions */
        assert(p_j2k != 00);
        assert(p_stream != 00);
        assert(p_manager != 00);

        /* STATE checking */
        /* make sure the state is at 0 */
        l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);

        /* POINTER validation */
        /* make sure a p_j2k codec is present */
        l_is_valid &= (p_j2k->m_procedure_list != 00);
        /* make sure a validation list is present */
        l_is_valid &= (p_j2k->m_validation_list != 00);

        /* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
        /* 33 (32) would always fail the check below (if a cast to 64bits was done) */
        /* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
        if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) || (p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
                opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
                return OPJ_FALSE;
        }

        if ((p_j2k->m_cp.tdx) < (OPJ_UINT32) (1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
                opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
                return OPJ_FALSE;
        }

        if ((p_j2k->m_cp.tdy) < (OPJ_UINT32) (1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
                opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
                return OPJ_FALSE;
        }

        /* PARAMETER VALIDATION */
        return l_is_valid;
}


void opj_j2k_write_poc_in_memory(   opj_j2k_t *p_j2k,
                                                                OPJ_BYTE * p_data,
                                                                OPJ_UINT32 * p_data_written,
                                                                opj_event_mgr_t * p_manager
                                    )
{
        OPJ_UINT32 i;
        OPJ_BYTE * l_current_data = 00;
        OPJ_UINT32 l_nb_comp;
        OPJ_UINT32 l_nb_poc;
        OPJ_UINT32 l_poc_size;
        opj_image_t *l_image = 00;
        opj_tcp_t *l_tcp = 00;
        opj_tccp_t *l_tccp = 00;
        opj_poc_t *l_current_poc = 00;
        OPJ_UINT32 l_poc_room;

        /* preconditions */
        assert(p_j2k != 00);
        assert(p_manager != 00);

        l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
        l_tccp = &l_tcp->tccps[0];
        l_image = p_j2k->m_private_image;
        l_nb_comp = l_image->numcomps;
        l_nb_poc = 1 + l_tcp->numpocs;

        if (l_nb_comp <= 256) {
                l_poc_room = 1;
        }
        else {
                l_poc_room = 2;
        }

        l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;

        l_current_data = p_data;

        opj_write_bytes(l_current_data,J2K_MS_POC,2);                                   /* POC  */
        l_current_data += 2;

        opj_write_bytes(l_current_data,l_poc_size-2,2);                                 /* Lpoc */
        l_current_data += 2;

        l_current_poc =  l_tcp->pocs;
        for (i = 0; i < l_nb_poc; ++i) {
                opj_write_bytes(l_current_data,l_current_poc->resno0,1);                                /* RSpoc_i */
                ++l_current_data;

                opj_write_bytes(l_current_data,l_current_poc->compno0,l_poc_room);              /* CSpoc_i */
                l_current_data+=l_poc_room;

                opj_write_bytes(l_current_data,l_current_poc->layno1,2);                                /* LYEpoc_i */
                l_current_data+=2;

                opj_write_bytes(l_current_data,l_current_poc->resno1,1);                                /* REpoc_i */
                ++l_current_data;

                opj_write_bytes(l_current_data,l_current_poc->compno1,l_poc_room);              /* CEpoc_i */
                l_current_data+=l_poc_room;

                opj_write_bytes(l_current_data,l_current_poc->prg,1);                                   /* Ppoc_i */
                ++l_current_data;

                /* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
                l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
                l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
                l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->compno1, (OPJ_INT32)l_nb_comp);

                ++l_current_poc;
        }

        *p_data_written = l_poc_size;
}


void opj_j2k_update_tlm (opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size )
{
        opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,p_j2k->m_current_tile_number,1);            /* PSOT */
        ++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;

        opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,p_tile_part_size,4);                                        /* PSOT */
        p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}


OPJ_BOOL opj_j2k_read_mcc (     opj_j2k_t *p_j2k,
                                                OPJ_BYTE * p_header_data,
                                                OPJ_UINT32 p_header_size,
                                                opj_event_mgr_t * p_manager )
{
        OPJ_UINT32 i,j;
        OPJ_UINT32 l_tmp;
        OPJ_UINT32 l_indix;
        opj_tcp_t * l_tcp;
        opj_simple_mcc_decorrelation_data_t * l_mcc_record;
        opj_mct_data_t * l_mct_data;
        OPJ_UINT32 l_nb_collections;
        OPJ_UINT32 l_nb_comps;
        OPJ_UINT32 l_nb_bytes_by_comp;

        /* preconditions */
        assert(p_header_data != 00);
        assert(p_j2k != 00);
        assert(p_manager != 00);

        l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
                        &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
                        p_j2k->m_specific_param.m_decoder.m_default_tcp;

        if (p_header_size < 2) {
                opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                return OPJ_FALSE;
        }

        /* first marker */
        opj_read_bytes(p_header_data,&l_tmp,2);                         /* Zmcc */
        p_header_data += 2;
        if (l_tmp != 0) {
                opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n");
                return OPJ_TRUE;
        }

        if (p_header_size < 7) {
                opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                return OPJ_FALSE;
        }

        opj_read_bytes(p_header_data,&l_indix,1); /* Imcc -> no need for other values, take the first */
        ++p_header_data;

        l_mcc_record = l_tcp->m_mcc_records;

        for(i=0;i<l_tcp->m_nb_mcc_records;++i) {
                if (l_mcc_record->m_index == l_indix) {
                        break;
                }
                ++l_mcc_record;
        }

        /** NOT FOUND */
        if (i == l_tcp->m_nb_mcc_records) {
                if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
                        opj_simple_mcc_decorrelation_data_t *new_mcc_records;
                        l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;

                        new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
                                        l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(opj_simple_mcc_decorrelation_data_t));
                        if (! new_mcc_records) {
                                opj_free(l_tcp->m_mcc_records);
                                l_tcp->m_mcc_records = NULL;
                                l_tcp->m_nb_max_mcc_records = 0;
                                l_tcp->m_nb_mcc_records = 0;
                                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
                                return OPJ_FALSE;
                        }
                        l_tcp->m_mcc_records = new_mcc_records;
                        l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
                        memset(l_mcc_record,0,(l_tcp->m_nb_max_mcc_records-l_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t));
                }
                l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
        }
        l_mcc_record->m_index = l_indix;

        /* only one marker atm */
        opj_read_bytes(p_header_data,&l_tmp,2);                         /* Ymcc */
        p_header_data+=2;
        if (l_tmp != 0) {
                opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n");
                return OPJ_TRUE;
        }

        opj_read_bytes(p_header_data,&l_nb_collections,2);                              /* Qmcc -> number of collections -> 1 */
        p_header_data+=2;

        if (l_nb_collections > 1) {
                opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple collections\n");
                return OPJ_TRUE;
        }

        p_header_size -= 7;

        for (i=0;i<l_nb_collections;++i) {
                if (p_header_size < 3) {
                        opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                        return OPJ_FALSE;
                }

                opj_read_bytes(p_header_data,&l_tmp,1); /* Xmcci type of component transformation -> array based decorrelation */
                ++p_header_data;

                if (l_tmp != 1) {
                        opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections other than array decorrelation\n");
                        return OPJ_TRUE;
                }

                opj_read_bytes(p_header_data,&l_nb_comps,2);

                p_header_data+=2;
                p_header_size-=3;

                l_nb_bytes_by_comp = 1 + (l_nb_comps>>15);
                l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;

                if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
                        opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                        return OPJ_FALSE;
                }

                p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);

                for (j=0;j<l_mcc_record->m_nb_comps;++j) {
                        opj_read_bytes(p_header_data,&l_tmp,l_nb_bytes_by_comp);        /* Cmccij Component offset*/
                        p_header_data+=l_nb_bytes_by_comp;

                        if (l_tmp != j) {
                                opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n");
                                return OPJ_TRUE;
                        }
                }

                opj_read_bytes(p_header_data,&l_nb_comps,2);
                p_header_data+=2;

                l_nb_bytes_by_comp = 1 + (l_nb_comps>>15);
                l_nb_comps &= 0x7fff;

                if (l_nb_comps != l_mcc_record->m_nb_comps) {
                        opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections without same number of indixes\n");
                        return OPJ_TRUE;
                }

                if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
                        opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                        return OPJ_FALSE;
                }

                p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);

                for (j=0;j<l_mcc_record->m_nb_comps;++j) {
                        opj_read_bytes(p_header_data,&l_tmp,l_nb_bytes_by_comp);        /* Wmccij Component offset*/
                        p_header_data+=l_nb_bytes_by_comp;

                        if (l_tmp != j) {
                                opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n");
                                return OPJ_TRUE;
                        }
                }

                opj_read_bytes(p_header_data,&l_tmp,3); /* Wmccij Component offset*/
                p_header_data += 3;

                l_mcc_record->m_is_irreversible = ! ((l_tmp>>16) & 1);
                l_mcc_record->m_decorrelation_array = 00;
                l_mcc_record->m_offset_array = 00;

                l_indix = l_tmp & 0xff;
                if (l_indix != 0) {
                        l_mct_data = l_tcp->m_mct_records;
                        for (j=0;j<l_tcp->m_nb_mct_records;++j) {
                                if (l_mct_data->m_index == l_indix) {
                                        l_mcc_record->m_decorrelation_array = l_mct_data;
                                        break;
                                }
                                ++l_mct_data;
                        }

                        if (l_mcc_record->m_decorrelation_array == 00) {
                                opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                                return OPJ_FALSE;
                        }
                }

                l_indix = (l_tmp >> 8) & 0xff;
                if (l_indix != 0) {
                        l_mct_data = l_tcp->m_mct_records;
                        for (j=0;j<l_tcp->m_nb_mct_records;++j) {
                                if (l_mct_data->m_index == l_indix) {
                                        l_mcc_record->m_offset_array = l_mct_data;
                                        break;
                                }
                                ++l_mct_data;
                        }

                        if (l_mcc_record->m_offset_array == 00) {
                                opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                                return OPJ_FALSE;
                        }
                }
        }

        if (p_header_size != 0) {
                opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
                return OPJ_FALSE;
        }

        ++l_tcp->m_nb_mcc_records;

        return OPJ_TRUE;
}


OPJ_BOOL opj_j2k_update_image_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image)
{
        OPJ_UINT32 i,j,k = 0;
        OPJ_UINT32 l_width_src,l_height_src;
        OPJ_UINT32 l_width_dest,l_height_dest;
        OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
        OPJ_INT32 l_start_offset_src, l_line_offset_src, l_end_offset_src ;
        OPJ_UINT32 l_start_x_dest , l_start_y_dest;
        OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
        OPJ_INT32 l_start_offset_dest, l_line_offset_dest;

        opj_image_comp_t * l_img_comp_src = 00;
        opj_image_comp_t * l_img_comp_dest = 00;

        opj_tcd_tilecomp_t * l_tilec = 00;
        opj_image_t * l_image_src = 00;
        OPJ_UINT32 l_size_comp, l_remaining;
        OPJ_INT32 * l_dest_ptr;
        opj_tcd_resolution_t* l_res= 00;

        l_tilec = p_tcd->tcd_image->tiles->comps;
        l_image_src = p_tcd->image;
        l_img_comp_src = l_image_src->comps;

        l_img_comp_dest = p_output_image->comps;

        for (i=0; i<l_image_src->numcomps; i++) {

                /* Allocate output component buffer if necessary */
                if (!l_img_comp_dest->data) {

                        l_img_comp_dest->data = (OPJ_INT32*) opj_calloc(l_img_comp_dest->w * l_img_comp_dest->h, sizeof(OPJ_INT32));
                        if (! l_img_comp_dest->data) {
                                return OPJ_FALSE;
                        }
                }

                /* Copy info from decoded comp image to output image */
                l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;

                /*-----*/
                /* Compute the precision of the output buffer */
                l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
                l_remaining = l_img_comp_src->prec & 7;  /* (%8) */
                l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;

                if (l_remaining) {
                        ++l_size_comp;
                }

                if (l_size_comp == 3) {
                        l_size_comp = 4;
                }
                /*-----*/

                /* Current tile component size*/
                /*if (i == 0) {
                fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
                                l_res->x0, l_res->x1, l_res->y0, l_res->y1);
                }*/

                l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
                l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);

                /* Border of the current output component*/
                l_x0_dest = (OPJ_UINT32)opj_int_ceildivpow2((OPJ_INT32)l_img_comp_dest->x0, (OPJ_INT32)l_img_comp_dest->factor);
                l_y0_dest = (OPJ_UINT32)opj_int_ceildivpow2((OPJ_INT32)l_img_comp_dest->y0, (OPJ_INT32)l_img_comp_dest->factor);
                l_x1_dest = l_x0_dest + l_img_comp_dest->w;
                l_y1_dest = l_y0_dest + l_img_comp_dest->h;

                /*if (i == 0) {
                fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
                                l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
                }*/

                /*-----*/
                /* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
                 * of the input buffer (decoded tile component) which will be move
                 * in the output buffer. Compute the area of the output buffer (l_start_x_dest,
                 * l_start_y_dest, l_width_dest, l_height_dest)  which will be modified
                 * by this input area.
                 * */
                assert( l_res->x0 >= 0);
                assert( l_res->x1 >= 0);
                if ( l_x0_dest < (OPJ_UINT32)l_res->x0 ) {
                        l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
                        l_offset_x0_src = 0;

                        if ( l_x1_dest >= (OPJ_UINT32)l_res->x1 ) {
                                l_width_dest = l_width_src;
                                l_offset_x1_src = 0;
                        }
                        else {
                                l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
                                l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
                        }
                }
                else {
                        l_start_x_dest = 0 ;
                        l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;

                        if ( l_x1_dest >= (OPJ_UINT32)l_res->x1 ) {
                                l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
                                l_offset_x1_src = 0;
                        }
                        else {
                                l_width_dest = l_img_comp_dest->w ;
                                l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
                        }
                }

                if ( l_y0_dest < (OPJ_UINT32)l_res->y0 ) {
                        l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
                        l_offset_y0_src = 0;

                        if ( l_y1_dest >= (OPJ_UINT32)l_res->y1 ) {
                                l_height_dest = l_height_src;
                                l_offset_y1_src = 0;
                        }
                        else {
                                l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
                                l_offset_y1_src =  (OPJ_INT32)(l_height_src - l_height_dest);
                        }
                }
                else {
                        l_start_y_dest = 0 ;
                        l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;

                        if ( l_y1_dest >= (OPJ_UINT32)l_res->y1 ) {
                                l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
                                l_offset_y1_src = 0;
                        }
                        else {
                                l_height_dest = l_img_comp_dest->h ;
                                l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
                        }
                }

                if( (l_offset_x0_src < 0 ) || (l_offset_y0_src < 0 ) || (l_offset_x1_src < 0 ) || (l_offset_y1_src < 0 ) ){
                        return OPJ_FALSE;
                }
                /* testcase 2977.pdf.asan.67.2198 */
                if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
                        return OPJ_FALSE;
                }
                /*-----*/

                /* Compute the input buffer offset */
                l_start_offset_src = l_offset_x0_src + l_offset_y0_src * (OPJ_INT32)l_width_src;
                l_line_offset_src = l_offset_x1_src + l_offset_x0_src;
                l_end_offset_src = l_offset_y1_src * (OPJ_INT32)l_width_src - l_offset_x0_src;

                /* Compute the output buffer offset */
                l_start_offset_dest = (OPJ_INT32)(l_start_x_dest + l_start_y_dest * l_img_comp_dest->w);
                l_line_offset_dest = (OPJ_INT32)(l_img_comp_dest->w - l_width_dest);

                /* Move the output buffer to the first place where we will write*/
                l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;

                /*if (i == 0) {
                        fprintf(stdout, "COMPO[%d]:\n",i);
                        fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
                                        "\t tile offset:%d, %d, %d, %d\n"
                                        "\t buffer offset: %d; %d, %d\n",
                                        l_res->x0, l_res->y0, l_width_src, l_height_src,
                                        l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
                                        l_start_offset_src, l_line_offset_src, l_end_offset_src);

                        fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
                                        "\t start offset: %d, line offset= %d\n",
                                        l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
                }*/

                switch (l_size_comp) {
                        case 1:
                                {
                                        OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
                                        l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/

                                        if (l_img_comp_src->sgnd) {
                                                for (j = 0 ; j < l_height_dest ; ++j) {
                                                        for ( k = 0 ; k < l_width_dest ; ++k) {
                                                                *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); /* Copy only the data needed for the output image */
                                                        }

                                                        l_dest_ptr+= l_line_offset_dest; /* Move to the next place where we will write */
                                                        l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
                                                }
                                        }
                                        else {
                                                for ( j = 0 ; j < l_height_dest ; ++j ) {
                                                        for ( k = 0 ; k < l_width_dest ; ++k) {
                                                                *(l_dest_ptr++) = (OPJ_INT32) ((*(l_src_ptr++))&0xff);
                                                        }

                                                        l_dest_ptr+= l_line_offset_dest;
                                                        l_src_ptr += l_line_offset_src;
                                                }
                                        }

                                        l_src_ptr += l_end_offset_src; /* Move to the end of this component-part of the input buffer */
                                        p_data = (OPJ_BYTE*) l_src_ptr; /* Keep the current position for the next component-part */
                                }
                                break;
                        case 2:
                                {
                                        OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
                                        l_src_ptr += l_start_offset_src;

                                        if (l_img_comp_src->sgnd) {
                                                for (j=0;j<l_height_dest;++j) {
                                                        for (k=0;k<l_width_dest;++k) {
                                                                *(l_dest_ptr++) = *(l_src_ptr++);
                                                        }

                                                        l_dest_ptr+= l_line_offset_dest;
                                                        l_src_ptr += l_line_offset_src ;
                                                }
                                        }
                                        else {
                                                for (j=0;j<l_height_dest;++j) {
                                                        for (k=0;k<l_width_dest;++k) {
                                                                *(l_dest_ptr++) = (*(l_src_ptr++))&0xffff;
                                                        }

                                                        l_dest_ptr+= l_line_offset_dest;
                                                        l_src_ptr += l_line_offset_src ;
                                                }
                                        }

                                        l_src_ptr += l_end_offset_src;
                                        p_data = (OPJ_BYTE*) l_src_ptr;
                                }
                                break;
                        case 4:
                                {
                                        OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
                                        l_src_ptr += l_start_offset_src;

                                        for (j=0;j<l_height_dest;++j) {
                                                for (k=0;k<l_width_dest;++k) {
                                                        *(l_dest_ptr++) = (*(l_src_ptr++));
                                                }

                                                l_dest_ptr+= l_line_offset_dest;
                                                l_src_ptr += l_line_offset_src ;
                                        }

                                        l_src_ptr += l_end_offset_src;
                                        p_data = (OPJ_BYTE*) l_src_ptr;
                                }
                                break;
                }

                ++l_img_comp_dest;
                ++l_img_comp_src;
                ++l_tilec;
        }

        return OPJ_TRUE;
}


void opj_j2k_write_float_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
        OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
        OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
        OPJ_UINT32 i;
        OPJ_UINT32 l_temp;

        for (i=0;i<p_nb_elem;++i) {
                l_temp = (OPJ_UINT32) *(l_src_data++);

                opj_write_bytes(l_dest_data,l_temp,sizeof(OPJ_INT32));

                l_dest_data+=sizeof(OPJ_INT32);
        }
}


OPJ_BOOL opj_j2k_write_cod(     opj_j2k_t *p_j2k,
                                                        opj_stream_private_t *p_stream,
                                                        opj_event_mgr_t * p_manager )
{
        opj_cp_t *l_cp = 00;
        opj_tcp_t *l_tcp = 00;
        OPJ_UINT32 l_code_size,l_remaining_size;
        OPJ_BYTE * l_current_data = 00;

        /* preconditions */
        assert(p_j2k != 00);
        assert(p_manager != 00);
        assert(p_stream != 00);

        l_cp = &(p_j2k->m_cp);
        l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
        l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,p_j2k->m_current_tile_number,0);
        l_remaining_size = l_code_size;

        if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
                OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
                if (! new_header_tile_data) {
                        opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
                        p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
                        p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
                        return OPJ_FALSE;
                }
                p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
                p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
        }

        l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;

        opj_write_bytes(l_current_data,J2K_MS_COD,2);           /* COD */
        l_current_data += 2;

        opj_write_bytes(l_current_data,l_code_size-2,2);        /* L_COD */
        l_current_data += 2;

        opj_write_bytes(l_current_data,l_tcp->csty,1);          /* Scod */
        ++l_current_data;

        opj_write_bytes(l_current_data,l_tcp->prg,1);           /* SGcod (A) */
        ++l_current_data;

        opj_write_bytes(l_current_data,l_tcp->numlayers,2);     /* SGcod (B) */
        l_current_data+=2;

        opj_write_bytes(l_current_data,l_tcp->mct,1);           /* SGcod (C) */
        ++l_current_data;

        l_remaining_size -= 9;

        if (! opj_j2k_write_SPCod_SPCoc(p_j2k,p_j2k->m_current_tile_number,0,l_current_data,&l_remaining_size,p_manager)) {
                opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
                return OPJ_FALSE;
        }

        if (l_remaining_size != 0) {
                opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
                return OPJ_FALSE;
        }

        if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_code_size,p_manager) != l_code_size) {
                return OPJ_FALSE;
        }

        return OPJ_TRUE;
}


OPJ_BOOL opj_j2k_build_encoder (opj_j2k_t * p_j2k,
                                                        opj_stream_private_t *p_stream,
                                                        opj_event_mgr_t * p_manager )
{
        /* add here initialization of cp
           copy paste of setup_encoder */
  (void)p_j2k;
  (void)p_stream;
  (void)p_manager;
        return OPJ_TRUE;
}


parse_xml (SoupMessage  *msg,
           xmlNodePtr   *root,
           const char   *name,
           GError      **error)
{
 xmlDocPtr  doc;

  if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
    {
      g_set_error (error,
                   G_IO_ERROR,
                   http_error_code_from_status (msg->status_code),
                   _("HTTP Error: %s"), msg->reason_phrase);
      return NULL;
    }

  doc = xmlReadMemory (msg->response_body->data,
                       msg->response_body->length,
                       "response.xml",
                       NULL,
                       XML_PARSE_NONET |
                       XML_PARSE_NOWARNING |
                       XML_PARSE_NOBLANKS |
                       XML_PARSE_NSCLEAN |
                       XML_PARSE_NOCDATA |
                       XML_PARSE_COMPACT);
  if (doc == NULL)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
	                   _("Could not parse response"));
      return NULL;
    }

  *root = xmlDocGetRootElement (doc);

  if (*root == NULL || (*root)->children == NULL)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
	                   _("Empty response"));
      xmlFreeDoc (doc);
      return NULL;
    }

  if (strcmp ((char *) (*root)->name, name))
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           _("Unexpected reply from server"));
      xmlFreeDoc (doc);
      return NULL;
    }

  return doc;
}


g_vfs_backend_dav_finalize (GObject *object)
{
  GVfsBackendDav *dav_backend;

  dav_backend = G_VFS_BACKEND_DAV (object);

#ifdef HAVE_AVAHI
  if (dav_backend->resolver != NULL)
    {
      g_signal_handlers_disconnect_by_func (dav_backend->resolver, dns_sd_resolver_changed, dav_backend);
      g_object_unref (dav_backend->resolver);
    }
#endif

  mount_auth_info_free (&(dav_backend->auth_info));

  if (G_OBJECT_CLASS (g_vfs_backend_dav_parent_class)->finalize)
    (*G_OBJECT_CLASS (g_vfs_backend_dav_parent_class)->finalize) (object);
}


do_enumerate (GVfsBackend           *backend,
              GVfsJobEnumerate      *job,
              const char            *filename,
              GFileAttributeMatcher *matcher,
              GFileQueryInfoFlags    flags)
{
  SoupMessage *msg;
  Multistatus  ms;
  xmlNodeIter  iter;
  gboolean     res;
  GError      *error;

  error = NULL;

  g_debug ("+ do_enumerate: %s\n", filename);

  msg = propfind_request_new (backend, filename, 1, ls_propnames);

  if (msg == NULL)
    {
      g_vfs_job_failed (G_VFS_JOB (job),
                        G_IO_ERROR, G_IO_ERROR_FAILED,
                        _("Could not create request"));

      return;
    }

  message_add_redirect_header (msg, flags);

  g_vfs_backend_dav_send_message (backend, msg);

  res = multistatus_parse (msg, &ms, &error);

  if (res == FALSE)
    {
      g_vfs_job_failed_from_error (G_VFS_JOB (job), error);
      g_error_free (error);
      g_object_unref (msg);
      return;
    }
  g_vfs_job_succeeded (G_VFS_JOB (job));

  multistatus_get_response_iter (&ms, &iter);

  while (xml_node_iter_next (&iter))
    {
      MsResponse  response;
      GFileInfo  *info;

      if (! multistatus_get_response (&iter, &response))
        continue;

      if (response.is_target == FALSE)
	{
	  info = g_file_info_new ();
	  ms_response_to_file_info (&response, info);
	  g_vfs_job_enumerate_add_info (job, info);
          g_object_unref (info);
	}

      ms_response_clear (&response);
    }

  multistatus_free (&ms);
  g_object_unref (msg);

  g_vfs_job_enumerate_done (G_VFS_JOB_ENUMERATE (job));
}


node_has_name (xmlNodePtr node, const char *name)
{
  g_return_val_if_fail (node != NULL, FALSE);

  return ! strcmp ((char *) node->name, name);
}


do_query_info (GVfsBackend           *backend,
               GVfsJobQueryInfo      *job,
               const char            *filename,
               GFileQueryInfoFlags    flags,
               GFileInfo             *info,
               GFileAttributeMatcher *matcher)
{
  SoupMessage *msg;
  Multistatus  ms;
  xmlNodeIter  iter;
  gboolean     res;
  GError      *error;

  error   = NULL;

  g_debug ("Query info %s\n", filename);

  msg = propfind_request_new (backend, filename, 0, ls_propnames);

  if (msg == NULL)
    {
      g_vfs_job_failed (G_VFS_JOB (job),
                        G_IO_ERROR, G_IO_ERROR_FAILED,
                        _("Could not create request"));

      return;
    }

  message_add_redirect_header (msg, flags);

  g_vfs_backend_dav_send_message (backend, msg);

  res = multistatus_parse (msg, &ms, &error);

  if (res == FALSE)
    {
      g_vfs_job_failed_from_error (G_VFS_JOB (job), error);
      g_error_free (error);
      g_object_unref (msg);
      return;
    }

  res = FALSE;
  multistatus_get_response_iter (&ms, &iter);

  while (xml_node_iter_next (&iter))
    {
      MsResponse response;

      if (! multistatus_get_response (&iter, &response))
        continue;

      if (response.is_target)
        {
          ms_response_to_file_info (&response, job->file_info);
          res = TRUE;
        }

      ms_response_clear (&response);
    }

  multistatus_free (&ms);
  g_object_unref (msg);

  if (res)
    g_vfs_job_succeeded (G_VFS_JOB (job));
  else
    g_vfs_job_failed (G_VFS_JOB (job),
                      G_IO_ERROR, G_IO_ERROR_FAILED,
                      _("Response invalid"));

}


dav_uri_encode (const char *path_to_encode)
{
  char *path;
  static const char *allowed_reserved_chars = "/";

  path = g_uri_escape_string (path_to_encode,
                              allowed_reserved_chars,
                              FALSE);

  return path;
}


do_delete (GVfsBackend   *backend,
           GVfsJobDelete *job,
           const char    *filename)
{
  SoupMessage *msg;
  SoupURI     *uri;
  GFileType    file_type;
  gboolean     res;
  guint        num_children;
  guint        status;
  GError      *error;

  error = NULL;

  uri = g_vfs_backend_dav_uri_for_path (backend, filename, FALSE);
  res = stat_location (backend, uri, &file_type, &num_children, &error);

  if (res == FALSE)
    {
      g_vfs_job_failed_from_error (G_VFS_JOB (job), error);
      g_error_free (error);
      return;
    }

  if (file_type == G_FILE_TYPE_DIRECTORY && num_children)
    {
      g_vfs_job_failed (G_VFS_JOB (job),
                        G_IO_ERROR, G_IO_ERROR_NOT_EMPTY,
                        _("Directory not empty"));
      return;
    }

  msg = soup_message_new_from_uri (SOUP_METHOD_DELETE, uri);

  status = g_vfs_backend_dav_send_message (backend, msg);

  if (!SOUP_STATUS_IS_SUCCESSFUL (status))
    http_job_failed (G_VFS_JOB (job), msg);
  else
    g_vfs_job_succeeded (G_VFS_JOB (job));

  soup_uri_free (uri);
  g_object_unref (msg);
}


static ssize_t show_device_bridge(struct device *cd,
				  struct device_attribute *attr, char *buf)
{
	struct video_device *vdev =
		container_of(cd, struct video_device, dev);
	struct usb_usbvision *usbvision = video_get_drvdata(vdev);
	return sprintf(buf, "%d\n", usbvision->bridge_type);
}


static ssize_t show_model(struct device *cd,
			  struct device_attribute *attr, char *buf)
{
	struct video_device *vdev =
		container_of(cd, struct video_device, dev);
	struct usb_usbvision *usbvision = video_get_drvdata(vdev);
	return sprintf(buf, "%s\n",
		       usbvision_device_data[usbvision->dev_model].model_string);
}


static void usbvision_unregister_video(struct usb_usbvision *usbvision)
{
	/* Radio Device: */
	if (video_is_registered(&usbvision->rdev)) {
		PDEBUG(DBG_PROBE, "unregister %s [v4l2]",
		       video_device_node_name(&usbvision->rdev));
		video_unregister_device(&usbvision->rdev);
	}

	/* Video Device: */
	if (video_is_registered(&usbvision->vdev)) {
		PDEBUG(DBG_PROBE, "unregister %s [v4l2]",
		       video_device_node_name(&usbvision->vdev));
		video_unregister_device(&usbvision->vdev);
	}
}


int ssl_write_certificate( ssl_context *ssl )
{
    const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;

    SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );

    if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
        ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_DHE_PSK ||
        ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK )
    {
        SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
        ssl->state++;
        return( 0 );
    }

    SSL_DEBUG_MSG( 1, ( "should never happen" ) );
    return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
}