pack_unpack_internal(VALUE str, VALUE fmt, int mode)
{
#define hexdigits ruby_hexdigits
    char *s, *send;
    char *p, *pend;
    VALUE ary;
    char type;
    long len;
    AVOID_CC_BUG long tmp_len;
    int star;
#ifdef NATINT_PACK
    int natint;			/* native integer */
#endif
    int signed_p, integer_size, bigendian_p;
#define UNPACK_PUSH(item) do {\
	VALUE item_val = (item);\
	if ((mode) == UNPACK_BLOCK) {\
	    rb_yield(item_val);\
	}\
	else if ((mode) == UNPACK_ARRAY) {\
	    rb_ary_push(ary, item_val);\
	}\
	else /* if ((mode) == UNPACK_1) { */ {\
	    return item_val; \
	}\
    } while (0)

    StringValue(str);
    StringValue(fmt);
    s = RSTRING_PTR(str);
    send = s + RSTRING_LEN(str);
    p = RSTRING_PTR(fmt);
    pend = p + RSTRING_LEN(fmt);

    ary = mode == UNPACK_ARRAY ? rb_ary_new() : Qnil;
    while (p < pend) {
	int explicit_endian = 0;
	type = *p++;
#ifdef NATINT_PACK
	natint = 0;
#endif

	if (ISSPACE(type)) continue;
	if (type == '#') {
	    while ((p < pend) && (*p != '\n')) {
		p++;
	    }
	    continue;
	}

	star = 0;
	{
          modifiers:
	    switch (*p) {
	      case '_':
	      case '!':

		if (strchr(natstr, type)) {
#ifdef NATINT_PACK
		    natint = 1;
#endif
		    p++;
		}
		else {
		    rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
		}
		goto modifiers;

	      case '<':
	      case '>':
		if (!strchr(endstr, type)) {
		    rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr);
		}
		if (explicit_endian) {
		    rb_raise(rb_eRangeError, "Can't use both '<' and '>'");
		}
		explicit_endian = *p++;
		goto modifiers;
	    }
	}

	if (p >= pend)
	    len = 1;
	else if (*p == '*') {
	    star = 1;
	    len = send - s;
	    p++;
	}
	else if (ISDIGIT(*p)) {
	    errno = 0;
	    len = STRTOUL(p, (char**)&p, 10);
	    if (len < 0 || errno) {
		rb_raise(rb_eRangeError, "pack length too big");
	    }
	}
	else {
	    len = (type != '@');
	}

	switch (type) {
	  case '%':
	    rb_raise(rb_eArgError, "%% is not supported");
	    break;

	  case 'A':
	    if (len > send - s) len = send - s;
	    {
		long end = len;
		char *t = s + len - 1;

		while (t >= s) {
		    if (*t != ' ' && *t != '\0') break;
		    t--; len--;
		}
		UNPACK_PUSH(infected_str_new(s, len, str));
		s += end;
	    }
	    break;

	  case 'Z':
	    {
		char *t = s;

		if (len > send-s) len = send-s;
		while (t < s+len && *t) t++;
		UNPACK_PUSH(infected_str_new(s, t-s, str));
		if (t < send) t++;
		s = star ? t : s+len;
	    }
	    break;

	  case 'a':
	    if (len > send - s) len = send - s;
	    UNPACK_PUSH(infected_str_new(s, len, str));
	    s += len;
	    break;

	  case 'b':
	    {
		VALUE bitstr;
		char *t;
		int bits;
		long i;

		if (p[-1] == '*' || len > (send - s) * 8)
		    len = (send - s) * 8;
		bits = 0;
		bitstr = rb_usascii_str_new(0, len);
		t = RSTRING_PTR(bitstr);
		for (i=0; i<len; i++) {
		    if (i & 7) bits >>= 1;
		    else bits = (unsigned char)*s++;
		    *t++ = (bits & 1) ? '1' : '0';
		}
		UNPACK_PUSH(bitstr);
	    }
	    break;

	  case 'B':
	    {
		VALUE bitstr;
		char *t;
		int bits;
		long i;

		if (p[-1] == '*' || len > (send - s) * 8)
		    len = (send - s) * 8;
		bits = 0;
		bitstr = rb_usascii_str_new(0, len);
		t = RSTRING_PTR(bitstr);
		for (i=0; i<len; i++) {
		    if (i & 7) bits <<= 1;
		    else bits = (unsigned char)*s++;
		    *t++ = (bits & 128) ? '1' : '0';
		}
		UNPACK_PUSH(bitstr);
	    }
	    break;

	  case 'h':
	    {
		VALUE bitstr;
		char *t;
		int bits;
		long i;

		if (p[-1] == '*' || len > (send - s) * 2)
		    len = (send - s) * 2;
		bits = 0;
		bitstr = rb_usascii_str_new(0, len);
		t = RSTRING_PTR(bitstr);
		for (i=0; i<len; i++) {
		    if (i & 1)
			bits >>= 4;
		    else
			bits = (unsigned char)*s++;
		    *t++ = hexdigits[bits & 15];
		}
		UNPACK_PUSH(bitstr);
	    }
	    break;

	  case 'H':
	    {
		VALUE bitstr;
		char *t;
		int bits;
		long i;

		if (p[-1] == '*' || len > (send - s) * 2)
		    len = (send - s) * 2;
		bits = 0;
		bitstr = rb_usascii_str_new(0, len);
		t = RSTRING_PTR(bitstr);
		for (i=0; i<len; i++) {
		    if (i & 1)
			bits <<= 4;
		    else
			bits = (unsigned char)*s++;
		    *t++ = hexdigits[(bits >> 4) & 15];
		}
		UNPACK_PUSH(bitstr);
	    }
	    break;

	  case 'c':
	    signed_p = 1;
	    integer_size = 1;
	    bigendian_p = BIGENDIAN_P(); /* not effective */
	    goto unpack_integer;

	  case 'C':
	    signed_p = 0;
	    integer_size = 1;
	    bigendian_p = BIGENDIAN_P(); /* not effective */
	    goto unpack_integer;

	  case 's':
	    signed_p = 1;
	    integer_size = NATINT_LEN(short, 2);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'S':
	    signed_p = 0;
	    integer_size = NATINT_LEN(short, 2);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'i':
	    signed_p = 1;
	    integer_size = (int)sizeof(int);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'I':
	    signed_p = 0;
	    integer_size = (int)sizeof(int);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'l':
	    signed_p = 1;
	    integer_size = NATINT_LEN(long, 4);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'L':
	    signed_p = 0;
	    integer_size = NATINT_LEN(long, 4);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'q':
	    signed_p = 1;
	    integer_size = NATINT_LEN_Q;
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'Q':
	    signed_p = 0;
	    integer_size = NATINT_LEN_Q;
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'j':
	    signed_p = 1;
	    integer_size = sizeof(intptr_t);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'J':
	    signed_p = 0;
	    integer_size = sizeof(uintptr_t);
	    bigendian_p = BIGENDIAN_P();
	    goto unpack_integer;

	  case 'n':
	    signed_p = 0;
	    integer_size = 2;
	    bigendian_p = 1;
	    goto unpack_integer;

	  case 'N':
	    signed_p = 0;
	    integer_size = 4;
	    bigendian_p = 1;
	    goto unpack_integer;

	  case 'v':
	    signed_p = 0;
	    integer_size = 2;
	    bigendian_p = 0;
	    goto unpack_integer;

	  case 'V':
	    signed_p = 0;
	    integer_size = 4;
	    bigendian_p = 0;
	    goto unpack_integer;

	  unpack_integer:
	    if (explicit_endian) {
		bigendian_p = explicit_endian == '>';
	    }
            PACK_LENGTH_ADJUST_SIZE(integer_size);
            while (len-- > 0) {
                int flags = bigendian_p ? INTEGER_PACK_BIG_ENDIAN : INTEGER_PACK_LITTLE_ENDIAN;
                VALUE val;
                if (signed_p)
                    flags |= INTEGER_PACK_2COMP;
                val = rb_integer_unpack(s, integer_size, 1, 0, flags);
                UNPACK_PUSH(val);
                s += integer_size;
            }
            PACK_ITEM_ADJUST();
            break;

	  case 'f':
	  case 'F':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(float));
	    while (len-- > 0) {
		float tmp;
		memcpy(&tmp, s, sizeof(float));
		s += sizeof(float);
		UNPACK_PUSH(DBL2NUM((double)tmp));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'e':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(float));
	    while (len-- > 0) {
		FLOAT_CONVWITH(tmp);
		memcpy(tmp.buf, s, sizeof(float));
		s += sizeof(float);
		VTOHF(tmp);
		UNPACK_PUSH(DBL2NUM(tmp.f));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'E':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(double));
	    while (len-- > 0) {
		DOUBLE_CONVWITH(tmp);
		memcpy(tmp.buf, s, sizeof(double));
		s += sizeof(double);
		VTOHD(tmp);
		UNPACK_PUSH(DBL2NUM(tmp.d));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'D':
	  case 'd':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(double));
	    while (len-- > 0) {
		double tmp;
		memcpy(&tmp, s, sizeof(double));
		s += sizeof(double);
		UNPACK_PUSH(DBL2NUM(tmp));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'g':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(float));
	    while (len-- > 0) {
		FLOAT_CONVWITH(tmp);
		memcpy(tmp.buf, s, sizeof(float));
		s += sizeof(float);
		NTOHF(tmp);
		UNPACK_PUSH(DBL2NUM(tmp.f));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'G':
	    PACK_LENGTH_ADJUST_SIZE(sizeof(double));
	    while (len-- > 0) {
		DOUBLE_CONVWITH(tmp);
		memcpy(tmp.buf, s, sizeof(double));
		s += sizeof(double);
		NTOHD(tmp);
		UNPACK_PUSH(DBL2NUM(tmp.d));
	    }
	    PACK_ITEM_ADJUST();
	    break;

	  case 'U':
	    if (len > send - s) len = send - s;
	    while (len > 0 && s < send) {
		long alen = send - s;
		unsigned long l;

		l = utf8_to_uv(s, &alen);
		s += alen; len--;
		UNPACK_PUSH(ULONG2NUM(l));
	    }
	    break;

	  case 'u':
	    {
		VALUE buf = infected_str_new(0, (send - s)*3/4, str);
		char *ptr = RSTRING_PTR(buf);
		long total = 0;

		while (s < send && (unsigned char)*s > ' ' && (unsigned char)*s < 'a') {
		    long a,b,c,d;
		    char hunk[3];

		    len = ((unsigned char)*s++ - ' ') & 077;

		    total += len;
		    if (total > RSTRING_LEN(buf)) {
			len -= total - RSTRING_LEN(buf);
			total = RSTRING_LEN(buf);
		    }

		    while (len > 0) {
			long mlen = len > 3 ? 3 : len;

			if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
			    a = ((unsigned char)*s++ - ' ') & 077;
			else
			    a = 0;
			if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
			    b = ((unsigned char)*s++ - ' ') & 077;
			else
			    b = 0;
			if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
			    c = ((unsigned char)*s++ - ' ') & 077;
			else
			    c = 0;
			if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
			    d = ((unsigned char)*s++ - ' ') & 077;
			else
			    d = 0;
			hunk[0] = (char)(a << 2 | b >> 4);
			hunk[1] = (char)(b << 4 | c >> 2);
			hunk[2] = (char)(c << 6 | d);
			memcpy(ptr, hunk, mlen);
			ptr += mlen;
			len -= mlen;
		    }
		    if (s < send && (unsigned char)*s != '\r' && *s != '\n')
			s++;	/* possible checksum byte */
		    if (s < send && *s == '\r') s++;
		    if (s < send && *s == '\n') s++;
		}

		rb_str_set_len(buf, total);
		UNPACK_PUSH(buf);
	    }
	    break;

	  case 'm':
	    {
		VALUE buf = infected_str_new(0, (send - s + 3)*3/4, str); /* +3 is for skipping paddings */
		char *ptr = RSTRING_PTR(buf);
		int a = -1,b = -1,c = 0,d = 0;
		static signed char b64_xtable[256];

		if (b64_xtable['/'] <= 0) {
		    int i;

		    for (i = 0; i < 256; i++) {
			b64_xtable[i] = -1;
		    }
		    for (i = 0; i < 64; i++) {
			b64_xtable[(unsigned char)b64_table[i]] = (char)i;
		    }
		}
		if (len == 0) {
		    while (s < send) {
			a = b = c = d = -1;
			a = b64_xtable[(unsigned char)*s++];
			if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64");
			b = b64_xtable[(unsigned char)*s++];
			if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64");
			if (*s == '=') {
			    if (s + 2 == send && *(s + 1) == '=') break;
			    rb_raise(rb_eArgError, "invalid base64");
			}
			c = b64_xtable[(unsigned char)*s++];
			if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64");
			if (s + 1 == send && *s == '=') break;
			d = b64_xtable[(unsigned char)*s++];
			if (d == -1) rb_raise(rb_eArgError, "invalid base64");
			*ptr++ = castchar(a << 2 | b >> 4);
			*ptr++ = castchar(b << 4 | c >> 2);
			*ptr++ = castchar(c << 6 | d);
		    }
		    if (c == -1) {
			*ptr++ = castchar(a << 2 | b >> 4);
			if (b & 0xf) rb_raise(rb_eArgError, "invalid base64");
		    }
		    else if (d == -1) {
			*ptr++ = castchar(a << 2 | b >> 4);
			*ptr++ = castchar(b << 4 | c >> 2);
			if (c & 0x3) rb_raise(rb_eArgError, "invalid base64");
		    }
		}
		else {
		    while (s < send) {
			a = b = c = d = -1;
			while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
			if (s >= send) break;
			s++;
			while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
			if (s >= send) break;
			s++;
			while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
			if (*s == '=' || s >= send) break;
			s++;
			while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
			if (*s == '=' || s >= send) break;
			s++;
			*ptr++ = castchar(a << 2 | b >> 4);
			*ptr++ = castchar(b << 4 | c >> 2);
			*ptr++ = castchar(c << 6 | d);
			a = -1;
		    }
		    if (a != -1 && b != -1) {
			if (c == -1)
			    *ptr++ = castchar(a << 2 | b >> 4);
			else {
			    *ptr++ = castchar(a << 2 | b >> 4);
			    *ptr++ = castchar(b << 4 | c >> 2);
			}
		    }
		}
		rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
		UNPACK_PUSH(buf);
	    }
	    break;

	  case 'M':
	    {
		VALUE buf = infected_str_new(0, send - s, str);
		char *ptr = RSTRING_PTR(buf), *ss = s;
		int csum = 0;
		int c1, c2;

		while (s < send) {
		    if (*s == '=') {
			if (++s == send) break;
			if (s+1 < send && *s == '\r' && *(s+1) == '\n')
			    s++;
			if (*s != '\n') {
			    if ((c1 = hex2num(*s)) == -1) break;
			    if (++s == send) break;
			    if ((c2 = hex2num(*s)) == -1) break;
			    csum |= *ptr++ = castchar(c1 << 4 | c2);
			}
		    }
		    else {
			csum |= *ptr++ = *s;
		    }
		    s++;
		    ss = s;
		}
		rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
		rb_str_buf_cat(buf, ss, send-ss);
		csum = ISASCII(csum) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID;
		ENCODING_CODERANGE_SET(buf, rb_ascii8bit_encindex(), csum);
		UNPACK_PUSH(buf);
	    }
	    break;

	  case '@':
	    if (len > RSTRING_LEN(str))
		rb_raise(rb_eArgError, "@ outside of string");
	    s = RSTRING_PTR(str) + len;
	    break;

	  case 'X':
	    if (len > s - RSTRING_PTR(str))
		rb_raise(rb_eArgError, "X outside of string");
	    s -= len;
	    break;

	  case 'x':
	    if (len > send - s)
		rb_raise(rb_eArgError, "x outside of string");
	    s += len;
	    break;

	  case 'P':
	    if (sizeof(char *) <= (size_t)(send - s)) {
		VALUE tmp = Qnil;
		char *t;

		memcpy(&t, s, sizeof(char *));
		s += sizeof(char *);

		if (t) {
		    VALUE a;
		    const VALUE *p, *pend;

		    if (!(a = str_associated(str))) {
			rb_raise(rb_eArgError, "no associated pointer");
		    }
		    p = RARRAY_CONST_PTR(a);
		    pend = p + RARRAY_LEN(a);
		    while (p < pend) {
			if (RB_TYPE_P(*p, T_STRING) && RSTRING_PTR(*p) == t) {
			    if (len < RSTRING_LEN(*p)) {
				tmp = rb_tainted_str_new(t, len);
				str_associate(tmp, a);
			    }
			    else {
				tmp = *p;
			    }
			    break;
			}
			p++;
		    }
		    if (p == pend) {
			rb_raise(rb_eArgError, "non associated pointer");
		    }
		}
		UNPACK_PUSH(tmp);
	    }
	    break;

	  case 'p':
	    if (len > (long)((send - s) / sizeof(char *)))
		len = (send - s) / sizeof(char *);
	    while (len-- > 0) {
		if ((size_t)(send - s) < sizeof(char *))
		    break;
		else {
		    VALUE tmp = Qnil;
		    char *t;

		    memcpy(&t, s, sizeof(char *));
		    s += sizeof(char *);

		    if (t) {
			VALUE a;
			const VALUE *p, *pend;

			if (!(a = str_associated(str))) {
			    rb_raise(rb_eArgError, "no associated pointer");
			}
			p = RARRAY_CONST_PTR(a);
			pend = p + RARRAY_LEN(a);
			while (p < pend) {
			    if (RB_TYPE_P(*p, T_STRING) && RSTRING_PTR(*p) == t) {
				tmp = *p;
				break;
			    }
			    p++;
			}
			if (p == pend) {
			    rb_raise(rb_eArgError, "non associated pointer");
			}
		    }
		    UNPACK_PUSH(tmp);
		}
	    }
	    break;

	  case 'w':
	    {
                char *s0 = s;
                while (len > 0 && s < send) {
                    if (*s & 0x80) {
                        s++;
                    }
                    else {
                        s++;
                        UNPACK_PUSH(rb_integer_unpack(s0, s-s0, 1, 1, INTEGER_PACK_BIG_ENDIAN));
                        len--;
                        s0 = s;
                    }
                }
	    }
	    break;

	  default:
	    rb_warning("unknown unpack directive '%c' in '%s'",
		type, RSTRING_PTR(fmt));
	    break;
	}
    }

    return ary;
}


static void warnf(struct Configurable *config, const char *fmt, ...)
{
  if(!(config->conf & CONF_MUTE)) {
    va_list ap;
    int len;
    char *ptr;
    char print_buffer[256];

    va_start(ap, fmt);
    va_start(ap, fmt);
    len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);
    va_end(ap);

    ptr = print_buffer;
    while(len > 0) {
      fputs(WARN_PREFIX, config->errors);

      if(len > (int)WARN_TEXTWIDTH) {
        int cut = WARN_TEXTWIDTH-1;

        while(!ISSPACE(ptr[cut]) && cut) {
          cut--;
        }

        fwrite(ptr, cut + 1, 1, config->errors);
        fputs("\n", config->errors);
        ptr += cut+1; /* skip the space too */
        len -= cut;
      }
      else {
        fputs(ptr, config->errors);
        len = 0;
      }
    }
  }
}


static void do_sdl_resize(int new_width, int new_height, int bpp) { int flags; // printf("resizing to %d %d\n", w, h); flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL|SDL_RESIZABLE; if (gui_fullscreen) flags |= SDL_FULLSCREEN; if (gui_noframe) flags |= SDL_NOFRAME; width = new_width; height = new_height; real_screen = SDL_SetVideoMode(width, height, bpp, flags); if (!real_screen) { fprintf(stderr, "Could not open SDL display (%dx%dx%d): %s\n", width, height, bpp, SDL_GetError()); exit(1); } }


main(int argc, char* argv[])
{
	uint32 rowsperstrip = (uint32) -1;
	TIFF *in, *out;
	uint32 w, h;
	uint16 samplesperpixel;
	uint16 bitspersample;
	uint16 config;
	uint16 photometric;
	uint16* red;
	uint16* green;
	uint16* blue;
	tsize_t rowsize;
	register uint32 row;
	register tsample_t s;
	unsigned char *inbuf, *outbuf;
	char thing[1024];
	int c;
#if !HAVE_DECL_OPTARG
	extern int optind;
	extern char *optarg;
#endif

        in = (TIFF *) NULL;
        out = (TIFF *) NULL;
        inbuf = (unsigned char *) NULL;
        outbuf = (unsigned char *) NULL;

	while ((c = getopt(argc, argv, "c:r:R:G:B:")) != -1)
		switch (c) {
		case 'c':		/* compression scheme */
			if (!processCompressOptions(optarg))
				usage();
			break;
		case 'r':		/* rows/strip */
			rowsperstrip = atoi(optarg);
			break;
		case 'R':
			RED = PCT(atoi(optarg));
			break;
		case 'G':
			GREEN = PCT(atoi(optarg));
			break;
		case 'B':
			BLUE = PCT(atoi(optarg));
			break;
		case '?':
			usage();
			/*NOTREACHED*/
		}
	if (argc - optind < 2)
		usage();
	in = TIFFOpen(argv[optind], "r");
	if (in == NULL)
		return (-1);
	photometric = 0;
	TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric);
	if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE ) {
		fprintf(stderr,
	    "%s: Bad photometric; can only handle RGB and Palette images.\n",
		    argv[optind]);
                goto tiff2bw_error;
	}
	TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
	if (samplesperpixel != 1 && samplesperpixel != 3) {
		fprintf(stderr, "%s: Bad samples/pixel %u.\n",
		    argv[optind], samplesperpixel);
                goto tiff2bw_error;
	}
	if( photometric == PHOTOMETRIC_RGB && samplesperpixel != 3) {
		fprintf(stderr, "%s: Bad samples/pixel %u for PHOTOMETRIC_RGB.\n",
		    argv[optind], samplesperpixel);
                goto tiff2bw_error;
	}
	TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
	if (bitspersample != 8) {
		fprintf(stderr,
		    " %s: Sorry, only handle 8-bit samples.\n", argv[optind]);
                goto tiff2bw_error;
	}
	TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
	TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h);
	TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);

	out = TIFFOpen(argv[optind+1], "w");
	if (out == NULL)
	{
                goto tiff2bw_error;
	}
	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w);
	TIFFSetField(out, TIFFTAG_IMAGELENGTH, h);
	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
	TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
	cpTags(in, out);
	if (compression != (uint16) -1) {
		TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
		switch (compression) {
		case COMPRESSION_JPEG:
			TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
			TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
			break;
		case COMPRESSION_LZW:
		case COMPRESSION_DEFLATE:
			if (predictor != 0)
				TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
			break;
		}
	}
	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
	snprintf(thing, sizeof(thing), "B&W version of %s", argv[optind]);
	TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
	TIFFSetField(out, TIFFTAG_SOFTWARE, "tiff2bw");
	outbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
	    TIFFDefaultStripSize(out, rowsperstrip));

#define	pack(a,b)	((a)<<8 | (b))
	switch (pack(photometric, config)) {
	case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
	case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
		TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue);
		/*
		 * Convert 16-bit colormap to 8-bit (unless it looks
		 * like an old-style 8-bit colormap).
		 */
		if (checkcmap(in, 1<<bitspersample, red, green, blue) == 16) {
			int i;
#define	CVT(x)		(((x) * 255L) / ((1L<<16)-1))
			for (i = (1<<bitspersample)-1; i >= 0; i--) {
				red[i] = CVT(red[i]);
				green[i] = CVT(green[i]);
				blue[i] = CVT(blue[i]);
			}
#undef CVT
		}
		inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
		for (row = 0; row < h; row++) {
			if (TIFFReadScanline(in, inbuf, row, 0) < 0)
				break;
			compresspalette(outbuf, inbuf, w, red, green, blue);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
		inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
		for (row = 0; row < h; row++) {
			if (TIFFReadScanline(in, inbuf, row, 0) < 0)
				break;
			compresscontig(outbuf, inbuf, w);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
		rowsize = TIFFScanlineSize(in);
		inbuf = (unsigned char *)_TIFFmalloc(3*rowsize);
		for (row = 0; row < h; row++) {
			for (s = 0; s < 3; s++)
				if (TIFFReadScanline(in,
				    inbuf+s*rowsize, row, s) < 0)
                                        goto tiff2bw_error;
			compresssep(outbuf,
			    inbuf, inbuf+rowsize, inbuf+2*rowsize, w);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	}
#undef pack
        if (inbuf)
                _TIFFfree(inbuf);
        if (outbuf)
                _TIFFfree(outbuf);
        TIFFClose(in);
	TIFFClose(out);
	return (0);

 tiff2bw_error:
        if (inbuf)
                _TIFFfree(inbuf);
        if (outbuf)
                _TIFFfree(outbuf);
        if (out)
                TIFFClose(out);
        if (in)
                TIFFClose(in);
        return (-1);
}


void remove_tap_listener_mgcp_calls ( void ) {
 remove_tap_listener ( & ( the_tapinfo_struct . mgcp_dummy ) ) ;
 have_MGCP_tap_listener = FALSE ;
 }


static int dissect_h245_Restriction ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h245_Restriction , Restriction_choice , NULL ) ;
 return offset ;
 }


static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter) { int pid; pid = filter->pid; if (filter->type == MPEGTS_SECTION) av_freep(&filter->u.section_filter.section_buf); av_free(filter); ts->pids[pid] = NULL;


static void blk_mig_reset_dirty_cursor(void) { BlkMigDevState *bmds; QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) { bmds->cur_dirty = 0; } }


void NumberFormatTest::Test20037_ScientificIntegerOverflow() {
    IcuTestErrorCode status(*this, "Test20037_ScientificIntegerOverflow");

    LocalPointer<NumberFormat> nf(NumberFormat::createInstance(status));
    if (U_FAILURE(status)) {
        dataerrln("Unable to create NumberFormat instance.");
        return;
    }
    Formattable result;

    // Test overflow of exponent
    nf->parse(u"1E-2147483648", result, status);
    StringPiece sp = result.getDecimalNumber(status);
    assertEquals(u"Should snap to zero",
                 u"0",
                 {sp.data(), sp.length(), US_INV});

    // Test edge case overflow of exponent
    result = Formattable();
    nf->parse(u"1E-2147483647E-1", result, status);
    sp = result.getDecimalNumber(status);
    assertEquals(u"Should not overflow and should parse only the first exponent",
                 u"1E-2147483647",
                 {sp.data(), sp.length(), US_INV});
}


static void url_stream_end (auth_client *auth_user)
{
    char *mount, *server;
    ice_config_t *config = config_get_config ();
    mount_proxy *mountinfo = config_find_mount (config, auth_user->mount, MOUNT_TYPE_NORMAL);
    auth_t *auth = mountinfo->auth;
    auth_url *url = auth->state;
    char *stream_end_url;
    int port;
    char post [4096];

    if (url->stream_end == NULL)
    {
        config_release_config ();
        return;
    }
    server = util_url_escape (config->hostname);
    port = config->port;
    stream_end_url = strdup (url->stream_end);
    /* we don't want this auth disappearing from under us while
     * the connection is in progress */
    mountinfo->auth->refcount++;
    config_release_config ();
    mount = util_url_escape (auth_user->mount);

    snprintf (post, sizeof (post),
            "action=mount_remove&mount=%s&server=%s&port=%d", mount, server, port);
    free (server);
    free (mount);

    if (strchr (url->stream_end, '@') == NULL)
    {
        if (url->userpwd)
            curl_easy_setopt (url->handle, CURLOPT_USERPWD, url->userpwd);
        else
            curl_easy_setopt (url->handle, CURLOPT_USERPWD, "");
    }
    else
        curl_easy_setopt (url->handle, CURLOPT_USERPWD, "");
    curl_easy_setopt (url->handle, CURLOPT_URL, url->stream_end);
    curl_easy_setopt (url->handle, CURLOPT_POSTFIELDS, post);
    curl_easy_setopt (url->handle, CURLOPT_WRITEHEADER, auth_user);

    if (curl_easy_perform (url->handle))
        ICECAST_LOG_WARN("auth to server %s failed with %s", stream_end_url, url->errormsg);

    auth_release (auth);
    free (stream_end_url);
    return;
}


delete_buff_tail(buffheader_T *buf, int slen)
{
    int len = (int)STRLEN(buf->bh_curr->b_str);

    if (len >= slen)
    {
	buf->bh_curr->b_str[len - slen] = NUL;
	buf->bh_space += slen;
    }
}


void nautilus_file_mark_desktop_file_executable ( GFile * file , GtkWindow * parent_window , gboolean interactive , NautilusOpCallback done_callback , gpointer done_callback_data ) {
 GTask * task ;
 MarkTrustedJob * job ;
 job = op_job_new ( MarkTrustedJob , parent_window ) ;
 job -> file = g_object_ref ( file ) ;
 job -> interactive = interactive ;
 job -> done_callback = done_callback ;
 job -> done_callback_data = done_callback_data ;
 task = g_task_new ( NULL , NULL , mark_desktop_file_executable_task_done , job ) ;
 g_task_set_task_data ( task , job , NULL ) ;
 g_task_run_in_thread ( task , mark_desktop_file_executable_task_thread_func ) ;
 g_object_unref ( task ) ;
 }


static int access_check ( i_ctx_t * i_ctx_p , int access , bool modify ) {
 os_ptr op = osp ;
 ref * aop ;
 switch ( r_type ( op ) ) {
 case t_dictionary : aop = dict_access_ref ( op ) ;
 if ( modify ) {
 if ( ! r_has_attrs ( aop , access ) ) return_error ( gs_error_invalidaccess ) ;
 ref_save ( op , aop , "access_check(modify)" ) ;
 r_clear_attrs ( aop , a_all ) ;
 r_set_attrs ( aop , access ) ;
 dict_set_top ( ) ;
 return 0 ;
 }
 break ;
 case t_array : case t_file : case t_string : case t_mixedarray : case t_shortarray : case t_astruct : case t_device : ;
 if ( modify ) {
 if ( ! r_has_attrs ( op , access ) ) return_error ( gs_error_invalidaccess ) ;
 r_clear_attrs ( op , a_all ) ;
 r_set_attrs ( op , access ) ;
 return 0 ;
 }
 aop = op ;
 break ;
 default : return_op_typecheck ( op ) ;
 }
 return ( r_has_attrs ( aop , access ) ? 1 : 0 ) ;
 }


ga_concat_shorten_esc(garray_T *gap, char_u *str)
{
    char_u  *p;
    char_u  *s;
    int	    c;
    int	    clen;
    char_u  buf[NUMBUFLEN];
    int	    same_len;

    if (str == NULL)
    {
	ga_concat(gap, (char_u *)"NULL");
	return;
    }

    for (p = str; *p != NUL; ++p)
    {
	same_len = 1;
	s = p;
	c = mb_ptr2char_adv(&s);
	clen = s - p;
	while (*s != NUL && c == mb_ptr2char(s))
	{
	    ++same_len;
	    s += clen;
	}
	if (same_len > 20)
	{
	    ga_concat(gap, (char_u *)"\\[");
	    ga_concat_esc(gap, p, clen);
	    ga_concat(gap, (char_u *)" occurs ");
	    vim_snprintf((char *)buf, NUMBUFLEN, "%d", same_len);
	    ga_concat(gap, buf);
	    ga_concat(gap, (char_u *)" times]");
	    p = s - 1;
	}
	else
	    ga_concat_esc(gap, p, clen);
    }
}


static int decode_header(SnowContext *s){ int plane_index, tmp; uint8_t kstate[32]; memset(kstate, MID_STATE, sizeof(kstate)); s->keyframe= get_rac(&s->c, kstate); if(s->keyframe || s->always_reset){ ff_snow_reset_contexts(s); s->spatial_decomposition_type= s->qlog= s->qbias= s->mv_scale= s->block_max_depth= 0; } if(s->keyframe){ GET_S(s->version, tmp <= 0U) s->always_reset= get_rac(&s->c, s->header_state); s->temporal_decomposition_type= get_symbol(&s->c, s->header_state, 0); s->temporal_decomposition_count= get_symbol(&s->c, s->header_state, 0); GET_S(s->spatial_decomposition_count, 0 < tmp && tmp <= MAX_DECOMPOSITIONS) s->colorspace_type= get_symbol(&s->c, s->header_state, 0); if (s->colorspace_type == 1) { s->avctx->pix_fmt= AV_PIX_FMT_GRAY8; s->nb_planes = 1; } else if(s->colorspace_type == 0) { s->chroma_h_shift= get_symbol(&s->c, s->header_state, 0); s->chroma_v_shift= get_symbol(&s->c, s->header_state, 0); if(s->chroma_h_shift == 1 && s->chroma_v_shift==1){ s->avctx->pix_fmt= AV_PIX_FMT_YUV420P; }else if(s->chroma_h_shift == 0 && s->chroma_v_shift==0){ s->avctx->pix_fmt= AV_PIX_FMT_YUV444P; }else if(s->chroma_h_shift == 2 && s->chroma_v_shift==2){ s->avctx->pix_fmt= AV_PIX_FMT_YUV410P; } else { av_log(s, AV_LOG_ERROR, "unsupported color subsample mode %d %d\n", s->chroma_h_shift, s->chroma_v_shift); s->chroma_h_shift = s->chroma_v_shift = 1; s->avctx->pix_fmt= AV_PIX_FMT_YUV420P; return AVERROR_INVALIDDATA; } s->nb_planes = 3; } else { av_log(s, AV_LOG_ERROR, "unsupported color space\n"); s->chroma_h_shift = s->chroma_v_shift = 1; s->avctx->pix_fmt= AV_PIX_FMT_YUV420P; return AVERROR_INVALIDDATA; } s->spatial_scalability= get_rac(&s->c, s->header_state); // s->rate_scalability= get_rac(&s->c, s->header_state); GET_S(s->max_ref_frames, tmp < (unsigned)MAX_REF_FRAMES) s->max_ref_frames++; decode_qlogs(s); } if(!s->keyframe){ if(get_rac(&s->c, s->header_state)){ for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){ int htaps, i, sum=0; Plane *p= &s->plane[plane_index]; p->diag_mc= get_rac(&s->c, s->header_state); htaps= get_symbol(&s->c, s->header_state, 0)*2 + 2; if((unsigned)htaps >= HTAPS_MAX || htaps==0) return AVERROR_INVALIDDATA; p->htaps= htaps; for(i= htaps/2; i; i--){ p->hcoeff[i]= get_symbol(&s->c, s->header_state, 0) * (1-2*(i&1)); sum += p->hcoeff[i]; } p->hcoeff[0]= 32-sum; } s->plane[2].diag_mc= s->plane[1].diag_mc; s->plane[2].htaps = s->plane[1].htaps; memcpy(s->plane[2].hcoeff, s->plane[1].hcoeff, sizeof(s->plane[1].hcoeff)); } if(get_rac(&s->c, s->header_state)){ GET_S(s->spatial_decomposition_count, 0 < tmp && tmp <= MAX_DECOMPOSITIONS) decode_qlogs(s); } } s->spatial_decomposition_type+= get_symbol(&s->c, s->header_state, 1); if(s->spatial_decomposition_type > 1U){ av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_type %d not supported\n", s->spatial_decomposition_type); return AVERROR_INVALIDDATA; } if(FFMIN(s->avctx-> width>>s->chroma_h_shift, s->avctx->height>>s->chroma_v_shift) >> (s->spatial_decomposition_count-1) <= 1){ av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_count %d too large for size\n", s->spatial_decomposition_count); return AVERROR_INVALIDDATA; } if (s->avctx->width > 65536-4) { av_log(s->avctx, AV_LOG_ERROR, "Width %d is too large\n", s->avctx->width); return AVERROR_INVALIDDATA; } s->qlog += get_symbol(&s->c, s->header_state, 1); s->mv_scale += get_symbol(&s->c, s->header_state, 1); s->qbias += get_symbol(&s->c, s->header_state, 1); s->block_max_depth+= get_symbol(&s->c, s->header_state, 1); if(s->block_max_depth > 1 || s->block_max_depth < 0 || s->mv_scale > 256U){ av_log(s->avctx, AV_LOG_ERROR, "block_max_depth= %d is too large\n", s->block_max_depth); s->block_max_depth= 0; s->mv_scale = 0; return AVERROR_INVALIDDATA; } if (FFABS(s->qbias) > 127) { av_log(s->avctx, AV_LOG_ERROR, "qbias %d is too large\n", s->qbias); s->qbias = 0; return AVERROR_INVALIDDATA; } return 0; }


amstar_estimate(
    application_argument_t *argument)
{
    GPtrArray  *argv_ptr;
    char       *cmd = NULL;
    int         nullfd;
    int         pipefd;
    FILE       *dumpout = NULL;
    off_t       size = -1;
    char        line[32768];
    char       *errmsg = NULL;
    char       *qerrmsg;
    char       *qdisk;
    amwait_t    wait_status;
    int         starpid;
    amregex_t  *rp;
    times_t     start_time;
    int         level = 0;
    GSList     *levels = NULL;
    char       *option;

    if (!argument->level) {
	fprintf(stderr, "ERROR No level argument\n");
	error(_("No level argument"));
    }
    if (!argument->dle.disk) {
	fprintf(stderr, "ERROR No disk argument\n");
	error(_("No disk argument"));
    }
    if (!argument->dle.device) {
	fprintf(stderr, "ERROR No device argument\n");
	error(_("No device argument"));
    }

    if (argument->dle.include_list &&
	argument->dle.include_list->nb_element >= 0) {
	fprintf(stderr, "ERROR include-list not supported for backup\n");
    }

    if (check_device(argument) == 0) {
	return;
    }

    if ((option = validate_command_options(argument))) {
	fprintf(stderr, "ERROR Invalid '%s' COMMAND-OPTIONS\n", option);
	error("Invalid '%s' COMMAND-OPTIONS", option);
    }

    qdisk = quote_string(argument->dle.disk);
    if (argument->calcsize) {
	char *dirname;
	char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL);
	if (!check_exec_for_suid(calcsize, FALSE)) {
	    errmsg = g_strdup_printf("'%s' binary is not secure", calcsize);
	    goto common_error;
	    return;
	}

	if (star_directory) {
	    dirname = star_directory;
	} else {
	    dirname = argument->dle.device;
	}
	run_calcsize(argument->config, "STAR", argument->dle.disk, dirname,
		     argument->level, NULL, NULL);
	return;
    }

    if (!star_path) {
	errmsg = vstrallocf(_("STAR-PATH not defined"));
	goto common_error;
    }
    if (!check_exec_for_suid(star_path, FALSE)) {
	errmsg = g_strdup_printf("'%s' binary is not secure", star_path);
	goto common_error;
    }

    cmd = stralloc(star_path);

    start_time = curclock();

    for (levels = argument->level; levels != NULL; levels = levels->next) {
	level = GPOINTER_TO_INT(levels->data);
	argv_ptr = amstar_build_argv(argument, level, CMD_ESTIMATE, NULL);

	if ((nullfd = open("/dev/null", O_RDWR)) == -1) {
	    errmsg = vstrallocf(_("Cannot access /dev/null : %s"),
				strerror(errno));
	    goto common_error;
	}

	starpid = pipespawnv(cmd, STDERR_PIPE, 1,
			     &nullfd, &nullfd, &pipefd,
			     (char **)argv_ptr->pdata);

	dumpout = fdopen(pipefd,"r");
	if (!dumpout) {
	    errmsg = vstrallocf(_("Can't fdopen: %s"), strerror(errno));
	    goto common_error;
	}

	size = (off_t)-1;
	while (size < 0 && (fgets(line, sizeof(line), dumpout)) != NULL) {
	    if (line[strlen(line)-1] == '\n') /* remove trailling \n */
		line[strlen(line)-1] = '\0';
	    if (line[0] == '\0')
		continue;
	    dbprintf("%s\n", line);
	    /* check for size match */
	    /*@ignore@*/
	    for(rp = re_table; rp->regex != NULL; rp++) {
		if(match(rp->regex, line)) {
		    if (rp->typ == DMP_SIZE) {
			size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);
			if(size < 0.0)
			    size = 1.0;             /* found on NeXT -- sigh */
		    }
		    break;
		}
	    }
	    /*@end@*/
	}

	while ((fgets(line, sizeof(line), dumpout)) != NULL) {
	    dbprintf("%s", line);
	}

	dbprintf(".....\n");
	dbprintf(_("estimate time for %s level %d: %s\n"),
		 qdisk,
		 level,
		 walltime_str(timessub(curclock(), start_time)));
	if(size == (off_t)-1) {
	    errmsg = vstrallocf(_("no size line match in %s output"),
				cmd);
	    dbprintf(_("%s for %s\n"), errmsg, qdisk);
	    dbprintf(".....\n");
	} else if(size == (off_t)0 && argument->level == 0) {
	    dbprintf(_("possible %s problem -- is \"%s\" really empty?\n"),
		     cmd, argument->dle.disk);
	    dbprintf(".....\n");
	}
	dbprintf(_("estimate size for %s level %d: %lld KB\n"),
		 qdisk,
		 level,
		 (long long)size);

	kill(-starpid, SIGTERM);

	dbprintf(_("waiting for %s \"%s\" child\n"), cmd, qdisk);
	waitpid(starpid, &wait_status, 0);
	if (WIFSIGNALED(wait_status)) {
	    errmsg = vstrallocf(_("%s terminated with signal %d: see %s"),
				cmd, WTERMSIG(wait_status), dbfn());
	} else if (WIFEXITED(wait_status)) {
	    if (WEXITSTATUS(wait_status) != 0) {
		errmsg = vstrallocf(_("%s exited with status %d: see %s"),
				    cmd, WEXITSTATUS(wait_status), dbfn());
	    } else {
		/* Normal exit */
	    }
	} else {
	    errmsg = vstrallocf(_("%s got bad exit: see %s"), cmd, dbfn());
	}
	dbprintf(_("after %s %s wait\n"), cmd, qdisk);

	g_ptr_array_free_full(argv_ptr);

	aclose(nullfd);
	afclose(dumpout);

	fprintf(stdout, "%d %lld 1\n", level, (long long)size);
    }
    amfree(qdisk);
    amfree(cmd);
    return;

common_error:
    dbprintf("%s\n", errmsg);
    qerrmsg = quote_string(errmsg);
    amfree(qdisk);
    dbprintf("%s", errmsg);
    fprintf(stdout, "ERROR %s\n", qerrmsg);
    amfree(errmsg);
    amfree(qerrmsg);
    amfree(cmd);
}


void qemu_input_event_send_key(QemuConsole *src, KeyValue *key, bool down) { InputEvent *evt; evt = qemu_input_event_new_key(key, down); if (QTAILQ_EMPTY(&kbd_queue)) { qemu_input_event_send(src, evt); qemu_input_event_sync(); qapi_free_InputEvent(evt); } else { qemu_input_queue_event(&kbd_queue, src, evt); qemu_input_queue_sync(&kbd_queue); } }


int av_strerror(int errnum, char *errbuf, size_t errbuf_size) { int ret = 0, i; struct error_entry *entry = NULL; for (i = 0; i < FF_ARRAY_ELEMS(error_entries); i++) { if (errnum == error_entries[i].num) { entry = &error_entries[i]; break; } } if (entry) { av_strlcpy(errbuf, entry->str, errbuf_size); } else { #if HAVE_STRERROR_R ret = strerror_r(AVUNERROR(errnum), errbuf, errbuf_size); #else ret = -1; #endif if (ret < 0) snprintf(errbuf, errbuf_size, "Error number %d occurred", errnum); } return ret; }


static int dissect_h245_CloseLogicalChannelAck ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_CloseLogicalChannelAck , CloseLogicalChannelAck_sequence ) ;
 # line 554 "../../asn1/h245/h245.cnf" if ( h245_pi != NULL ) h245_pi -> msg_type = H245_CloseLogChnAck ;
 return offset ;
 }


static int ngsniffer_process_record ( wtap * wth , gboolean is_random , guint * padding , struct wtap_pkthdr * phdr , Buffer * buf , int * err , gchar * * err_info ) {
 ngsniffer_t * ngsniffer ;
 char record_type [ 2 ] ;
 char record_length [ 4 ] ;
 guint type , length ;
 struct frame2_rec frame2 ;
 struct frame4_rec frame4 ;
 struct frame6_rec frame6 ;
 guint16 time_low , time_med , true_size , size ;
 guint8 time_high , time_day ;
 guint64 t , tsecs , tpsecs ;
 if ( ! ng_read_bytes_or_eof ( wth , record_type , 2 , is_random , err , err_info ) ) {
 if ( * err != 0 ) return - 1 ;
 return REC_EOF ;
 }
 if ( ! ng_read_bytes ( wth , record_length , 4 , is_random , err , err_info ) ) return - 1 ;
 type = pletoh16 ( record_type ) ;
 length = pletoh16 ( record_length ) ;
 ngsniffer = ( ngsniffer_t * ) wth -> priv ;
 switch ( type ) {
 case REC_FRAME2 : if ( ngsniffer -> network == NETWORK_ATM ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: REC_FRAME2 record in an ATM Sniffer file" ) ;
 return - 1 ;
 }
 if ( length < sizeof frame2 ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: REC_FRAME2 record length is less than record header length" ) ;
 return - 1 ;
 }
 if ( ! ng_read_bytes ( wth , & frame2 , ( unsigned int ) sizeof frame2 , is_random , err , err_info ) ) return - 1 ;
 time_low = pletoh16 ( & frame2 . time_low ) ;
 time_med = pletoh16 ( & frame2 . time_med ) ;
 time_high = frame2 . time_high ;
 time_day = frame2 . time_day ;
 size = pletoh16 ( & frame2 . size ) ;
 true_size = pletoh16 ( & frame2 . true_size ) ;
 length -= sizeof frame2 ;
 set_pseudo_header_frame2 ( wth , & phdr -> pseudo_header , & frame2 ) ;
 break ;
 case REC_FRAME4 : if ( ngsniffer -> network != NETWORK_ATM ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: REC_FRAME4 record in a non-ATM Sniffer file" ) ;
 return - 1 ;
 }
 if ( ngsniffer -> maj_vers < 5 && ngsniffer -> min_vers >= 95 ) length += sizeof frame4 - sizeof frame2 ;
 if ( length < sizeof frame4 ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: REC_FRAME4 record length is less than record header length" ) ;
 return - 1 ;
 }
 if ( ! ng_read_bytes ( wth , & frame4 , ( unsigned int ) sizeof frame4 , is_random , err , err_info ) ) return - 1 ;
 time_low = pletoh16 ( & frame4 . time_low ) ;
 time_med = pletoh16 ( & frame4 . time_med ) ;
 time_high = frame4 . time_high ;
 time_day = frame4 . time_day ;
 size = pletoh16 ( & frame4 . size ) ;
 true_size = pletoh16 ( & frame4 . true_size ) ;
 length -= sizeof frame4 ;
 set_pseudo_header_frame4 ( & phdr -> pseudo_header , & frame4 ) ;
 break ;
 case REC_FRAME6 : if ( length < sizeof frame6 ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: REC_FRAME6 record length is less than record header length" ) ;
 return - 1 ;
 }
 if ( ! ng_read_bytes ( wth , & frame6 , ( unsigned int ) sizeof frame6 , is_random , err , err_info ) ) return - 1 ;
 time_low = pletoh16 ( & frame6 . time_low ) ;
 time_med = pletoh16 ( & frame6 . time_med ) ;
 time_high = frame6 . time_high ;
 time_day = frame6 . time_day ;
 size = pletoh16 ( & frame6 . size ) ;
 true_size = pletoh16 ( & frame6 . true_size ) ;
 length -= sizeof frame6 ;
 set_pseudo_header_frame6 ( wth , & phdr -> pseudo_header , & frame6 ) ;
 break ;
 case REC_EOF : * err = 0 ;
 return REC_EOF ;
 default : if ( padding != NULL ) {
 * padding = length ;
 }
 return type ;
 }
 if ( size > length ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup ( "ngsniffer: Record length is less than packet size" ) ;
 return - 1 ;
 }
 if ( padding != NULL ) {
 * padding = length - size ;
 }
 phdr -> rec_type = REC_TYPE_PACKET ;
 phdr -> presence_flags = true_size ? WTAP_HAS_TS | WTAP_HAS_CAP_LEN : WTAP_HAS_TS ;
 phdr -> len = true_size ? true_size : size ;
 phdr -> caplen = size ;
 ws_buffer_assure_space ( buf , size ) ;
 if ( ! ng_read_bytes ( wth , ws_buffer_start_ptr ( buf ) , size , is_random , err , err_info ) ) return - 1 ;
 phdr -> pkt_encap = fix_pseudo_header ( wth -> file_encap , buf , size , & phdr -> pseudo_header ) ;
 t = ( ( ( guint64 ) time_high ) << 32 ) | ( ( ( guint64 ) time_med ) << 16 ) | time_low ;
 t *= ngsniffer -> timeunit ;
 tsecs = t / G_GUINT64_CONSTANT ( 1000000000000 ) ;
 tpsecs = t - tsecs * G_GUINT64_CONSTANT ( 1000000000000 ) ;
 tsecs += time_day * 86400 ;
 tsecs += ngsniffer -> start ;
 phdr -> ts . secs = ( time_t ) tsecs ;
 phdr -> ts . nsecs = ( int ) ( tpsecs / 1000 ) ;
 return type ;
 }


static void bind_date_conv ( uint row_count , my_bool preserveFractions ) {
 MYSQL_STMT * stmt = 0 ;
 uint rc , i , count = row_count ;
 ulong length [ 4 ] ;
 MYSQL_BIND my_bind [ 4 ] ;
 my_bool is_null [ 4 ] = {
 0 }
 ;
 MYSQL_TIME tm [ 4 ] ;
 ulong second_part ;
 uint year , month , day , hour , minute , sec ;
 uint now_year = 1990 , now_month = 3 , now_day = 13 ;
 rc = mysql_query ( mysql , "SET timestamp=UNIX_TIMESTAMP('1990-03-13')" ) ;
 myquery ( rc ) ;
 stmt = mysql_simple_prepare ( mysql , "INSERT INTO test_date VALUES(?, ?, ?, ?)" ) ;
 check_stmt ( stmt ) ;
 verify_param_count ( stmt , 4 ) ;
 memset ( my_bind , 0 , sizeof ( my_bind ) ) ;
 my_bind [ 0 ] . buffer_type = MYSQL_TYPE_TIMESTAMP ;
 my_bind [ 1 ] . buffer_type = MYSQL_TYPE_TIME ;
 my_bind [ 2 ] . buffer_type = MYSQL_TYPE_DATETIME ;
 my_bind [ 3 ] . buffer_type = MYSQL_TYPE_DATE ;
 for ( i = 0 ;
 i < ( int ) array_elements ( my_bind ) ;
 i ++ ) {
 my_bind [ i ] . buffer = ( void * ) & tm [ i ] ;
 my_bind [ i ] . is_null = & is_null [ i ] ;
 my_bind [ i ] . length = & length [ i ] ;
 my_bind [ i ] . buffer_length = 30 ;
 length [ i ] = 20 ;
 }
 second_part = 0 ;
 year = 2000 ;
 month = 01 ;
 day = 10 ;
 hour = 11 ;
 minute = 16 ;
 sec = 20 ;
 rc = mysql_stmt_bind_param ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 for ( count = 0 ;
 count < row_count ;
 count ++ ) {
 for ( i = 0 ;
 i < ( int ) array_elements ( my_bind ) ;
 i ++ ) {
 tm [ i ] . neg = 0 ;
 tm [ i ] . second_part = second_part + count ;
 if ( my_bind [ i ] . buffer_type != MYSQL_TYPE_TIME ) {
 tm [ i ] . year = year + count ;
 tm [ i ] . month = month + count ;
 tm [ i ] . day = day + count ;
 }
 else tm [ i ] . year = tm [ i ] . month = tm [ i ] . day = 0 ;
 if ( my_bind [ i ] . buffer_type != MYSQL_TYPE_DATE ) {
 tm [ i ] . hour = hour + count ;
 tm [ i ] . minute = minute + count ;
 tm [ i ] . second = sec + count ;
 }
 else tm [ i ] . hour = tm [ i ] . minute = tm [ i ] . second = 0 ;
 }
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 }
 rc = mysql_commit ( mysql ) ;
 myquery ( rc ) ;
 mysql_stmt_close ( stmt ) ;
 rc = my_stmt_result ( "SELECT * FROM test_date" ) ;
 DIE_UNLESS ( row_count == rc ) ;
 stmt = mysql_simple_prepare ( mysql , "SELECT * FROM test_date" ) ;
 check_stmt ( stmt ) ;
 rc = mysql_stmt_bind_result ( stmt , my_bind ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_store_result ( stmt ) ;
 check_execute ( stmt , rc ) ;
 for ( count = 0 ;
 count < row_count ;
 count ++ ) {
 rc = mysql_stmt_fetch ( stmt ) ;
 DIE_UNLESS ( rc == 0 || rc == MYSQL_DATA_TRUNCATED ) ;
 if ( ! opt_silent ) fprintf ( stdout , "\n" ) ;
 for ( i = 0 ;
 i < array_elements ( my_bind ) ;
 i ++ ) {
 if ( ! opt_silent ) fprintf ( stdout , "\ntime[%d]: %02d-%02d-%02d %02d:%02d:%02d.%06lu" , i , tm [ i ] . year , tm [ i ] . month , tm [ i ] . day , tm [ i ] . hour , tm [ i ] . minute , tm [ i ] . second , tm [ i ] . second_part ) ;
 DIE_UNLESS ( tm [ i ] . year == 0 || tm [ i ] . year == year + count || ( tm [ i ] . year == now_year && my_bind [ i ] . buffer_type == MYSQL_TYPE_TIME ) ) ;
 DIE_UNLESS ( tm [ i ] . month == 0 || tm [ i ] . month == month + count || ( tm [ i ] . month == now_month && my_bind [ i ] . buffer_type == MYSQL_TYPE_TIME ) ) ;
 DIE_UNLESS ( tm [ i ] . day == 0 || tm [ i ] . day == day + count || ( tm [ i ] . day == now_day && my_bind [ i ] . buffer_type == MYSQL_TYPE_TIME ) ) ;
 DIE_UNLESS ( tm [ i ] . hour == 0 || tm [ i ] . hour == hour + count ) ;
 DIE_UNLESS ( tm [ i ] . minute == 0 || tm [ i ] . minute == minute + count ) ;
 DIE_UNLESS ( tm [ i ] . second == 0 || tm [ i ] . second == sec + count ) ;
 if ( preserveFractions ) {
 if ( i == 3 ) {
 DIE_UNLESS ( tm [ i ] . second_part == 0 ) ;
 }
 else {
 DIE_UNLESS ( tm [ i ] . second_part == second_part + count ) ;
 }
 }
 else {
 DIE_UNLESS ( ( tm [ i ] . second_part == 0 ) || tm [ i ] . second_part == second_part + count ) ;
 }
 }
 }
 rc = mysql_stmt_fetch ( stmt ) ;
 DIE_UNLESS ( rc == MYSQL_NO_DATA ) ;
 mysql_stmt_close ( stmt ) ;
 }


static int dissect_h245_T_atm_AAL5_compressed ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_T_atm_AAL5_compressed , T_atm_AAL5_compressed_sequence ) ;
 return offset ;
 }


static const unsigned char * seq_decode_op2 ( SeqVideoContext * seq , const unsigned char * src , const unsigned char * src_end , unsigned char * dst ) {
 int i ;
 if ( src_end - src < 8 * 8 ) return NULL ;
 for ( i = 0 ;
 i < 8 ;
 i ++ ) {
 memcpy ( dst , src , 8 ) ;
 src += 8 ;
 dst += seq -> frame . linesize [ 0 ] ;
 }
 return src ;
 }


stop_insert(
    pos_T	*end_insert_pos,
    int		esc,			// called by ins_esc()
    int		nomove)			// <c-\><c-o>, don't move cursor
{
    int		cc;
    char_u	*ptr;

    stop_redo_ins();
    replace_flush();		// abandon replace stack

    /*
     * Save the inserted text for later redo with ^@ and CTRL-A.
     * Don't do it when "restart_edit" was set and nothing was inserted,
     * otherwise CTRL-O w and then <Left> will clear "last_insert".
     */
    ptr = get_inserted();
    if (did_restart_edit == 0 || (ptr != NULL
				       && (int)STRLEN(ptr) > new_insert_skip))
    {
	vim_free(last_insert);
	last_insert = ptr;
	last_insert_skip = new_insert_skip;
    }
    else
	vim_free(ptr);

    if (!arrow_used && end_insert_pos != NULL)
    {
	// Auto-format now.  It may seem strange to do this when stopping an
	// insertion (or moving the cursor), but it's required when appending
	// a line and having it end in a space.  But only do it when something
	// was actually inserted, otherwise undo won't work.
	if (!ins_need_undo && has_format_option(FO_AUTO))
	{
	    pos_T   tpos = curwin->w_cursor;

	    // When the cursor is at the end of the line after a space the
	    // formatting will move it to the following word.  Avoid that by
	    // moving the cursor onto the space.
	    cc = 'x';
	    if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
	    {
		dec_cursor();
		cc = gchar_cursor();
		if (!VIM_ISWHITE(cc))
		    curwin->w_cursor = tpos;
	    }

	    auto_format(TRUE, FALSE);

	    if (VIM_ISWHITE(cc))
	    {
		if (gchar_cursor() != NUL)
		    inc_cursor();
		// If the cursor is still at the same character, also keep
		// the "coladd".
		if (gchar_cursor() == NUL
			&& curwin->w_cursor.lnum == tpos.lnum
			&& curwin->w_cursor.col == tpos.col)
		    curwin->w_cursor.coladd = tpos.coladd;
	    }
	}

	// If a space was inserted for auto-formatting, remove it now.
	check_auto_format(TRUE);

	// If we just did an auto-indent, remove the white space from the end
	// of the line, and put the cursor back.
	// Do this when ESC was used or moving the cursor up/down.
	// Check for the old position still being valid, just in case the text
	// got changed unexpectedly.
	if (!nomove && did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
			&& curwin->w_cursor.lnum != end_insert_pos->lnum))
		&& end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
	{
	    pos_T	tpos = curwin->w_cursor;

	    curwin->w_cursor = *end_insert_pos;
	    check_cursor_col();  // make sure it is not past the line
	    for (;;)
	    {
		if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
		    --curwin->w_cursor.col;
		cc = gchar_cursor();
		if (!VIM_ISWHITE(cc))
		    break;
		if (del_char(TRUE) == FAIL)
		    break;  // should not happen
	    }
	    if (curwin->w_cursor.lnum != tpos.lnum)
		curwin->w_cursor = tpos;
	    else
	    {
		// reset tpos, could have been invalidated in the loop above
		tpos = curwin->w_cursor;
		tpos.col++;
		if (cc != NUL && gchar_pos(&tpos) == NUL)
		    ++curwin->w_cursor.col;	// put cursor back on the NUL
	    }

	    // <C-S-Right> may have started Visual mode, adjust the position for
	    // deleted characters.
	    if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
	    {
		int len = (int)STRLEN(ml_get_curline());

		if (VIsual.col > len)
		{
		    VIsual.col = len;
		    VIsual.coladd = 0;
		}
	    }
	}
    }
    did_ai = FALSE;
#ifdef FEAT_SMARTINDENT
    did_si = FALSE;
    can_si = FALSE;
    can_si_back = FALSE;
#endif

    // Set '[ and '] to the inserted text.  When end_insert_pos is NULL we are
    // now in a different buffer.
    if (end_insert_pos != NULL)
    {
	curbuf->b_op_start = Insstart;
	curbuf->b_op_start_orig = Insstart_orig;
	curbuf->b_op_end = *end_insert_pos;
    }
}


static bfd_boolean srec_scan ( bfd * abfd ) {
 int c ;
 unsigned int lineno = 1 ;
 bfd_boolean error = FALSE ;
 bfd_byte * buf = NULL ;
 size_t bufsize = 0 ;
 asection * sec = NULL ;
 char * symbuf = NULL ;
 if ( bfd_seek ( abfd , ( file_ptr ) 0 , SEEK_SET ) != 0 ) goto error_return ;
 while ( ( c = srec_get_byte ( abfd , & error ) ) != EOF ) {
 if ( c != 'S' && c != '\r' && c != '\n' ) sec = NULL ;
 switch ( c ) {
 default : srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 case '\n' : ++ lineno ;
 break ;
 case '\r' : break ;
 case '$' : while ( ( c = srec_get_byte ( abfd , & error ) ) != '\n' && c != EOF ) ;
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 ++ lineno ;
 break ;
 case ' ' : do {
 bfd_size_type alc ;
 char * p , * symname ;
 bfd_vma symval ;
 while ( ( c = srec_get_byte ( abfd , & error ) ) != EOF && ( c == ' ' || c == '\t' ) ) ;
 if ( c == '\n' || c == '\r' ) break ;
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 alc = 10 ;
 symbuf = ( char * ) bfd_malloc ( alc + 1 ) ;
 if ( symbuf == NULL ) goto error_return ;
 p = symbuf ;
 * p ++ = c ;
 while ( ( c = srec_get_byte ( abfd , & error ) ) != EOF && ! ISSPACE ( c ) ) {
 if ( ( bfd_size_type ) ( p - symbuf ) >= alc ) {
 char * n ;
 alc *= 2 ;
 n = ( char * ) bfd_realloc ( symbuf , alc + 1 ) ;
 if ( n == NULL ) goto error_return ;
 p = n + ( p - symbuf ) ;
 symbuf = n ;
 }
 * p ++ = c ;
 }
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 * p ++ = '\0' ;
 symname = ( char * ) bfd_alloc ( abfd , ( bfd_size_type ) ( p - symbuf ) ) ;
 if ( symname == NULL ) goto error_return ;
 strcpy ( symname , symbuf ) ;
 free ( symbuf ) ;
 symbuf = NULL ;
 while ( ( c = srec_get_byte ( abfd , & error ) ) != EOF && ( c == ' ' || c == '\t' ) ) ;
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 if ( c == '$' ) {
 c = srec_get_byte ( abfd , & error ) ;
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 }
 symval = 0 ;
 while ( ISHEX ( c ) ) {
 symval <<= 4 ;
 symval += NIBBLE ( c ) ;
 c = srec_get_byte ( abfd , & error ) ;
 if ( c == EOF ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 }
 if ( ! srec_new_symbol ( abfd , symname , symval ) ) goto error_return ;
 }
 while ( c == ' ' || c == '\t' ) ;
 if ( c == '\n' ) ++ lineno ;
 else if ( c != '\r' ) {
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 break ;
 case 'S' : {
 file_ptr pos ;
 char hdr [ 3 ] ;
 unsigned int bytes , min_bytes ;
 bfd_vma address ;
 bfd_byte * data ;
 unsigned char check_sum ;
 pos = bfd_tell ( abfd ) - 1 ;
 if ( bfd_bread ( hdr , ( bfd_size_type ) 3 , abfd ) != 3 ) goto error_return ;
 if ( ! ISHEX ( hdr [ 1 ] ) || ! ISHEX ( hdr [ 2 ] ) ) {
 if ( ! ISHEX ( hdr [ 1 ] ) ) c = hdr [ 1 ] ;
 else c = hdr [ 2 ] ;
 srec_bad_byte ( abfd , lineno , c , error ) ;
 goto error_return ;
 }
 check_sum = bytes = HEX ( hdr + 1 ) ;
 min_bytes = 3 ;
 if ( hdr [ 0 ] == '2' || hdr [ 0 ] == '8' ) min_bytes = 4 ;
 else if ( hdr [ 0 ] == '3' || hdr [ 0 ] == '7' ) min_bytes = 5 ;
 if ( bytes < min_bytes ) {
 ( * _bfd_error_handler ) ( _ ( "%B:%d: byte count %d too small\n" ) , abfd , lineno , bytes ) ;
 bfd_set_error ( bfd_error_bad_value ) ;
 goto error_return ;
 }
 if ( bytes * 2 > bufsize ) {
 if ( buf != NULL ) free ( buf ) ;
 buf = ( bfd_byte * ) bfd_malloc ( ( bfd_size_type ) bytes * 2 ) ;
 if ( buf == NULL ) goto error_return ;
 bufsize = bytes * 2 ;
 }
 if ( bfd_bread ( buf , ( bfd_size_type ) bytes * 2 , abfd ) != bytes * 2 ) goto error_return ;
 -- bytes ;
 address = 0 ;
 data = buf ;
 switch ( hdr [ 0 ] ) {
 case '0' : case '5' : sec = NULL ;
 break ;
 case '3' : check_sum += HEX ( data ) ;
 address = HEX ( data ) ;
 data += 2 ;
 -- bytes ;
 case '2' : check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 -- bytes ;
 case '1' : check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 bytes -= 2 ;
 if ( sec != NULL && sec -> vma + sec -> size == address ) {
 sec -> size += bytes ;
 }
 else {
 char secbuf [ 20 ] ;
 char * secname ;
 bfd_size_type amt ;
 flagword flags ;
 sprintf ( secbuf , ".sec%d" , bfd_count_sections ( abfd ) + 1 ) ;
 amt = strlen ( secbuf ) + 1 ;
 secname = ( char * ) bfd_alloc ( abfd , amt ) ;
 strcpy ( secname , secbuf ) ;
 flags = SEC_HAS_CONTENTS | SEC_LOAD | SEC_ALLOC ;
 sec = bfd_make_section_with_flags ( abfd , secname , flags ) ;
 if ( sec == NULL ) goto error_return ;
 sec -> vma = address ;
 sec -> lma = address ;
 sec -> size = bytes ;
 sec -> filepos = pos ;
 }
 while ( bytes > 0 ) {
 check_sum += HEX ( data ) ;
 data += 2 ;
 bytes -- ;
 }
 check_sum = 255 - ( check_sum & 0xff ) ;
 if ( check_sum != HEX ( data ) ) {
 ( * _bfd_error_handler ) ( _ ( "%B:%d: Bad checksum in S-record file\n" ) , abfd , lineno ) ;
 bfd_set_error ( bfd_error_bad_value ) ;
 goto error_return ;
 }
 break ;
 case '7' : check_sum += HEX ( data ) ;
 address = HEX ( data ) ;
 data += 2 ;
 case '8' : check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 case '9' : check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 check_sum += HEX ( data ) ;
 address = ( address << 8 ) | HEX ( data ) ;
 data += 2 ;
 abfd -> start_address = address ;
 check_sum = 255 - ( check_sum & 0xff ) ;
 if ( check_sum != HEX ( data ) ) {
 ( * _bfd_error_handler ) ( _ ( "%B:%d: Bad checksum in S-record file\n" ) , abfd , lineno ) ;
 bfd_set_error ( bfd_error_bad_value ) ;
 goto error_return ;
 }
 if ( buf != NULL ) free ( buf ) ;
 return TRUE ;
 }
 }
 break ;
 }
 }
 if ( error ) goto error_return ;
 if ( buf != NULL ) free ( buf ) ;
 return TRUE ;
 error_return : if ( symbuf != NULL ) free ( symbuf ) ;
 if ( buf != NULL ) free ( buf ) ;
 return FALSE ;
 }


void jpc_qmfb_split_col ( jpc_fix_t * a , int numrows , int stride , int parity ) {
 int bufsize = JPC_CEILDIVPOW2 ( numrows , 1 ) ;
 jpc_fix_t splitbuf [ QMFB_SPLITBUFSIZE ] ;
 jpc_fix_t * buf = splitbuf ;
 register jpc_fix_t * srcptr ;
 register jpc_fix_t * dstptr ;
 register int n ;
 register int m ;
 int hstartrow ;
 if ( bufsize > QMFB_SPLITBUFSIZE ) {
 if ( ! ( buf = jas_alloc2 ( bufsize , sizeof ( jpc_fix_t ) ) ) ) {
 abort ( ) ;
 }
 }
 if ( numrows >= 2 ) {
 hstartrow = ( numrows + 1 - parity ) >> 1 ;
 m = numrows - hstartrow ;
 n = m ;
 dstptr = buf ;
 srcptr = & a [ ( 1 - parity ) * stride ] ;
 while ( n -- > 0 ) {
 * dstptr = * srcptr ;
 ++ dstptr ;
 srcptr += stride << 1 ;
 }
 dstptr = & a [ ( 1 - parity ) * stride ] ;
 srcptr = & a [ ( 2 - parity ) * stride ] ;
 n = numrows - m - ( ! parity ) ;
 while ( n -- > 0 ) {
 * dstptr = * srcptr ;
 dstptr += stride ;
 srcptr += stride << 1 ;
 }
 dstptr = & a [ hstartrow * stride ] ;
 srcptr = buf ;
 n = m ;
 while ( n -- > 0 ) {
 * dstptr = * srcptr ;
 dstptr += stride ;
 ++ srcptr ;
 }
 }
 if ( buf != splitbuf ) {
 jas_free ( buf ) ;
 }
 }


static void _slurm_rpc_assoc_mgr_info ( slurm_msg_t * msg ) {
 DEF_TIMERS ;
 char * dump = NULL ;
 int dump_size = 0 ;
 slurm_msg_t response_msg ;
 uid_t uid = g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 START_TIMER ;
 debug2 ( "%s: Processing RPC: REQUEST_ASSOC_MGR_INFO uid=%d" , __func__ , uid ) ;
 assoc_mgr_info_get_pack_msg ( & dump , & dump_size , ( assoc_mgr_info_request_msg_t * ) msg -> data , uid , acct_db_conn , msg -> protocol_version ) ;
 END_TIMER2 ( "_slurm_rpc_assoc_mgr_info" ) ;
 debug2 ( "%s: size=%d %s" , __func__ , dump_size , TIME_STR ) ;
 slurm_msg_t_init ( & response_msg ) ;
 response_msg . flags = msg -> flags ;
 response_msg . protocol_version = msg -> protocol_version ;
 response_msg . address = msg -> address ;
 response_msg . conn = msg -> conn ;
 response_msg . msg_type = RESPONSE_ASSOC_MGR_INFO ;
 response_msg . data = dump ;
 response_msg . data_size = dump_size ;
 slurm_send_node_msg ( msg -> conn_fd , & response_msg ) ;
 xfree ( dump ) ;
 }


static CharDriverState *qemu_chr_open_tty_fd(int fd) { CharDriverState *chr; tty_serial_init(fd, 115200, 'N', 8, 1); chr = qemu_chr_open_fd(fd, fd); chr->chr_ioctl = tty_serial_ioctl; chr->chr_close = qemu_chr_close_tty; return chr; }


static uint16_t shpc_get_status(SHPCDevice *shpc, int slot, uint16_t msk) { uint8_t *status = shpc->config + SHPC_SLOT_STATUS(slot); return (pci_get_word(status) & msk) >> (ffs(msk) - 1); }


main (int argc, char **argv)
{	STATE state ;
	SF_INFO sfinfo ;
	char pathname [512], ext [32], *cptr ;
	int ch, double_split ;

	if (argc != 2)
	{	if (argc != 1)
			puts ("\nError : need a single input file.\n") ;
		usage_exit () ;
		} ;

	memset (&state, 0, sizeof (state)) ;
	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	if ((state.infile = sf_open (argv [1], SFM_READ, &sfinfo)) == NULL)
	{	printf ("\nError : Not able to open input file '%s'\n%s\n", argv [1], sf_strerror (NULL)) ;
		exit (1) ;
		} ;

	if (sfinfo.channels < 2)
	{	printf ("\nError : Input file '%s' only has one channel.\n", argv [1]) ;
		exit (1) ;
		} ;

	state.channels = sfinfo.channels ;
	sfinfo.channels = 1 ;

	if (snprintf (pathname, sizeof (pathname), "%s", argv [1]) > (int) sizeof (pathname))
	{	printf ("\nError : Length of provided filename '%s' exceeds MAX_PATH (%d).\n", argv [1], (int) sizeof (pathname)) ;
		exit (1) ;
		} ;

	if ((cptr = strrchr (pathname, '.')) == NULL)
		ext [0] = 0 ;
	else
	{	snprintf (ext, sizeof (ext), "%s", cptr) ;
		cptr [0] = 0 ;
		} ;

	printf ("Input file : %s\n", pathname) ;
	puts ("Output files :") ;

	for (ch = 0 ; ch < state.channels ; ch++)
	{	char filename [520] ;

		snprintf (filename, sizeof (filename), "%s_%02d%s", pathname, ch, ext) ;

		if ((state.outfile [ch] = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
		{	printf ("Not able to open output file '%s'\n%s\n", filename, sf_strerror (NULL)) ;
			exit (1) ;
			} ;

		printf ("    %s\n", filename) ;
		} ;

	switch (sfinfo.format & SF_FORMAT_SUBMASK)
	{	case SF_FORMAT_FLOAT :
		case SF_FORMAT_DOUBLE :
		case SF_FORMAT_VORBIS :
			double_split = 1 ;
			break ;

		default :
			double_split = 0 ;
			break ;
		} ;

	if (double_split)
		deinterleave_double (&state) ;
	else
		deinterleave_int (&state) ;

	sf_close (state.infile) ;
	for (ch = 0 ; ch < MAX_CHANNELS ; ch++)
		if (state.outfile [ch] != NULL)
			sf_close (state.outfile [ch]) ;

	return 0 ;
} /* main */


static void process_envvars ( enum mode * modep ) {
 char * * runp = _environ ;
 char * envline ;
 enum mode mode = normal ;
 char * debug_output = NULL ;
 GLRO ( dl_profile_output ) = & "/var/tmp\0/var/profile" [ __libc_enable_secure ? 9 : 0 ] ;
 while ( ( envline = _dl_next_ld_env_entry ( & runp ) ) != NULL ) {
 size_t len = 0 ;
 while ( envline [ len ] != '\0' && envline [ len ] != '=' ) ++ len ;
 if ( envline [ len ] != '=' ) continue ;
 switch ( len ) {
 case 4 : if ( memcmp ( envline , "WARN" , 4 ) == 0 ) GLRO ( dl_verbose ) = envline [ 5 ] != '\0' ;
 break ;
 case 5 : if ( memcmp ( envline , "DEBUG" , 5 ) == 0 ) {
 process_dl_debug ( & envline [ 6 ] ) ;
 break ;
 }
 if ( memcmp ( envline , "AUDIT" , 5 ) == 0 ) process_dl_audit ( & envline [ 6 ] ) ;
 break ;
 case 7 : if ( memcmp ( envline , "VERBOSE" , 7 ) == 0 ) {
 version_info = envline [ 8 ] != '\0' ;
 break ;
 }
 if ( memcmp ( envline , "PRELOAD" , 7 ) == 0 ) {
 preloadlist = & envline [ 8 ] ;
 break ;
 }
 if ( memcmp ( envline , "PROFILE" , 7 ) == 0 && envline [ 8 ] != '\0' ) GLRO ( dl_profile ) = & envline [ 8 ] ;
 break ;
 case 8 : if ( memcmp ( envline , "BIND_NOW" , 8 ) == 0 ) {
 GLRO ( dl_lazy ) = envline [ 9 ] == '\0' ;
 break ;
 }
 if ( memcmp ( envline , "BIND_NOT" , 8 ) == 0 ) GLRO ( dl_bind_not ) = envline [ 9 ] != '\0' ;
 break ;
 case 9 : if ( ! __libc_enable_secure && memcmp ( envline , "SHOW_AUXV" , 9 ) == 0 ) _dl_show_auxv ( ) ;
 break ;
 case 10 : if ( memcmp ( envline , "HWCAP_MASK" , 10 ) == 0 ) GLRO ( dl_hwcap_mask ) = __strtoul_internal ( & envline [ 11 ] , NULL , 0 , 0 ) ;
 break ;
 case 11 : if ( ! __libc_enable_secure && memcmp ( envline , "ORIGIN_PATH" , 11 ) == 0 ) GLRO ( dl_origin_path ) = & envline [ 12 ] ;
 break ;
 case 12 : if ( memcmp ( envline , "LIBRARY_PATH" , 12 ) == 0 ) {
 library_path = & envline [ 13 ] ;
 break ;
 }
 if ( memcmp ( envline , "DEBUG_OUTPUT" , 12 ) == 0 ) {
 debug_output = & envline [ 13 ] ;
 break ;
 }
 if ( ! __libc_enable_secure && memcmp ( envline , "DYNAMIC_WEAK" , 12 ) == 0 ) GLRO ( dl_dynamic_weak ) = 1 ;
 break ;
 case 13 : # ifdef EXTRA_LD_ENVVARS_13 EXTRA_LD_ENVVARS_13 # endif if ( ! __libc_enable_secure && memcmp ( envline , "USE_LOAD_BIAS" , 13 ) == 0 ) {
 GLRO ( dl_use_load_bias ) = envline [ 14 ] == '1' ? - 1 : 0 ;
 break ;
 }
 break ;
 case 14 : if ( ! __libc_enable_secure && memcmp ( envline , "PROFILE_OUTPUT" , 14 ) == 0 && envline [ 15 ] != '\0' ) GLRO ( dl_profile_output ) = & envline [ 15 ] ;
 break ;
 case 16 : if ( memcmp ( envline , "TRACE_PRELINKING" , 16 ) == 0 ) {
 mode = trace ;
 GLRO ( dl_verbose ) = 1 ;
 GLRO ( dl_debug_mask ) |= DL_DEBUG_PRELINK ;
 GLRO ( dl_trace_prelink ) = & envline [ 17 ] ;
 }
 break ;
 case 20 : if ( memcmp ( envline , "TRACE_LOADED_OBJECTS" , 20 ) == 0 ) mode = trace ;
 break ;
 # ifdef EXTRA_LD_ENVVARS EXTRA_LD_ENVVARS # endif }
 }
 * modep = mode ;
 if ( __builtin_expect ( __libc_enable_secure , 0 ) ) {
 static const char unsecure_envvars [ ] = # ifdef EXTRA_UNSECURE_ENVVARS EXTRA_UNSECURE_ENVVARS # endif UNSECURE_ENVVARS ;
 const char * nextp ;
 nextp = unsecure_envvars ;
 do {
 unsetenv ( nextp ) ;
 nextp = ( char * ) ( strchr ) ( nextp , '\0' ) + 1 ;
 }
 while ( * nextp != '\0' ) ;
 if ( __access ( "/etc/suid-debug" , F_OK ) != 0 ) {
 unsetenv ( "MALLOC_CHECK_" ) ;
 GLRO ( dl_debug_mask ) = 0 ;
 }
 if ( mode != normal ) _exit ( 5 ) ;
 }
 else if ( any_debug && debug_output != NULL ) {
 # ifdef O_NOFOLLOW const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW ;
 # else const int flags = O_WRONLY | O_APPEND | O_CREAT ;
 # endif size_t name_len = strlen ( debug_output ) ;
 char buf [ name_len + 12 ] ;
 char * startp ;
 buf [ name_len + 11 ] = '\0' ;
 startp = _itoa ( __getpid ( ) , & buf [ name_len + 11 ] , 10 , 0 ) ;
 * -- startp = '.' ;
 startp = memcpy ( startp - name_len , debug_output , name_len ) ;
 GLRO ( dl_debug_fd ) = __open ( startp , flags , DEFFILEMODE ) ;
 if ( GLRO ( dl_debug_fd ) == - 1 ) GLRO ( dl_debug_fd ) = STDOUT_FILENO ;
 }
 }


zsetdevice(i_ctx_t *i_ctx_p)
{
    gx_device *odev = NULL, *dev = gs_currentdevice(igs);
    os_ptr op = osp;
    int code = dev_proc(dev, dev_spec_op)(dev,
                        gxdso_current_output_device, (void *)&odev, 0);

    if (code < 0)
        return code;

    check_write_type(*op, t_device);
    if (odev->LockSafetyParams) {	  /* do additional checking if locked  */
        if(op->value.pdevice != odev) 	  /* don't allow a different device    */
            return_error(gs_error_invalidaccess);
    }
    dev->ShowpageCount = 0;

    if (op->value.pdevice == 0)
        return gs_note_error(gs_error_undefined);

    code = gs_setdevice_no_erase(igs, op->value.pdevice);
    if (code < 0)
        return code;

    make_bool(op, code != 0);	/* erase page if 1 */
    invalidate_stack_devices(i_ctx_p);
    clear_pagedevice(istate);
    return code;
}


static ssize_t mcf_fec_receive(NetClientState *nc, const uint8_t *buf, size_t size) { mcf_fec_state *s = qemu_get_nic_opaque(nc); mcf_fec_bd bd; uint32_t flags = 0; uint32_t addr; uint32_t crc; uint32_t buf_addr; uint8_t *crc_ptr; unsigned int buf_len; size_t retsize; DPRINTF("do_rx len %d\n", size); if (!s->rx_enabled) { return -1; } /* 4 bytes for the CRC. */ size += 4; crc = cpu_to_be32(crc32(~0, buf, size)); crc_ptr = (uint8_t *)&crc; /* Huge frames are truncted. */ if (size > FEC_MAX_FRAME_SIZE) { size = FEC_MAX_FRAME_SIZE; flags |= FEC_BD_TR | FEC_BD_LG; } /* Frames larger than the user limit just set error flags. */ if (size > (s->rcr >> 16)) { flags |= FEC_BD_LG; } addr = s->rx_descriptor; retsize = size; while (size > 0) { mcf_fec_read_bd(&bd, addr); if ((bd.flags & FEC_BD_E) == 0) { /* No descriptors available. Bail out. */ /* FIXME: This is wrong. We should probably either save the remainder for when more RX buffers are available, or flag an error. */ fprintf(stderr, "mcf_fec: Lost end of frame\n"); break; } buf_len = (size <= s->emrbr) ? size: s->emrbr; bd.length = buf_len; size -= buf_len; DPRINTF("rx_bd %x length %d\n", addr, bd.length); /* The last 4 bytes are the CRC. */ if (size < 4) buf_len += size - 4; buf_addr = bd.data; cpu_physical_memory_write(buf_addr, buf, buf_len); buf += buf_len; if (size < 4) { cpu_physical_memory_write(buf_addr + buf_len, crc_ptr, 4 - size); crc_ptr += 4 - size; } bd.flags &= ~FEC_BD_E; if (size == 0) { /* Last buffer in frame. */ bd.flags |= flags | FEC_BD_L; DPRINTF("rx frame flags %04x\n", bd.flags); s->eir |= FEC_INT_RXF; } else { s->eir |= FEC_INT_RXB; } mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->erdsr; } else { addr += 8; } } s->rx_descriptor = addr; mcf_fec_enable_rx(s); mcf_fec_update(s); return retsize; }


void check_file_actlst(int *ifd, char *dfile, struct activity *act[],
		       struct file_magic *file_magic, struct file_header *file_hdr,
		       struct file_activity **file_actlst, unsigned int id_seq[],
		       int ignore, int *endian_mismatch, int *arch_64)
{
	int i, j, k, p;
	struct file_activity *fal;
	void *buffer = NULL;

	/* Open sa data file and read its magic structure */
	if (sa_open_read_magic(ifd, dfile, file_magic, ignore, endian_mismatch, TRUE) < 0)
		/*
		 * Not current sysstat's format.
		 * Return now so that sadf -H can display at least
		 * file's version and magic number.
		 */
		return;

	/*
	 * We know now that we have a *compatible* sysstat datafile format
	 * (correct FORMAT_MAGIC value), and in this case, we should have
	 * checked header_size value. Anyway, with a corrupted datafile,
	 * this may not be the case. So check again.
	 */
	if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||
	    (file_magic->header_size > MAX_FILE_HEADER_SIZE)) {
#ifdef DEBUG
		fprintf(stderr, "%s: header_size=%u\n",
			__FUNCTION__, file_magic->header_size);
#endif
		goto format_error;
	}

	/* Allocate buffer for file_header structure */
	SREALLOC(buffer, char, file_magic->header_size);

	/* Read sa data file standard header and allocate activity list */
	sa_fread(*ifd, buffer, (size_t) file_magic->header_size, HARD_SIZE, UEOF_STOP);
	/*
	 * Data file header size (file_magic->header_size) may be greater or
	 * smaller than FILE_HEADER_SIZE. Remap the fields of the file header
	 * then copy its contents to the expected  structure.
	 */
	remap_struct(hdr_types_nr, file_magic->hdr_types_nr, buffer,
		     file_magic->header_size, FILE_HEADER_SIZE);
	memcpy(file_hdr, buffer, FILE_HEADER_SIZE);
	free(buffer);
	buffer = NULL;

	/* Tell that data come from a 64 bit machine */
	*arch_64 = (file_hdr->sa_sizeof_long == SIZEOF_LONG_64BIT);

	/* Normalize endianness for file_hdr structure */
	if (*endian_mismatch) {
		swap_struct(hdr_types_nr, file_hdr, *arch_64);
	}

	/*
	 * Sanity checks.
	 * NB: Compare against MAX_NR_ACT and not NR_ACT because
	 * we are maybe reading a datafile from a future sysstat version
	 * with more activities than known today.
	 */
	if ((file_hdr->sa_act_nr > MAX_NR_ACT) ||
	    (file_hdr->act_size > MAX_FILE_ACTIVITY_SIZE) ||
	    (file_hdr->rec_size > MAX_RECORD_HEADER_SIZE) ||
	    (MAP_SIZE(file_hdr->act_types_nr) > file_hdr->act_size) ||
	    (MAP_SIZE(file_hdr->rec_types_nr) > file_hdr->rec_size)) {
#ifdef DEBUG
		fprintf(stderr, "%s: sa_act_nr=%d act_size=%u rec_size=%u map_size(act)=%u map_size(rec)=%u\n",
			__FUNCTION__, file_hdr->sa_act_nr, file_hdr->act_size, file_hdr->rec_size,
			MAP_SIZE(file_hdr->act_types_nr), MAP_SIZE(file_hdr->rec_types_nr));
#endif
		/* Maybe a "false positive" sysstat datafile? */
		goto format_error;
	}

	SREALLOC(buffer, char, file_hdr->act_size);
	SREALLOC(*file_actlst, struct file_activity, FILE_ACTIVITY_SIZE * file_hdr->sa_act_nr);
	fal = *file_actlst;

	/* Read activity list */
	j = 0;
	for (i = 0; i < file_hdr->sa_act_nr; i++, fal++) {

		/* Read current file_activity structure from file */
		sa_fread(*ifd, buffer, (size_t) file_hdr->act_size, HARD_SIZE, UEOF_STOP);
		/*
		* Data file_activity size (file_hdr->act_size) may be greater or
		* smaller than FILE_ACTIVITY_SIZE. Remap the fields of the file's structure
		* then copy its contents to the expected structure.
		*/
		remap_struct(act_types_nr, file_hdr->act_types_nr, buffer,
			     file_hdr->act_size, FILE_ACTIVITY_SIZE);
		memcpy(fal, buffer, FILE_ACTIVITY_SIZE);

		/* Normalize endianness for file_activity structures */
		if (*endian_mismatch) {
			swap_struct(act_types_nr, fal, *arch_64);
		}

		/*
		 * Every activity, known or unknown, should have
		 * at least one item and sub-item.
		 * Also check that the number of items and sub-items
		 * doesn't exceed a max value. This is necessary
		 * because we will use @nr and @nr2 to
		 * allocate memory to read the file contents. So we
		 * must make sure the file is not corrupted.
		 * NB: Another check will be made below for known
		 * activities which have each a specific max value.
		 */
		if ((fal->nr < 1) || (fal->nr2 < 1) ||
		    (fal->nr > NR_MAX) || (fal->nr2 > NR2_MAX)) {
#ifdef DEBUG
			fprintf(stderr, "%s: id=%d nr=%d nr2=%d\n",
				__FUNCTION__, fal->id, fal->nr, fal->nr2);
#endif
			goto format_error;
		}

		if ((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0)
			/* Unknown activity */
			continue;

		if (act[p]->magic != fal->magic) {
			/* Bad magical number */
			if (ignore) {
				/*
				 * This is how sadf -H knows that this
				 * activity has an unknown format.
				 */
				act[p]->magic = ACTIVITY_MAGIC_UNKNOWN;
			}
			else
				continue;
		}

		/* Check max value for known activities */
		if (fal->nr > act[p]->nr_max) {
#ifdef DEBUG
			fprintf(stderr, "%s: id=%d nr=%d nr_max=%d\n",
				__FUNCTION__, fal->id, fal->nr, act[p]->nr_max);
#endif
			goto format_error;
		}

		/*
		 * Number of fields of each type ("long long", or "long"
		 * or "int") composing the structure with statistics may
		 * only increase with new sysstat versions. Here, we may
		 * be reading a file created by current sysstat version,
		 * or by an older or a newer version.
		 */
		if (!(((fal->types_nr[0] >= act[p]->gtypes_nr[0]) &&
		     (fal->types_nr[1] >= act[p]->gtypes_nr[1]) &&
		     (fal->types_nr[2] >= act[p]->gtypes_nr[2]))
		     ||
		     ((fal->types_nr[0] <= act[p]->gtypes_nr[0]) &&
		     (fal->types_nr[1] <= act[p]->gtypes_nr[1]) &&
		     (fal->types_nr[2] <= act[p]->gtypes_nr[2]))) && !ignore) {
#ifdef DEBUG
			fprintf(stderr, "%s: id=%d file=%d,%d,%d activity=%d,%d,%d\n",
				__FUNCTION__, fal->id, fal->types_nr[0], fal->types_nr[1], fal->types_nr[2],
				act[p]->gtypes_nr[0], act[p]->gtypes_nr[1], act[p]->gtypes_nr[2]);
#endif
			goto format_error;
		}

		if (MAP_SIZE(fal->types_nr) > fal->size) {
#ifdef DEBUG
		fprintf(stderr, "%s: id=%d size=%u map_size=%u\n",
			__FUNCTION__, fal->id, fal->size, MAP_SIZE(fal->types_nr));
#endif
			goto format_error;
		}

		for (k = 0; k < 3; k++) {
			act[p]->ftypes_nr[k] = fal->types_nr[k];
		}

		if (fal->size > act[p]->msize) {
			act[p]->msize = fal->size;
		}

		act[p]->nr_ini = fal->nr;
		act[p]->nr2    = fal->nr2;
		act[p]->fsize  = fal->size;
		/*
		 * This is a known activity with a known format
		 * (magical number). Only such activities will be displayed.
		 * (Well, this may also be an unknown format if we have entered sadf -H.)
		 */
		id_seq[j++] = fal->id;
	}

	while (j < NR_ACT) {
		id_seq[j++] = 0;
	}

	free(buffer);

	/* Check that at least one activity selected by the user is available in file */
	for (i = 0; i < NR_ACT; i++) {

		if (!IS_SELECTED(act[i]->options))
			continue;

		/* Here is a selected activity: Does it exist in file? */
		fal = *file_actlst;
		for (j = 0; j < file_hdr->sa_act_nr; j++, fal++) {
			if (act[i]->id == fal->id)
				break;
		}
		if (j == file_hdr->sa_act_nr) {
			/* No: Unselect it */
			act[i]->options &= ~AO_SELECTED;
		}
	}

	/*
	 * None of selected activities exist in file: Abort.
	 * NB: Error is ignored if we only want to display
	 * datafile header (sadf -H).
	 */
	if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES) && !ignore) {
		fprintf(stderr, _("Requested activities not available in file %s\n"),
			dfile);
		close(*ifd);
		exit(1);
	}

	return;

format_error:
	if (buffer) {
		free(buffer);
	}
	handle_invalid_sa_file(*ifd, file_magic, dfile, 0);
}


static void update_golden_frame_stats ( VP8_COMP * cpi ) {
 VP8_COMMON * cm = & cpi -> common ;
 if ( cm -> refresh_golden_frame ) {
 if ( ! cpi -> auto_gold ) cpi -> frames_till_gf_update_due = DEFAULT_GF_INTERVAL ;
 if ( ( cpi -> pass != 2 ) && ( cpi -> frames_till_gf_update_due > 0 ) ) {
 cpi -> current_gf_interval = cpi -> frames_till_gf_update_due ;
 if ( ( cm -> frame_type != KEY_FRAME ) && ! cpi -> source_alt_ref_active ) {
 cpi -> gf_overspend_bits += ( cpi -> projected_frame_size - cpi -> inter_frame_target ) ;
 }
 cpi -> non_gf_bitrate_adjustment = cpi -> gf_overspend_bits / cpi -> frames_till_gf_update_due ;
 }
 vpx_memset ( cpi -> gf_active_flags , 1 , ( cm -> mb_rows * cm -> mb_cols ) ) ;
 cpi -> gf_active_count = cm -> mb_rows * cm -> mb_cols ;
 cm -> refresh_golden_frame = 0 ;
 cpi -> frames_since_golden = 0 ;
 cpi -> recent_ref_frame_usage [ INTRA_FRAME ] = 1 ;
 cpi -> recent_ref_frame_usage [ LAST_FRAME ] = 1 ;
 cpi -> recent_ref_frame_usage [ GOLDEN_FRAME ] = 1 ;
 cpi -> recent_ref_frame_usage [ ALTREF_FRAME ] = 1 ;
 if ( cpi -> oxcf . fixed_q >= 0 && cpi -> oxcf . play_alternate && ! cpi -> common . refresh_alt_ref_frame ) {
 cpi -> source_alt_ref_pending = 1 ;
 cpi -> frames_till_gf_update_due = cpi -> baseline_gf_interval ;
 }
 if ( ! cpi -> source_alt_ref_pending ) cpi -> source_alt_ref_active = 0 ;
 if ( cpi -> frames_till_gf_update_due > 0 ) cpi -> frames_till_gf_update_due -- ;
 }
 else if ( ! cpi -> common . refresh_alt_ref_frame ) {
 if ( cpi -> frames_till_gf_update_due > 0 ) cpi -> frames_till_gf_update_due -- ;
 if ( cpi -> frames_till_alt_ref_frame ) cpi -> frames_till_alt_ref_frame -- ;
 cpi -> frames_since_golden ++ ;
 if ( cpi -> frames_since_golden > 1 ) {
 cpi -> recent_ref_frame_usage [ INTRA_FRAME ] += cpi -> mb . count_mb_ref_frame_usage [ INTRA_FRAME ] ;
 cpi -> recent_ref_frame_usage [ LAST_FRAME ] += cpi -> mb . count_mb_ref_frame_usage [ LAST_FRAME ] ;
 cpi -> recent_ref_frame_usage [ GOLDEN_FRAME ] += cpi -> mb . count_mb_ref_frame_usage [ GOLDEN_FRAME ] ;
 cpi -> recent_ref_frame_usage [ ALTREF_FRAME ] += cpi -> mb . count_mb_ref_frame_usage [ ALTREF_FRAME ] ;
 }
 }
 }


spell_dump_compl(
    char_u	*pat,	    // leading part of the word
    int		ic,	    // ignore case
    int		*dir,	    // direction for adding matches
    int		dumpflags_arg)	// DUMPFLAG_*
{
    langp_T	*lp;
    slang_T	*slang;
    idx_T	arridx[MAXWLEN];
    int		curi[MAXWLEN];
    char_u	word[MAXWLEN];
    int		c;
    char_u	*byts;
    idx_T	*idxs;
    linenr_T	lnum = 0;
    int		round;
    int		depth;
    int		n;
    int		flags;
    char_u	*region_names = NULL;	    // region names being used
    int		do_region = TRUE;	    // dump region names and numbers
    char_u	*p;
    int		lpi;
    int		dumpflags = dumpflags_arg;
    int		patlen;

    // When ignoring case or when the pattern starts with capital pass this on
    // to dump_word().
    if (pat != NULL)
    {
	if (ic)
	    dumpflags |= DUMPFLAG_ICASE;
	else
	{
	    n = captype(pat, NULL);
	    if (n == WF_ONECAP)
		dumpflags |= DUMPFLAG_ONECAP;
	    else if (n == WF_ALLCAP && (int)STRLEN(pat) > mb_ptr2len(pat))
		dumpflags |= DUMPFLAG_ALLCAP;
	}
    }

    // Find out if we can support regions: All languages must support the same
    // regions or none at all.
    for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
    {
	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
	p = lp->lp_slang->sl_regions;
	if (p[0] != 0)
	{
	    if (region_names == NULL)	    // first language with regions
		region_names = p;
	    else if (STRCMP(region_names, p) != 0)
	    {
		do_region = FALSE;	    // region names are different
		break;
	    }
	}
    }

    if (do_region && region_names != NULL)
    {
	if (pat == NULL)
	{
	    vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names);
	    ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
	}
    }
    else
	do_region = FALSE;

    /*
     * Loop over all files loaded for the entries in 'spelllang'.
     */
    for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
    {
	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
	slang = lp->lp_slang;
	if (slang->sl_fbyts == NULL)	    // reloading failed
	    continue;

	if (pat == NULL)
	{
	    vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname);
	    ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
	}

	// When matching with a pattern and there are no prefixes only use
	// parts of the tree that match "pat".
	if (pat != NULL && slang->sl_pbyts == NULL)
	    patlen = (int)STRLEN(pat);
	else
	    patlen = -1;

	// round 1: case-folded tree
	// round 2: keep-case tree
	for (round = 1; round <= 2; ++round)
	{
	    if (round == 1)
	    {
		dumpflags &= ~DUMPFLAG_KEEPCASE;
		byts = slang->sl_fbyts;
		idxs = slang->sl_fidxs;
	    }
	    else
	    {
		dumpflags |= DUMPFLAG_KEEPCASE;
		byts = slang->sl_kbyts;
		idxs = slang->sl_kidxs;
	    }
	    if (byts == NULL)
		continue;		// array is empty

	    depth = 0;
	    arridx[0] = 0;
	    curi[0] = 1;
	    while (depth >= 0 && !got_int
				  && (pat == NULL || !ins_compl_interrupted()))
	    {
		if (curi[depth] > byts[arridx[depth]])
		{
		    // Done all bytes at this node, go up one level.
		    --depth;
		    line_breakcheck();
		    ins_compl_check_keys(50, FALSE);
		}
		else
		{
		    // Do one more byte at this node.
		    n = arridx[depth] + curi[depth];
		    ++curi[depth];
		    c = byts[n];
		    if (c == 0)
		    {
			// End of word, deal with the word.
			// Don't use keep-case words in the fold-case tree,
			// they will appear in the keep-case tree.
			// Only use the word when the region matches.
			flags = (int)idxs[n];
			if ((round == 2 || (flags & WF_KEEPCAP) == 0)
				&& (flags & WF_NEEDCOMP) == 0
				&& (do_region
				    || (flags & WF_REGION) == 0
				    || (((unsigned)flags >> 16)
						       & lp->lp_region) != 0))
			{
			    word[depth] = NUL;
			    if (!do_region)
				flags &= ~WF_REGION;

			    // Dump the basic word if there is no prefix or
			    // when it's the first one.
			    c = (unsigned)flags >> 24;
			    if (c == 0 || curi[depth] == 2)
			    {
				dump_word(slang, word, pat, dir,
						      dumpflags, flags, lnum);
				if (pat == NULL)
				    ++lnum;
			    }

			    // Apply the prefix, if there is one.
			    if (c != 0)
				lnum = dump_prefixes(slang, word, pat, dir,
						      dumpflags, flags, lnum);
			}
		    }
		    else
		    {
			// Normal char, go one level deeper.
			word[depth++] = c;
			arridx[depth] = idxs[n];
			curi[depth] = 1;

			// Check if this character matches with the pattern.
			// If not skip the whole tree below it.
			// Always ignore case here, dump_word() will check
			// proper case later.  This isn't exactly right when
			// length changes for multi-byte characters with
			// ignore case...
			if (depth <= patlen
					&& MB_STRNICMP(word, pat, depth) != 0)
			    --depth;
		    }
		}
	    }
	}
    }
}


static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint32_t type; uint32_t av_unused ctype; int64_t title_size; char *title_str; if (c->fc->nb_streams < 1) // meta before first trak return 0; st = c->fc->streams[c->fc->nb_streams-1]; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ /* component type */ ctype = avio_rl32(pb); type = avio_rl32(pb); /* component subtype */ av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype); av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type); if (type == MKTAG('v','i','d','e')) st->codec->codec_type = AVMEDIA_TYPE_VIDEO; else if (type == MKTAG('s','o','u','n')) st->codec->codec_type = AVMEDIA_TYPE_AUDIO; else if (type == MKTAG('m','1','a',' ')) st->codec->codec_id = AV_CODEC_ID_MP2; else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p'))) st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE; avio_rb32(pb); /* component manufacture */ avio_rb32(pb); /* component flags */ avio_rb32(pb); /* component flags mask */ title_size = atom.size - 24; if (title_size > 0) { title_str = av_malloc(title_size + 1); /* Add null terminator */ if (!title_str) return AVERROR(ENOMEM); avio_read(pb, title_str, title_size); title_str[title_size] = 0; if (title_str[0]) { int off = (!c->isom && title_str[0] == title_size - 1); av_dict_set(&st->metadata, "handler_name", title_str + off, 0); } av_freep(&title_str); } return 0; }


static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
{
	if (!cmd->argv[0])
		die("BUG: command is empty");

	/*
	 * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
	 * attempt to interpret the command with 'sh'.
	 */
	argv_array_push(out, SHELL_PATH);

	if (cmd->git_cmd) {
		argv_array_push(out, "git");
		argv_array_pushv(out, cmd->argv);
	} else if (cmd->use_shell) {
		prepare_shell_cmd(out, cmd->argv);
	} else {
		argv_array_pushv(out, cmd->argv);
	}

	/*
	 * If there are no '/' characters in the command then perform a path
	 * lookup and use the resolved path as the command to exec.  If there
	 * are no '/' characters or if the command wasn't found in the path,
	 * have exec attempt to invoke the command directly.
	 */
	if (!strchr(out->argv[1], '/')) {
		char *program = locate_in_PATH(out->argv[1]);
		if (program) {
			free((char *)out->argv[1]);
			out->argv[1] = program;
		}
	}
}


aio_read_done(void *opaque, int ret) { struct aio_ctx *ctx = opaque; struct timeval t2; gettimeofday(&t2, NULL); if (ret < 0) { printf("readv failed: %s\n", strerror(-ret)); return; } if (ctx->Pflag) { void *cmp_buf = malloc(ctx->qiov.size); memset(cmp_buf, ctx->pattern, ctx->qiov.size); if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) { printf("Pattern verification failed at offset %lld, " "%zd bytes\n", (long long) ctx->offset, ctx->qiov.size); } free(cmp_buf); } if (ctx->qflag) { return; } if (ctx->vflag) { dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size); } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, ctx->t1); print_report("read", &t2, ctx->offset, ctx->qiov.size, ctx->qiov.size, 1, ctx->Cflag); qemu_io_free(ctx->buf); free(ctx); }


void helper_retry(void) { env->pc = env->tsptr->tpc; env->npc = env->tsptr->tnpc; PUT_CCR(env, env->tsptr->tstate >> 32); env->asi = (env->tsptr->tstate >> 24) & 0xff; change_pstate((env->tsptr->tstate >> 8) & 0xf3f); PUT_CWP64(env, env->tsptr->tstate & 0xff); env->tl--; env->tsptr = &env->ts[env->tl & MAXTL_MASK]; }


static void dispatch_message_real(
                Server *s,
                struct iovec *iovec, size_t n, size_t m,
                const ClientContext *c,
                const struct timeval *tv,
                int priority,
                pid_t object_pid) {

        char source_time[sizeof("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)];
        uid_t journal_uid;
        ClientContext *o;

        assert(s);
        assert(iovec);
        assert(n > 0);
        assert(n +
               N_IOVEC_META_FIELDS +
               (pid_is_valid(object_pid) ? N_IOVEC_OBJECT_FIELDS : 0) +
               client_context_extra_fields_n_iovec(c) <= m);

        if (c) {
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->pid, pid_t, pid_is_valid, PID_FMT, "_PID");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->uid, uid_t, uid_is_valid, UID_FMT, "_UID");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->gid, gid_t, gid_is_valid, GID_FMT, "_GID");

                IOVEC_ADD_STRING_FIELD(iovec, n, c->comm, "_COMM");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->exe, "_EXE");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->cmdline, "_CMDLINE");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->capeff, "_CAP_EFFECTIVE");

                IOVEC_ADD_SIZED_FIELD(iovec, n, c->label, c->label_size, "_SELINUX_CONTEXT");

                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "_AUDIT_SESSION");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->loginuid, uid_t, uid_is_valid, UID_FMT, "_AUDIT_LOGINUID");

                IOVEC_ADD_STRING_FIELD(iovec, n, c->cgroup, "_SYSTEMD_CGROUP");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->session, "_SYSTEMD_SESSION");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->owner_uid, uid_t, uid_is_valid, UID_FMT, "_SYSTEMD_OWNER_UID");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->unit, "_SYSTEMD_UNIT");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->user_unit, "_SYSTEMD_USER_UNIT");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->slice, "_SYSTEMD_SLICE");
                IOVEC_ADD_STRING_FIELD(iovec, n, c->user_slice, "_SYSTEMD_USER_SLICE");

                IOVEC_ADD_ID128_FIELD(iovec, n, c->invocation_id, "_SYSTEMD_INVOCATION_ID");

                if (c->extra_fields_n_iovec > 0) {
                        memcpy(iovec + n, c->extra_fields_iovec, c->extra_fields_n_iovec * sizeof(struct iovec));
                        n += c->extra_fields_n_iovec;
                }
        }

        assert(n <= m);

        if (pid_is_valid(object_pid) && client_context_get(s, object_pid, NULL, NULL, 0, NULL, &o) >= 0) {

                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->pid, pid_t, pid_is_valid, PID_FMT, "OBJECT_PID");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_UID");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->gid, gid_t, gid_is_valid, GID_FMT, "OBJECT_GID");

                IOVEC_ADD_STRING_FIELD(iovec, n, o->comm, "OBJECT_COMM");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->exe, "OBJECT_EXE");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->cmdline, "OBJECT_CMDLINE");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->capeff, "OBJECT_CAP_EFFECTIVE");

                IOVEC_ADD_SIZED_FIELD(iovec, n, o->label, o->label_size, "OBJECT_SELINUX_CONTEXT");

                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "OBJECT_AUDIT_SESSION");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->loginuid, uid_t, uid_is_valid, UID_FMT, "OBJECT_AUDIT_LOGINUID");

                IOVEC_ADD_STRING_FIELD(iovec, n, o->cgroup, "OBJECT_SYSTEMD_CGROUP");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->session, "OBJECT_SYSTEMD_SESSION");
                IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->owner_uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_SYSTEMD_OWNER_UID");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->unit, "OBJECT_SYSTEMD_UNIT");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->user_unit, "OBJECT_SYSTEMD_USER_UNIT");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->slice, "OBJECT_SYSTEMD_SLICE");
                IOVEC_ADD_STRING_FIELD(iovec, n, o->user_slice, "OBJECT_SYSTEMD_USER_SLICE");

                IOVEC_ADD_ID128_FIELD(iovec, n, o->invocation_id, "OBJECT_SYSTEMD_INVOCATION_ID=");
        }

        assert(n <= m);

        if (tv) {
                sprintf(source_time, "_SOURCE_REALTIME_TIMESTAMP=" USEC_FMT, timeval_load(tv));
                iovec[n++] = IOVEC_MAKE_STRING(source_time);
        }

        /* Note that strictly speaking storing the boot id here is
         * redundant since the entry includes this in-line
         * anyway. However, we need this indexed, too. */
        if (!isempty(s->boot_id_field))
                iovec[n++] = IOVEC_MAKE_STRING(s->boot_id_field);

        if (!isempty(s->machine_id_field))
                iovec[n++] = IOVEC_MAKE_STRING(s->machine_id_field);

        if (!isempty(s->hostname_field))
                iovec[n++] = IOVEC_MAKE_STRING(s->hostname_field);

        assert(n <= m);

        if (s->split_mode == SPLIT_UID && c && uid_is_valid(c->uid))
                /* Split up strictly by (non-root) UID */
                journal_uid = c->uid;
        else if (s->split_mode == SPLIT_LOGIN && c && c->uid > 0 && uid_is_valid(c->owner_uid))
                /* Split up by login UIDs.  We do this only if the
                 * realuid is not root, in order not to accidentally
                 * leak privileged information to the user that is
                 * logged by a privileged process that is part of an
                 * unprivileged session. */
                journal_uid = c->owner_uid;
        else
                journal_uid = 0;

        write_to_journal(s, journal_uid, iovec, n, priority);


static int process_http_upload(
                struct MHD_Connection *connection,
                const char *upload_data,
                size_t *upload_data_size,
                RemoteSource *source) {

        bool finished = false;
        size_t remaining;
        int r;

        assert(source);

        log_trace("%s: connection %p, %zu bytes",
                  __func__, connection, *upload_data_size);

        if (*upload_data_size) {
                log_trace("Received %zu bytes", *upload_data_size);

                r = journal_importer_push_data(&source->importer,
                                               upload_data, *upload_data_size);
                if (r < 0)
                        return mhd_respond_oom(connection);

                *upload_data_size = 0;
        } else
                finished = true;

        for (;;) {
                r = process_source(source,
                                   journal_remote_server_global->compress,
                                   journal_remote_server_global->seal);
                if (r == -EAGAIN)
                        break;
                if (r < 0) {
                        if (r == -E2BIG)
                                log_warning_errno(r, "Entry is too above maximum of %u, aborting connection %p.",
                                                  DATA_SIZE_MAX, connection);
                        else
                                log_warning_errno(r, "Failed to process data, aborting connection %p: %m",
                                                  connection);
                        return MHD_NO;
                }
        }

        if (!finished)
                return MHD_YES;

        /* The upload is finished */

        remaining = journal_importer_bytes_remaining(&source->importer);
        if (remaining > 0) {
                log_warning("Premature EOF byte. %zu bytes lost.", remaining);
                return mhd_respondf(connection,
                                    0, MHD_HTTP_EXPECTATION_FAILED,
                                    "Premature EOF. %zu bytes of trailing data not processed.",
                                    remaining);
        }

        return mhd_respond(connection, MHD_HTTP_ACCEPTED, "OK.");
};


regtilde(char_u *source, int magic)
{
    char_u	*newsub = source;
    char_u	*tmpsub;
    char_u	*p;
    int		len;
    int		prevlen;

    for (p = newsub; *p; ++p)
    {
	if ((*p == '~' && magic) || (*p == '\\' && *(p + 1) == '~' && !magic))
	{
	    if (reg_prev_sub != NULL)
	    {
		// length = len(newsub) - 1 + len(prev_sub) + 1
		prevlen = (int)STRLEN(reg_prev_sub);
		tmpsub = alloc(STRLEN(newsub) + prevlen);
		if (tmpsub != NULL)
		{
		    // copy prefix
		    len = (int)(p - newsub);	// not including ~
		    mch_memmove(tmpsub, newsub, (size_t)len);
		    // interpret tilde
		    mch_memmove(tmpsub + len, reg_prev_sub, (size_t)prevlen);
		    // copy postfix
		    if (!magic)
			++p;			// back off backslash
		    STRCPY(tmpsub + len + prevlen, p + 1);

		    if (newsub != source)	// already allocated newsub
			vim_free(newsub);
		    newsub = tmpsub;
		    p = newsub + len + prevlen;
		}
	    }
	    else if (magic)
		STRMOVE(p, p + 1);	// remove '~'
	    else
		STRMOVE(p, p + 2);	// remove '\~'
	    --p;
	}
	else
	{
	    if (*p == '\\' && p[1])		// skip escaped characters
		++p;
	    if (has_mbyte)
		p += (*mb_ptr2len)(p) - 1;
	}
    }

    vim_free(reg_prev_sub);
    if (newsub != source)	// newsub was allocated, just keep it
	reg_prev_sub = newsub;
    else			// no ~ found, need to save newsub
	reg_prev_sub = vim_strsave(newsub);
    return newsub;
}


znumicc_components(i_ctx_t * i_ctx_p)
{
    ref *                   pnval;
    ref *                   pstrmval;
    stream *                s;
    int                     ncomps, expected = 0, code;
    cmm_profile_t           *picc_profile;
    os_ptr                  op = osp;

    check_type(*op, t_dictionary);
    check_dict_read(*op);

    code = dict_find_string(op, "N", &pnval);
    if (code < 0)
        return code;
    if (code == 0)
        return_error(gs_error_undefined);
    ncomps = pnval->value.intval;
    /* verify the DataSource entry. Create profile from stream */
    if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
        return_error(gs_error_undefined);
    check_read_file(i_ctx_p, s, pstrmval);

    picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0);
    if (picc_profile == NULL)
        return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");

    picc_profile->num_comps = ncomps;
    picc_profile->profile_handle =
        gsicc_get_profile_handle_buffer(picc_profile->buffer,
                                        picc_profile->buffer_size,
                                        gs_gstate_memory(igs));
    if (picc_profile->profile_handle == NULL) {
        rc_decrement(picc_profile,"znumicc_components");
        make_int(op, expected);
        return 0;
    }
    picc_profile->data_cs =
        gscms_get_profile_data_space(picc_profile->profile_handle,
            picc_profile->memory);

    switch (picc_profile->data_cs) {
        case gsCIEXYZ:
        case gsCIELAB:
        case gsRGB:
            expected = 3;
            break;
        case gsGRAY:
            expected = 1;
            break;
        case gsCMYK:
            expected = 4;
            break;
        case gsNCHANNEL:
            expected = 0;
            break;
        case gsNAMED:
        case gsUNDEFINED:
            expected = -1;
            break;
    }

    make_int(op, expected);

    rc_decrement(picc_profile,"zset_outputintent");
    return 0;
}


static void coroutine_delete(Coroutine *co) { if (CONFIG_COROUTINE_POOL) { qemu_mutex_lock(&pool_lock); if (pool_size < pool_max_size) { QSLIST_INSERT_HEAD(&pool, co, pool_next); co->caller = NULL; pool_size++; qemu_mutex_unlock(&pool_lock); return; } qemu_mutex_unlock(&pool_lock); } qemu_coroutine_delete(co); }


static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop) { cirrus_fill_t rop_func; if (blit_is_unsafe(s, true)) { return 0; } rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1]; rop_func(s, s->vga.vram_ptr + s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_bitblt_reset(s); return 1; }