Пример #1
0
void check_add_file(char *filename)
{
	const char *bn;

	if (filename == NULL || *filename == '\0')
		return;

	if (access(filename, R_OK) < 0) {
		warn("could not open file: %s", filename);
		return;
	}

	if (fileidx == filecnt) {
		filecnt *= 2;
		files = (fileinfo_t*) s_realloc(files, filecnt * sizeof(fileinfo_t));
	}

#if defined _BSD_SOURCE || defined _XOPEN_SOURCE && \
    ((_XOPEN_SOURCE - 0) >= 500 || defined _XOPEN_SOURCE_EXTENDED)

	if ((files[fileidx].path = realpath(filename, NULL)) == NULL) {
		warn("could not get real path of file: %s\n", filename);
		return;
	}
#else
	if (*filename != '/') {
		if ((files[fileidx].path = absolute_path(filename)) == NULL) {
			warn("could not get absolute path of file: %s\n", filename);
			return;
		}
	} else {
		files[fileidx].path = NULL;
	}
#endif

	files[fileidx].loaded = false;
	files[fileidx].name = s_strdup(filename);
	if (files[fileidx].path == NULL)
		files[fileidx].path = files[fileidx].name;
	if ((bn = strrchr(files[fileidx].name , '/')) != NULL && bn[1] != '\0')
		files[fileidx].base = ++bn;
	else
		files[fileidx].base = files[fileidx].name;
	fileidx++;
}
Пример #2
0
GAULFUNC char *ga_chromosome_list_to_string(
                              const population *pop, const entity *joe,
                              char *text, size_t *textlen)
  {

  if (!pop) die("Null pointer to population structure passed.");
  if (!joe) die("Null pointer to entity structure passed.");

  if (!text || *textlen < 14)
    {
    *textlen = 14;
    text = s_realloc(text, sizeof(char) * *textlen);
    }

  strncpy(text, "<unavailable>", 14);

  return text;
  }
Пример #3
0
/* Enlarge the free space at the end of the sds string so that the caller
 * is sure that after calling this function can overwrite up to addlen
 * bytes after the end of the string, plus one more byte for nul term.
 *
 * Note: this does not change the *length* of the sds string as returned
 * by sdslen(), but only the free buffer space we have. */
sds sdsMakeRoomFor(sds s, size_t addlen) {
    void *sh, *newsh;
    size_t avail = sdsavail(s);
    size_t len, newlen;
    char type, oldtype = s[-1] & SDS_TYPE_MASK;
    int hdrlen;

    /* Return ASAP if there is enough space left. */
    if (avail >= addlen) return s;

    len = sdslen(s);
    sh = (char*)s-sdsHdrSize(oldtype);
    newlen = (len+addlen);
    if (newlen < SDS_MAX_PREALLOC)
        newlen *= 2;
    else
        newlen += SDS_MAX_PREALLOC;

    type = sdsReqType(newlen);

    /* Don't use type 5: the user is appending to the string and type 5 is
     * not able to remember empty space, so sdsMakeRoomFor() must be called
     * at every appending operation. */
    if (type == SDS_TYPE_5) type = SDS_TYPE_8;

    hdrlen = sdsHdrSize(type);
    if (oldtype==type) {
        newsh = s_realloc(sh, hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        s = (char*)newsh+hdrlen;
    } else {
        /* Since the header size changes, need to move the string forward,
         * and can't use realloc */
        newsh = s_malloc(hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        memcpy((char*)newsh+hdrlen, s, len+1);
        s_free(sh);
        s = (char*)newsh+hdrlen;
        s[-1] = type;
        sdssetlen(s, len);
    }
    sdssetalloc(s, newlen);
    return s;
}
Пример #4
0
void SWindow::windowAtEvent (s_window_t *window, s_event_t *event)
{
	switch (event->type & EVENT_TYPE_MASK) {
		case EVENT_TYPE_CONFIG:
			if ((event->type & (EVENT_TYPE_CONFIG_W | EVENT_TYPE_CONFIG_H)) ||
			    (objectWindow->surface->vbuf == NULL)) {
				objectWindow->surface->width = objectWindow->surface->buf->w;
				objectWindow->surface->height = objectWindow->surface->buf->h;
				objectWindow->surface->vbuf = (unsigned char *) s_realloc(objectWindow->surface->vbuf,
				                                                 objectWindow->surface->width *
				                                                 objectWindow->surface->height *
				                                                 objectWindow->surface->bytesperpixel);
				geometry(0, 0, objectWindow->surface->width, objectWindow->surface->height);
				
				objectWindow->surface->mode = SURFACE_VIRTUAL;
				draw();
				objectWindow->surface->mode = (S_SURFACE_MODE) (SURFACE_VIRTUAL | SURFACE_REAL);
			}
			break;
	}
}
Пример #5
0
void *as_sprintf(const char *fmt, ...)
{
    /* Guess we need no more than 100 bytes. */
    int n, size = 100;
    void *p;
    va_list ap;
    p = s_malloc(size);
    while (1) {
        /* Try to print in the allocated space. */
        va_start(ap, fmt);
        n = vsnprintf(p, size, fmt, ap);
        va_end(ap);
        /* If that worked, return the string. */
        if (n > -1 && n < size)
            return p;
        /* Else try again with more space. */
        if (n > -1)             /* glibc 2.1 */
            size = n + 1;       /* precisely what is needed */
        else                    /* glibc 2.0 */
            size *= 2;          /* twice the old size */
        p = s_realloc(p, size);
    }
}
Пример #6
0
static int
set_serial_rate(int com, char *rate)
{
	char **rp = &serial_config[com - 1];

	if ((com < 1) || (com > 2))
		return (-1);

	/*
	 * If rate is a NULL pointer, erase any existing serial configuration
	 * for this serial port.
	 */
	if (rate == NULL) {
		if (*rp != NULL) {
			free(*rp);
			*rp = NULL;
		}
		return (0);
	}

	*rp = s_realloc(*rp, strlen(rate) + 1);
	(void) strcpy(*rp, rate);
	return (0);
}
Пример #7
0
bool img_load_gif(img_t *img, const fileinfo_t *file)
{
	GifFileType *gif;
	GifRowType *rows = NULL;
	GifRecordType rec;
	ColorMapObject *cmap;
	DATA32 bgpixel, *data, *ptr;
	DATA32 *prev_frame = NULL;
	Imlib_Image im;
	int i, j, bg, r, g, b;
	int x, y, w, h, sw, sh;
	int px, py, pw, ph;
	int intoffset[] = { 0, 4, 2, 1 };
	int intjump[] = { 8, 8, 4, 2 };
	int transp = -1;
	unsigned int disposal = 0, prev_disposal = 0;
	unsigned int delay = 0;
	bool err = false;

	if (img->multi.cap == 0) {
		img->multi.cap = 8;
		img->multi.frames = (img_frame_t*)
		                    s_malloc(sizeof(img_frame_t) * img->multi.cap);
	}
	img->multi.cnt = img->multi.sel = 0;
	img->multi.length = 0;

#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
	gif = DGifOpenFileName(file->path, NULL);
#else
	gif = DGifOpenFileName(file->path);
#endif
	if (gif == NULL) {
		warn("could not open gif file: %s", file->name);
		return false;
	}
	bg = gif->SBackGroundColor;
	sw = gif->SWidth;
	sh = gif->SHeight;
	px = py = pw = ph = 0;

	do {
		if (DGifGetRecordType(gif, &rec) == GIF_ERROR) {
			err = true;
			break;
		}
		if (rec == EXTENSION_RECORD_TYPE) {
			int ext_code;
			GifByteType *ext = NULL;

			DGifGetExtension(gif, &ext_code, &ext);
			while (ext) {
				if (ext_code == GRAPHICS_EXT_FUNC_CODE) {
					if (ext[1] & 1)
						transp = (int) ext[4];
					else
						transp = -1;

					delay = 10 * ((unsigned int) ext[3] << 8 | (unsigned int) ext[2]);
					disposal = (unsigned int) ext[1] >> 2 & 0x7;
				}
				ext = NULL;
				DGifGetExtensionNext(gif, &ext);
			}
		} else if (rec == IMAGE_DESC_RECORD_TYPE) {
			if (DGifGetImageDesc(gif) == GIF_ERROR) {
				err = true;
				break;
			}
			x = gif->Image.Left;
			y = gif->Image.Top;
			w = gif->Image.Width;
			h = gif->Image.Height;

			rows = (GifRowType*) s_malloc(h * sizeof(GifRowType));
			for (i = 0; i < h; i++)
				rows[i] = (GifRowType) s_malloc(w * sizeof(GifPixelType));
			if (gif->Image.Interlace) {
				for (i = 0; i < 4; i++) {
					for (j = intoffset[i]; j < h; j += intjump[i])
						DGifGetLine(gif, rows[j], w);
				}
			} else {
				for (i = 0; i < h; i++)
					DGifGetLine(gif, rows[i], w);
			}

			ptr = data = (DATA32*) s_malloc(sizeof(DATA32) * sw * sh);
			cmap = gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap;
			r = cmap->Colors[bg].Red;
			g = cmap->Colors[bg].Green;
			b = cmap->Colors[bg].Blue;
			bgpixel = 0x00ffffff & (r << 16 | g << 8 | b);

			for (i = 0; i < sh; i++) {
				for (j = 0; j < sw; j++) {
					if (i < y || i >= y + h || j < x || j >= x + w ||
					    rows[i-y][j-x] == transp)
					{
						if (prev_frame != NULL && (prev_disposal != 2 ||
						    i < py || i >= py + ph || j < px || j >= px + pw))
						{
							*ptr = prev_frame[i * sw + j];
						} else {
							*ptr = bgpixel;
						}
					} else {
						r = cmap->Colors[rows[i-y][j-x]].Red;
						g = cmap->Colors[rows[i-y][j-x]].Green;
						b = cmap->Colors[rows[i-y][j-x]].Blue;
						*ptr = 0xff << 24 | r << 16 | g << 8 | b;
					}
					ptr++;
				}
			}

			im = imlib_create_image_using_copied_data(sw, sh, data);

			for (i = 0; i < h; i++)
				free(rows[i]);
			free(rows);
			free(data);

			if (im == NULL) {
				err = true;
				break;
			}

			imlib_context_set_image(im);
			imlib_image_set_format("gif");
			if (transp >= 0)
				imlib_image_set_has_alpha(1);

			if (disposal != 3)
				prev_frame = imlib_image_get_data_for_reading_only();
			prev_disposal = disposal;
			px = x, py = y, pw = w, ph = h;

			if (img->multi.cnt == img->multi.cap) {
				img->multi.cap *= 2;
				img->multi.frames = (img_frame_t*)
				                    s_realloc(img->multi.frames,
				                              img->multi.cap * sizeof(img_frame_t));
			}
			img->multi.frames[img->multi.cnt].im = im;
			img->multi.frames[img->multi.cnt].delay = delay > 0 ? delay : DEF_GIF_DELAY;
			img->multi.length += img->multi.frames[img->multi.cnt].delay;
			img->multi.cnt++;
		}
	} while (rec != TERMINATE_RECORD_TYPE);
Пример #8
0
/*
| Adds a logging category
|
| Returns true if OK.
*/
static bool
add_logcat( const char *name, int priority )
{
	struct logcat *lc;

	if( !strcmp( "all", name ) )
	{
		settings.log_level = 99;

		return true;
	}

	if( !strcmp( "scarce", name ) )
	{
		settings.log_level = LOG_WARNING;

		return true;
	}

	// categories must start with a capital letter.
	if( name[ 0 ] < 'A' || name[ 0 ] > 'Z' )
	{
		return false;
	}

	if( !logcats[ name[ 0 ]- 'A' ] )
	{
		// an empty capital letter
		lc = logcats[name[0]-'A'] = s_calloc(2, sizeof(struct logcat));
	}
	else
	{
		// length of letter list
		int ll = 0;

		// counts list length
		for( lc = logcats[name[0]-'A']; lc->name; lc++ )
			{ ll++; }

		// enlarges list
		logcats[ name[ 0 ] - 'A'] =
			s_realloc(
				logcats[ name[ 0 ]-'A' ],
				( ll + 2 ) * sizeof( struct logcat )
			);

		// goes to the list end
		for( lc = logcats[ name[ 0 ] - 'A']; lc->name; lc++ )
		{
			if( !strcmp( name, lc->name ) )
			{
				// already there
				return true;
			}
		}
	}

	lc->name = s_strdup( name );
	lc->priority = priority;

	// terminates the list
	lc[ 1 ].name = NULL;
	return true;
}
Пример #9
0
RD_BOOL
cssp_connect(char *server, char *user, char *domain, char *password, STREAM s)
{
	OM_uint32 actual_time;
	gss_cred_id_t cred;
	gss_buffer_desc input_tok, output_tok;
	gss_name_t target_name;
	OM_uint32 major_status, minor_status;
	int context_established = 0;
	gss_ctx_id_t gss_ctx;
	gss_OID desired_mech = &_gss_spnego_krb5_mechanism_oid_desc;

	STREAM ts_creds;
	struct stream token = { 0 };
	struct stream pubkey = { 0 };
	struct stream pubkey_cmp = { 0 };

	// Verify that system gss support spnego
	if (!cssp_gss_mech_available(desired_mech))
	{
		warning("CredSSP: System doesn't have support for desired authentication mechanism.\n");
		return False;
	}

	// Get service name
	if (!cssp_gss_get_service_name(server, &target_name))
	{
		warning("CredSSP: Failed to get target service name.\n");
		return False;
	}

	// Establish tls connection to server
	if (!tcp_tls_connect())
	{
		warning("CredSSP: Failed to establish TLS connection.\n");
		return False;
	}

	tcp_tls_get_server_pubkey(&pubkey);

#ifdef WITH_DEBUG_CREDSSP
	streamsave(&pubkey, "PubKey.raw");
#endif

	// Enter the spnego loop
	OM_uint32 actual_services;
	gss_OID actual_mech;
	struct stream blob = { 0 };

	gss_ctx = GSS_C_NO_CONTEXT;
	cred = GSS_C_NO_CREDENTIAL;

	input_tok.length = 0;
	output_tok.length = 0;
	minor_status = 0;

	int i = 0;

	do
	{
		major_status = gss_init_sec_context(&minor_status,
						    cred,
						    &gss_ctx,
						    target_name,
						    desired_mech,
						    GSS_C_MUTUAL_FLAG | GSS_C_DELEG_FLAG,
						    GSS_C_INDEFINITE,
						    GSS_C_NO_CHANNEL_BINDINGS,
						    &input_tok,
						    &actual_mech,
						    &output_tok, &actual_services, &actual_time);

		if (GSS_ERROR(major_status))
		{
			if (i == 0)
				error("CredSSP: Initialize failed, do you have correct kerberos tgt initialized ?\n");
			else
				error("CredSSP: Negotiation failed.\n");

#ifdef WITH_DEBUG_CREDSSP
			cssp_gss_report_error(GSS_C_GSS_CODE, "CredSSP: SPNEGO negotiation failed.",
					      major_status, minor_status);
#endif
			goto bail_out;
		}

		// validate required services
		if (!(actual_services & GSS_C_CONF_FLAG))
		{
			error("CredSSP: Confidiality service required but is not available.\n");
			goto bail_out;
		}

		// Send token to server
		if (output_tok.length != 0)
		{
			if (output_tok.length > token.size)
				s_realloc(&token, output_tok.length);
			s_reset(&token);

			out_uint8p(&token, output_tok.value, output_tok.length);
			s_mark_end(&token);

			if (!cssp_send_tsrequest(&token, NULL, NULL))
				goto bail_out;

			(void) gss_release_buffer(&minor_status, &output_tok);
		}

		// Read token from server
		if (major_status & GSS_S_CONTINUE_NEEDED)
		{
			(void) gss_release_buffer(&minor_status, &input_tok);

			if (!cssp_read_tsrequest(&token, NULL))
				goto bail_out;

			input_tok.value = token.data;
			input_tok.length = s_length(&token);
		}
		else
		{
			// Send encrypted pubkey for verification to server
			context_established = 1;

			if (!cssp_gss_wrap(gss_ctx, &pubkey, &blob))
				goto bail_out;

			if (!cssp_send_tsrequest(NULL, NULL, &blob))
				goto bail_out;

			context_established = 1;
		}

		i++;

	}
	while (!context_established);

	// read tsrequest response and decrypt for public key validation
	if (!cssp_read_tsrequest(NULL, &blob))
		goto bail_out;

	if (!cssp_gss_unwrap(gss_ctx, &blob, &pubkey_cmp))
		goto bail_out;

	pubkey_cmp.data[0] -= 1;

	// validate public key
	if (memcmp(pubkey.data, pubkey_cmp.data, s_length(&pubkey)) != 0)
	{
		error("CredSSP: Cannot guarantee integrity of server connection, MITM ? "
		      "(public key data mismatch)\n");
		goto bail_out;
	}

	// Send TSCredentials
	ts_creds = cssp_encode_tscredentials(user, password, domain);

	if (!cssp_gss_wrap(gss_ctx, ts_creds, &blob))
		goto bail_out;

	s_free(ts_creds);

	if (!cssp_send_tsrequest(NULL, &blob, NULL))
		goto bail_out;

	return True;

      bail_out:
	xfree(token.data);
	return False;
}
Пример #10
0
RD_BOOL
cssp_send_tsrequest(STREAM token, STREAM auth, STREAM pubkey)
{
	STREAM s;
	STREAM h1, h2, h3, h4, h5;

	struct stream tmp = { 0 };
	struct stream message = { 0 };

	memset(&message, 0, sizeof(message));
	memset(&tmp, 0, sizeof(tmp));

	// version [0]
	s_realloc(&tmp, sizeof(uint8));
	s_reset(&tmp);
	out_uint8(&tmp, 2);
	s_mark_end(&tmp);
	h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h2);
	s_free(h1);

	// negoToken [1]
	if (token && s_length(token))
	{
		h5 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, token);
		h4 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h5);
		h3 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h4);
		h2 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h3);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h5);
		s_free(h4);
		s_free(h3);
		s_free(h2);
		s_free(h1);
	}

	// authInfo [2]
	if (auth && s_length(auth))
	{
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, auth);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2);

		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));

		s_free(h2);
		s_free(h1);
	}

	// pubKeyAuth [3]
	if (pubkey && s_length(pubkey))
	{
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, pubkey);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2);

		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}
	s_mark_end(&message);

	// Construct ASN.1 Message
	// Todo: can h1 be send directly instead of tcp_init() approach
	h1 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message);
	s = tcp_init(s_length(h1));
	out_uint8p(s, h1->data, s_length(h1));
	s_mark_end(s);
	s_free(h1);

#if WITH_DEBUG_CREDSSP
	streamsave(s, "tsrequest_out.raw");
	printf("Out TSRequest %ld bytes\n", s_length(s));
	hexdump(s->data, s_length(s));
#endif

	tcp_send(s);

	// cleanup
	xfree(message.data);
	xfree(tmp.data);

	return True;
}
Пример #11
0
STREAM
cssp_encode_tscredentials(char *username, char *password, char *domain)
{
	STREAM out;
	STREAM h1, h2, h3;
	struct stream tmp = { 0 };
	struct stream message = { 0 };

	// credType [0]
	s_realloc(&tmp, sizeof(uint8));
	s_reset(&tmp);
	if (g_use_password_as_pin == False)
	{
		out_uint8(&tmp, 1);	// TSPasswordCreds
	}
	else
	{
		out_uint8(&tmp, 2);	// TSSmartCardCreds
	}

	s_mark_end(&tmp);
	h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h2);
	s_free(h1);

	// credentials [1]
	if (g_use_password_as_pin == False)
	{
		h3 = cssp_encode_tspasswordcreds(username, password, domain);
	}
	else
	{
		h3 = cssp_encode_tssmartcardcreds(username, password, domain);
	}

	h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, h3);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h3);
	s_free(h2);
	s_free(h1);

	// Construct ASN.1 message
	out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message);

#if WITH_DEBUG_CREDSSP
	streamsave(out, "tscredentials.raw");
	printf("Out TSCredentials %ld bytes\n", s_length(out));
	hexdump(out->data, s_length(out));
#endif

	// cleanup
	xfree(message.data);
	xfree(tmp.data);

	return out;
}
Пример #12
0
static STREAM
cssp_encode_tssmartcardcreds(char *username, char *password, char *domain)
{
	STREAM out, h1, h2;
	struct stream tmp = { 0 };
	struct stream message = { 0 };

	// pin [0]
	s_realloc(&tmp, strlen(password) * sizeof(uint16));
	s_reset(&tmp);
	rdp_out_unistr(&tmp, password, strlen(password) * sizeof(uint16));
	s_mark_end(&tmp);
	h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h2);
	s_free(h1);

	// cspData[1]        
	h2 = cssp_encode_tscspdatadetail(AT_KEYEXCHANGE, g_sc_card_name, g_sc_reader_name,
					 g_sc_container_name, g_sc_csp_name);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h2);
	s_free(h1);

	// userHint [2]
	if (username && strlen(username))
	{
		s_realloc(&tmp, strlen(username) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, username, strlen(username) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	// domainHint [3]
	if (domain && strlen(domain))
	{
		s_realloc(&tmp, strlen(domain) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, domain, strlen(domain) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	s_mark_end(&message);

	// build message
	out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message);

	// cleanup
	free(tmp.data);
	free(message.data);
	return out;
}
Пример #13
0
static STREAM
cssp_encode_tscspdatadetail(unsigned char keyspec, char *card, char *reader, char *container,
			    char *csp)
{
	STREAM out;
	STREAM h1, h2;
	struct stream tmp = { 0 };
	struct stream message = { 0 };

	// keySpec [0]
	s_realloc(&tmp, sizeof(uint8));
	s_reset(&tmp);
	out_uint8(&tmp, keyspec);
	s_mark_end(&tmp);
	h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp);
	h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2);
	s_realloc(&message, s_length(&message) + s_length(h1));
	out_uint8p(&message, h1->data, s_length(h1));
	s_mark_end(&message);
	s_free(h2);
	s_free(h1);

	// cardName [1]
	if (card)
	{
		s_realloc(&tmp, 4 + strlen(card) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, card, strlen(card) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	// readerName [2]
	if (reader)
	{
		s_realloc(&tmp, 4 + strlen(reader) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, reader, strlen(reader) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	// containerName [3]
	if (container)
	{
		s_realloc(&tmp, 4 + strlen(container) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, container, strlen(container) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	// cspName [4]
	if (csp)
	{
		s_realloc(&tmp, 4 + strlen(csp) * sizeof(uint16));
		s_reset(&tmp);
		rdp_out_unistr(&tmp, csp, strlen(csp) * sizeof(uint16));
		s_mark_end(&tmp);
		h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
		h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 4, h2);
		s_realloc(&message, s_length(&message) + s_length(h1));
		out_uint8p(&message, h1->data, s_length(h1));
		s_mark_end(&message);
		s_free(h2);
		s_free(h1);
	}

	s_mark_end(&message);

	// build message
	out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message);

	// cleanup
	free(tmp.data);
	free(message.data);
	return out;
}
Пример #14
0
/**
 * \brief
 *
 * \return
 */
void GuiMultiTextBox::renderText()
{
	// clean up previous contents
	if(fontData != NULL)
	{
		for(int i=0; i<numLines; i++)
		{
			if(fontData[i]) s_font_uninit(fontData[i]);
			fontData[i] = NULL;
		}

		s_free(fontData);
		fontData = NULL;
	}

	numLines = 0;

	std::list<std::string>::iterator it = fontWords.begin();
	while(true)
	{
		std::string textLine;
		if(it != fontWords.end()) textLine = it->c_str();
		else break;

		s_font_t**	newFontData = (s_font_t**)s_realloc(fontData,
				sizeof(s_font_t*) * (numLines + 1));

		if (newFontData == NULL) return;

		fontData = newFontData;
		fontData[numLines] = NULL;

		s_font_t* font;
		if(s_font_init(&font, (char*)fontName.c_str()))
		{
			return;
		}

		s_font_set_size(font, fontSize);
		s_font_set_rgb(font, fontColor.red, fontColor.green, fontColor.blue);

		std::string textTest;
		while(it != fontWords.end())
		{
			if(!textTest.empty()) textTest += " ";
			textTest += it->c_str();

			s_font_set_str(font, (char*)textTest.c_str());
			s_font_get_glyph(font);

			// the text does not fit anymore
			if(font->glyph.img->w > drawArea.w)
				break;

			textLine = textTest;
			it ++;
		}

		s_font_set_str(font, (char*)textLine.c_str());
		s_font_get_glyph(font);

		fontData[numLines ++] = font;
	}
}
Пример #15
0
int main (int argc, char *argv [])
{
    int
        i,
        j,
        k,
        n,
	x1,
	y1,
	x2,
	y2;
    float
        f,
        step,
	r,
	g,
	b;
    BOOL
        found,
	int2float;
    time_t
        tp;

    no_mem_buffer = (char *) malloc (1024);

    get_programname (argv [0]);

    if (argc == 1 && isatty (fileno (stdin)))
	syntax (0);

    fontname = "Helvetica";
    fontwidths = helvetica;

    arg_c = argc;
    arg_v = argv;
    process_args ();

    if (outfile) {
	fp_out = fopen (outfile, "w");
	if (! fp_out)
	    errit ("Creating file \"%s\": %s", outfile, strerror (errno));
    } else
	fp_out = stdout;

    if (example) {
	fputs (
	    "# Example cluster file\n"
	    "1 .12\n"
	    "L Norwegian\n"
	    "L Swedish\n"
	    "2 .15\n"
	    "C 1\n"
	    "L Danish\n"
	    "3 .3\n"
	    "L Dutch\n"
	    "L German\n"
	    "4 .35 Nordic group\n"
	    "L Icelandic\n"
	    "C 2\n"
	    "5 .7\n"
	    "C 4\n"
	    "C 3\n",
	    fp_out
	    );
	if (outfile)
	    fclose (fp_out);
	return 0;
    }

    if (patterns || symbols || numbers) {
	if (colorlabel || colorlink)
	    errit ("No colours with %s", patterns ? "patterns" : (symbols ? "symbols" : "numbers"));
	if ((ngroup < 2 || ngroup > n_colors) && ! numbers)
	    errit ("Illegal number of %s: %i", patterns ? "patterns" : "symbols", ngroup);
	if (patterns)
	    PSlevel = 2;
	labels = FALSE;
    }

    if ((colorlink || colorlabel) && (ngroup < 2 || ngroup > n_colors) && ! use_rainbow)
	errit ("Invalid number of groups with coloured labels or links. Try rainbow colours.");

    if (use_rainbow && ! (colorlink || colorlabel))
	errit ("Missing option -c and/or -C with rainbow colours");

    if (colorlabel && ! labels)
	errit ("Colour for no labels\n");

    if (fontsize < 4)
	errit ("fontsize too small");
    if (fontsize > 20)
	errit ("fontsize too large");

    if (evenodd && ! labels)
	errit("Placement of labels in two colums without labels");

    if (use_usercolours && (colorlabel || colorlink)) {
       int2float = FALSE;
       n_colors = 0;
       fp = fopen (colorfile, "r");
       if (! fp)
	   errit ("Opening file \"%s\": %s", colorfile, strerror (errno));
       inputline = 0;
       while (getline (FALSE)) {
           if (n_colors == max_colors) {
               max_colors += 16;
               usercolors = (float **) s_realloc (usercolors, max_colors * sizeof (float**));
           }
           if (sscanf (buffer, "%f %f %f", &r, &g, &b) != 3)
                errit ("Missing value(s) for in file \"%s\", line %i", colorfile, inputline);
           if (r < 0 || r > 255)
                errit ("Red component out of range in file \"%s\", line %i", colorfile, inputline);
           if (g < 0 || g > 255)
                errit ("Green component out of range in file \"%s\", line %i", colorfile, inputline);
           if (b < 0 || b > 255)
                errit ("Blue component out of range in file \"%s\", line %i", colorfile, inputline);
           if (r > 1 || g > 1 || b > 1)
               int2float = TRUE;
           usercolors [n_colors] = s_malloc (3 * sizeof (float));
           usercolors [n_colors][0] = r;
           usercolors [n_colors][1] = g;
           usercolors [n_colors][2] = b;
           n_colors++;
       }
       fclose (fp);
       if (int2float)
           for (i = 0; i < n_colors; i++)
               for (j = 0; j < 3; j++)
                   usercolors [i][j] /= 255;
       inputline = 0;
    }

    switch (arg_c) {
        case 1:
            if (isatty (fileno (stdin)))
                syntax (1);
            fp = stdin;
            break;
	case 2:
            fp = fopen (arg_v [1], "r");
            if (! fp)
                errit ("Opening file \"%s\": %s", arg_v [1], strerror (errno));
            break;
	default:
            syntax (1);
    }

    while (getline (FALSE)) {
        if (used == max) {
            max += 256;
            cl = (CLUSTER *) s_realloc (cl, max * sizeof (CLUSTER));
        }
        if (sscanf (buffer, "%i %g%n", &(cl [used].index), &(cl [used].value), &i) < 2)
            errit ("Syntax error at line %i: \"%s\"", inputline, buffer);
	if (cl [used].value > maxvalue)
	    maxvalue = cl [used].value;
        memmove (buffer, buffer + i, strlen (buffer + i) + 1);
        trim ();
        if (buffer [0] && buffer [0] != '#') {
            psstring ();
            cl [used].text = s_strdup (buffer);
        } else
            cl [used].text = NULL;
        for (n = 0; n < 2; n++) {
            getline (TRUE);
            switch (buffer [0]) {
  	        case 'l':
                case 'L':
                    cl [used].node [n] = LBL;
                    buffer [0] = ' ';
                    trim ();
                    psstring ();
                    if ((f = psstringwidth (buffer)) > maxlabelwidth)
                        maxlabelwidth = f;
                    cl [used].n [n].label = s_strdup (buffer);
                    break;
  	        case 'c':
                case 'C':
                    cl [used].node [n] = CLS;
                    if (sscanf (buffer + 1, "%i", &(cl [used].n [n].cluster)) != 1)
                        errit ("Missing cluster number at line %i", inputline);
                    break;
		default:
                    errit ("Syntax error at line %i: \"%s\"", inputline, buffer);
	    }
        }
        used++;
    }

    if (argc == 2)
        fclose (fp);

    if (!used)
        errit ("No data");

    /* replace indexes */
    for (i = 0; i < used; i++)
        for (j = 0; j < 2; j++)
            if (cl [i].node [j] == CLS)
                for (k = 0; k < used; k++)
		    if (cl [i].n [j].cluster == cl [k].index) {
                        cl [i].n [j].cluster = k;
                        break;
		    }

    /* locate top node */
    top = 0;
    do {
        found = FALSE;
        for (i = 1; i < used; i++)
            if ((cl [i].node [0] == CLS && cl [i].n [0].cluster == top) ||
                (cl [i].node [1] == CLS && cl [i].n [1].cluster == top)
            ) {
                top = i;
                found = TRUE;
                break;
	    }
    } while (found);

    if (! mindefined) {
        for (i = 0; i < used; i++)
            if (cl [i].value < minvalue)
                minvalue = cl [i].value;
        if (minvalue > 0)
            minvalue = 0;
    }

    for (i = 0; i < used; i++)
        if (
            cl [i].text
         && (f = psstringwidth (cl [i].text)
               + leftmargin + ((float) width) / pow (maxvalue - minvalue, exponent) * pow (cl [i].value - minvalue, exponent) + 5.0) > urx
        )
            urx = f;

    if (ngroup > 1) {

	/* divide into color groups */
	j = 0;
	for (i = 0; i < used; i++) {
	    cl [i].group [0] = cl [i].group [1] = 1;
	    for (k = 0; k < 2; k++)
		if (cl [i].node [k] == LBL)
		    j++;
	}
	if (ngroup > j)
	    errit ("Too many groups");
	groups = (int *) s_malloc (ngroup * sizeof (int));
	groups [0] = top;
	for (n = 1; n < ngroup; n++) {
	    f = - FLT_MAX;
	    for (i = 0; i < n; i++)
		if (groups [i] < used && cl [groups [i]].value > f) {
		    j = i;
		    f = cl [groups [i]].value;
		}
	    cl [groups [j]].group [0] = n + 1;
	    cl [groups [j]].group [1] = j + 1;
	    groups [n] = (cl [groups [j]].node [0] == CLS) ? cl [groups [j]].n [0].cluster : (INT_MAX);
	    groups [j] = (cl [groups [j]].node [1] == CLS) ? cl [groups [j]].n [1].cluster : (INT_MAX);
	    setclgroups (groups [n], n + 1);
	    /* setclgroups (groups [j], j + 1); */
	}

    }

    if (labels) {
	if (LineSkip < 0) {
	    LineSkip = 1.2 * fontsize;
	    if (evenodd)
		LineSkip /= 2;
	}
	if (LineSkip2 < 0) {
	    LineSkip2 = 1.5 * LineSkip;
	    if (evenodd)
		LineSkip2 *= 2;
	}
	if (RulerSkip < 0)
	    RulerSkip = 1.5 * LineSkip + 4;
    } else {
	if (LineSkip2 < 0)
	    LineSkip2 = 4;
	if (LineSkip < 0) {
	    LineSkip = 2;
	    if ((used - 1) * LineSkip + (ngroup - 1) * LineSkip2 > 530) {
		LineSkip = (530 - (ngroup - 1) * LineSkip2) / (used - 1);
	    }
	}
	if (RulerSkip < 0)
	    RulerSkip = LineSkip2 + 4;
    }

    fputs (
        "%!PS-Adobe-3.0 EPSF-3.0\n"
        "%%BoundingBox: ",
        fp_out
    );

    x1 = labels ? (leftmargin - 6 - maxlabelwidth) : leftmargin - 10;
    if (evenodd) {
	process_width (top);
	leftmargin2 = leftmargin - 4 - maxlabelwidth1;
	x1 = leftmargin2 - 6 - maxlabelwidth2;
    }
    if (patterns)
	x1 = 100;
    if (symbols)
	x1 = 120;
    if (numbers)
	x1 = 110;
    x2 = urx;
    y1 = 700 - (used - ngroup + 1) * LineSkip - (ngroup - 1) * LineSkip2;
    if (ruler)
	y1 -= RulerSkip + fontsize + 1;
    else if (labels)
	y1 -= fontsize / 2;
    y2 = 701;
    if (labels)
	y2 += fontsize / 2;

    fprintf (fp_out, "%i %i %i %i\n", x1, y1, x2, y2);

    fputs (
        "%%Creator: ",
        fp_out
    );
    fprintf (fp_out, "%s", programname);
    fputs (
        ", Version " denVERSION ", (c) P. Kleiweg 1997 - 2005\n"
        "%%CreationDate: ",
        fp_out
    );
    time (&tp);
    fputs (asctime (localtime (&tp)), fp_out);

    if (argc == 2) {
        fputs ("%%Title: ", fp_out);
        fprintf (fp_out, "%s %i\n", arg_v [1], ngroup);
    }

    fputs ("%%LanguageLevel: ", fp_out);
    fprintf (fp_out, "%i\n", PSlevel);

    fputs (
        "%%EndComments\n"
        "\n"
        "64 dict begin\n"
        "\n",
        fp_out
    );
    fprintf (
	fp_out,
	"/EXP { %g exp } def\n"
        "/FontName /%s def\n"
        "/FontSize %i def\n"
        "/LineSkip %g def\n"
        "/LineSkip2 %g def\n"
	"\n",
	exponent,
	fontname,
        fontsize,
	LineSkip,
	LineSkip2
    );
    fprintf (
	fp_out,
        "/TopMargin 700 def\n"
	"/LeftMargin %i def\n",
	leftmargin
    );
    if (evenodd)
	fprintf (
	    fp_out,
	    "/LeftMargin2 %i def\n",
	    leftmargin2
	);
    fprintf (
	fp_out,
	"\n"
        "/Width %i def\n"
        "\n",
	width
    );

    if (ruler) {
	fprintf (
            fp_out,
	    "/RulerSkip %g def\n"
	    "/RulerStep ",
	    RulerSkip
	);
	step = pow (10, ceil (log10 (maxvalue - minvalue)) - 1);
	if ((maxvalue - minvalue) / step > 6.0)
	    step *= 2.0;
	else if ((maxvalue - minvalue) / step < 3.0)
	    step *= 0.5;
	fprintf (fp_out, "%g def\n\n", step);
    }

    if (colorlink)
	fputs (
	    "/clw { 1 setlinewidth } bind def\n"
	    "/blw { .5 setlinewidth } bind def\n"
	    "\n",
	    fp_out
	);
    else
	fputs (
	    ".5 setlinewidth\n"
	    "\n",
	    fp_out
	);

    if (evenodd)
	fputs ("\n/oelinewidth .2 def\n\n", fp_out);

    if (patterns) {
	fputs (
            "<<\n"
            "    /PatternType 1\n"
            "    /PaintType 1\n"
            "    /TilingType 1\n"
            "    /PaintProc {\n"
            "        begin\n"
            "            XStep\n"
            "            YStep\n"
            "            1\n"
            "            [ 1 0 0 1 0 0 ]\n"
            "            data\n"
            "            image\n"
            "        end\n"
            "    }\n"
            ">>\n"
            "/pdict exch def\n"
            "\n"
            "% stack in:  /label width height patterndata\n"
            "% stack out: -\n"
            "/defpattern {\n"
            "    /pat exch def\n"
            "    /y exch def\n"
            "    /x exch def\n"
            "    pdict /BBox [ 0 0 x y ] put\n"
            "    pdict /XStep x put\n"
            "    pdict /YStep y put\n"
            "    pdict /data pat put\n"
            "    pdict [ 72 60 div 0 0\n"
            "            72 60 div 0 0 ] makepattern\n"
            "    def\n"
            "} bind def\n"
	    "\n",
	    fp_out
	);
	for (i = 0; i < ngroup; i++)
	    fprintf (fp_out, "/c%-2i %s defpattern\n", i + 1, pat [i]);
	fputs ("\n", fp_out);
    }

    if (numbers)
	fputs ("/NumFontSize 12 def\n\n", fp_out);

    if (symbols) {
	fputs (
	    "/Symsize 8 def\n"
	    "/Symlw .7 def\n"
	    "\n",
	    fp_out
	);
	for (i = 0; i < ngroup; i++)
	    fprintf (fp_out, "/c%-2i /sym%-2i def\n", i + 1, i);
	fputs ("\n", fp_out);
    }

    fputs (
        "%%% End of User Options %%%\n"
	"\n",
        fp_out
    );

    if (patterns)
	fputs (
	    "/c0 {\n"
	    "    COL {\n"
	    "        Y YY ne {\n"
	    "            /Pattern setcolorspace P setcolor\n"
	    "            100 Y moveto\n"
	    "            140 Y lineto\n"
	    "            140 YY LineSkip add lineto\n"
	    "            100 YY LineSkip add lineto\n"
	    "            closepath\n"
	    "            fill\n"
	    "            0 setgray\n"
	    "        } if\n"
	    "        /COL false def\n"
	    "    } if\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);

    if (symbols) {
	for (i = 0; i < ngroup; i++)
	    fprintf (fp_out, "/sym%-2i {\n%s} bind def\n\n", i, sym [i]);
	fputs (
	    "/c0 {\n"
	    "    COL {\n"
	    "        140 Y moveto\n"
	    "        135 Y lineto\n"
	    "        135 YY lineto\n"
	    "        140 YY lineto\n"
	    "        stroke\n"
	    "        currentlinewidth\n"
	    "        130 Symsize 2 div sub  Y YY add 2 div moveto\n"
	    "        gsave\n"
	    "            1 setgray\n"
	    "            Symsize -2 div 3 sub dup rmoveto\n"
	    "            Symsize 6 add 0 rlineto\n"
	    "            0 Symsize 6 add rlineto\n"
	    "            Symsize 6 add neg 0 rlineto\n"
	    "            closepath\n"
	    "            fill\n"
	    "        grestore\n"
	    "        Symlw setlinewidth\n"
	    "        P cvx exec\n"
	    "        setlinewidth\n"
	    "        /COL false def\n"
	    "    } if\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    }

    if (numbers) {
	fputs (
	    "/c0 {\n"
	    "    COL {\n"
	    "        140 Y moveto\n"
	    "        135 Y lineto\n"
	    "        135 YY lineto\n"
	    "        140 YY lineto\n"
	    "        stroke\n"
	    "        130 Y YY add 2 div Shift sub moveto\n"
	    "        P 10 string cvs\n"
	    "        dup stringwidth pop neg 0 rmoveto show\n"
	    "        /COL false def\n"
	    "    } if\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    }

    if (patterns || symbols || numbers)
	fputs (
	    "/col {\n"
	    "    c0\n"
	    "    /Y y def\n"
	    "    /YY y def\n"
	    "    /P exch def\n"
	    "    /COL true def\n"
	    "} bind def\n"
	    "\n"
	    "/COL false def\n"
	    "\n",
	    fp_out
	);

    if (colorlink || colorlabel) {
	fprintf (fp_out, "/SETCOLOR { set%scolor } bind def\n", use_rainbow ? "hsb" : "rgb");
	fprintf (fp_out, "/CURRENTCOLOR { current%scolor } bind def\n", use_rainbow ? "hsb" : "rgb");
	fprintf (fp_out, "/c0 {\n    0 setgray%s\n    /COL false def\n} bind def\n", colorlink ? "\n    blw" : "");
	if (use_rainbow)
            for (i = 0; i < ngroup; i++)
                fprintf (
                    fp_out,
                    "/c%i { %.4f 1 %s } def\n",
                    i + 1,
                    ((float) i) / ngroup,
                    ((i % 2) && ! use_bright) ? ".6" : "1"
                );
	else
	    for (i = 0; i < ngroup; i++)
		fprintf (
		    fp_out,
		    "/c%i { %g %g %g } def\n",
		    i + 1,
		    use_usercolours ? usercolors [i][0] : colors [i][0],
		    use_usercolours ? usercolors [i][1] : colors [i][1],
		    use_usercolours ? usercolors [i][2] : colors [i][2]
		);
	fputs (
	    "/col {\n"
	    "    SETCOLOR\n",
	    fp_out
	);
	if (colorlink)
	    fputs ("    clw\n", fp_out);
	fputs (
	    "    /COL true def\n"
	    "} bind def\n"
	    "\n"
	    "c0\n"
	    "\n",
	    fp_out
	);
    }

    if (eXtended && PSlevel == 1)
        fputs (
            "/ISOLatin1Encoding\n"
            "[/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
            "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
            "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
            "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
            "/space /exclam /quotedbl /numbersign /dollar /percent /ampersand\n"
            "/quoteright /parenleft /parenright /asterisk /plus /comma /minus /period\n"
            "/slash /zero /one /two /three /four /five /six /seven /eight /nine\n"
            "/colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F\n"
            "/G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft\n"
            "/backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d\n"
            "/e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z\n"
            "/braceleft /bar /braceright /asciitilde /.notdef /.notdef /.notdef\n"
            "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
            "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /dotlessi /grave\n"
            "/acute /circumflex /tilde /macron /breve /dotaccent /dieresis /.notdef\n"
            "/ring /cedilla /.notdef /hungarumlaut /ogonek /caron /space /exclamdown\n"
            "/cent /sterling /currency /yen /brokenbar /section /dieresis /copyright\n"
            "/ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron\n"
            "/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph\n"
            "/periodcentered /cedilla /onesuperior /ordmasculine /guillemotright\n"
            "/onequarter /onehalf /threequarters /questiondown /Agrave /Aacute\n"
            "/Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute\n"
            "/Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth\n"
            "/Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply\n"
            "/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn\n"
            "/germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae\n"
            "/ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute\n"
            "/icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex\n"
            "/otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex\n"
            "/udieresis /yacute /thorn /ydieresis]\n"
            "def\n"
            "\n",
            fp_out
        );

    if (eXtended)
        fputs (
            "/RE {\n"
            "    findfont\n"
            "    dup maxlength dict begin {\n"
            "        1 index /FID ne { def } { pop pop } ifelse\n"
            "    } forall\n"
            "    /Encoding exch def\n"
            "    dup /FontName exch def\n"
            "    currentdict end definefont pop\n"
            "} bind def\n"
            "\n"
            "/Font-ISOlat1 ISOLatin1Encoding FontName RE\n",
	    fp_out
	);

    if (numbers) {
	fprintf (fp_out, "/Font1 %s findfont FontSize scalefont def\n", eXtended ? "/Font-ISOlat1" : "FontName");
	fputs (
	    "/Font2 FontName findfont NumFontSize scalefont def\n"
	    "\n"
	    "Font1 setfont\n",
	    fp_out
	);
    } else
	fprintf (fp_out, "%s findfont FontSize scalefont setfont\n\n", eXtended ? "/Font-ISOlat1" : "FontName");

    fputs (
        "gsave\n"
        "    newpath\n"
        "    0 0 moveto\n"
        "    (Ag) false charpath\n"
        "    pathbbox\n"
        "grestore\n"
        "/Up exch def\n"
	"pop\n"
	"neg /Down exch def\n"
	"pop\n",
	fp_out
    );
    if (numbers)
	fputs ("Font2 setfont\n", fp_out);
    fputs (
        "gsave\n"
        "    newpath\n"
        "    0 0 moveto\n",
	fp_out
    );
    fprintf (fp_out, "    (%c) false charpath\n", numbers ? '1' : 'x');
    fputs (
        "    pathbbox\n"
        "grestore\n"
        "2 div /Shift exch def\n"
	"pop\n"
	"pop\n"
	"pop\n"
	"\n"
        "/y TopMargin def\n"
        "\n",
        fp_out
    );

    fprintf (fp_out, "/Min %g def\n/Max %g def\n\n", minvalue, maxvalue);

    if (evenodd)
	fputs ("/oe false def\n\n", fp_out);

    fputs (
        "/nl {\n"
        "  /y y LineSkip add LineSkip2 sub def\n"
        "} bind def\n"
        "\n",
	fp_out
    );

    if (patterns || symbols || numbers)
	fputs (
	    "/Cstroke {\n"
	    "    COL { /YY y def } if\n"
	    "    stroke\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    else if (colorlabel && ! colorlink)
	fputs (
	    "/Cstroke {\n"
	    "    COL {\n"
	    "        CURRENTCOLOR\n"
	    "        0 setgray\n"
	    "        stroke\n"
	    "        SETCOLOR\n"
	    "    } {\n"
	    "        stroke\n"
	    "    } ifelse\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    else
	fputs (
	    "/Cstroke {\n"
	    "    stroke\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);

    if (colorlabel)
	fputs (
	    "/Cshow {\n"
	    "    COL {\n"
	    "        gsave\n"
	    "            -1 -1 Down sub rmoveto\n"
	    "            dup stringwidth pop 2 add dup 0 rlineto\n"
	    "            0 Down Up add 2 add rlineto\n"
	    "            neg 0 rlineto\n"
	    "            closepath\n"
	    "            fill\n"
	    "        grestore\n"
	    "        gsave\n"
	    "            currentgray .4 gt { 0 } { 1 } ifelse setgray\n"
	    "            show\n"
	    "        grestore\n"
	    "    } {\n"
	    "        show\n"
	    "    } ifelse\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    else if (colorlink)
	fputs (
	    "/Cshow {\n"
	    "    COL {\n"
	    "        CURRENTCOLOR\n"
	    "        0 setgray\n"
	    "        4 -1 roll\n"
	    "        show\n"
	    "        SETCOLOR\n"
	    "    } {\n"
	    "        show\n"
	    "    } ifelse\n"
	    "} bind def \n"
	    "\n",
	    fp_out
	);
    else if (numbers)
	fputs (
	    "/Cshow {\n"
	    "    Font1 setfont\n"
	    "    show\n"
	    "    Font2 setfont\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    else
	fputs (
	    "/Cshow {\n"
	    "    show\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);

    if (labels) {
	fputs (
	    "% stack in:  (label)\n"
	    "% stach out: x y\n"
	    "/l {\n"
	    "    dup stringwidth pop\n"
	    "    neg LeftMargin add 4 sub y Shift sub moveto\n",
	    fp_out
	);
	if (evenodd)
	    fputs (
	        "    oe {\n"
		"        LeftMargin2 LeftMargin sub 0 rmoveto\n"
		"        Cshow\n"
		"        gsave\n"
		"            LeftMargin2 y moveto\n"
		"            LeftMargin 4 sub y lineto\n"
		"            0 setgray\n"
		"            oelinewidth setlinewidth\n"
		"            stroke\n"
		"        grestore\n"
		"        /oe false def\n"
		"    } {\n"
		"        Cshow\n"
		"        /oe true def\n"
		"    } ifelse\n",
		fp_out
	    );
	else
	    fputs (
	        "    Cshow\n",
		fp_out
	    );
	fputs (
	    "    LeftMargin y\n"
	    "    /y y LineSkip sub def\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);
    } else
	fputs (
	    "% stack in:  -\n"
	    "% stach out: x y\n"
	    "/l {\n"
	    "    LeftMargin y\n"
	    "    /y y LineSkip sub def\n"
	    "} bind def\n"
	    "\n",
	    fp_out
	);

    fputs (
        "% stack in:  x1 y1 x2 y2 value\n"
	"% stack out: x3 y3\n"
	"/c {\n"
	    "    Min sub EXP Width mul Max Min sub EXP div LeftMargin add\n",
	fp_out
    );
    if (linktype == RECT)
	fputs (
	    "    5 1 roll\n"
	    "    3 index 3 index moveto\n"
	    "    4 index 3 index lineto\n"
	    "    4 index 1 index lineto\n"
	    "    1 index 1 index lineto\n"
	    "    Cstroke\n"
	    "    exch pop\n"
	    "    add 2 div\n"
	    "    exch pop\n",
	    fp_out
	);
    else if (linktype == ARC)
	fputs (
	    "    /x3 exch def\n"
	    "    /y2 exch def\n"
	    "    /x2 exch def\n"
	    "    /y1 exch def\n"
	    "    /x1 exch def\n"
	    "    /y3 y1 y2 add 2 div def\n"
	    "    x1 y1 moveto\n"
	    "    x3 x1 sub .552284 mul x1 add y1\n"
	    "    x3 y1 y3 sub .552284 mul y3 add\n"
	    "    x3 y3 curveto\n"
	    "    x3 y2 y3 sub .552284 mul y3 add\n"
	    "    x3 x2 sub .552284 mul x2 add y2\n"
	    "    x2 y2 curveto\n"
	    "    Cstroke\n"
	    "    x3 y3\n",
	    fp_out
	);
    else
	fputs (
	    "    /x3 exch def\n"
	    "    /y2 exch def\n"
	    "    /x2 exch def\n"
	    "    /y1 exch def\n"
	    "    /x1 exch def\n"
	    "    /y3 y1 y2 add 2 div def\n"
	    "    x1 y1 moveto\n"
	    "    x3 y3 lineto\n"
	    "    x2 y2 lineto\n"
	    "    Cstroke\n"
	    "    x3 y3\n",
	    fp_out
	);
    fputs (
        "} bind def\n"
	"\n",
	fp_out
    );

    fputs (
        "% stack in:  x y (text)\n"
        "% stack out: x y\n"
        "/n {\n"
        "    2 index 3 add\n"
	"    2 index 2 add Down add\n"
        "    moveto\n"
        "    Cshow\n"
        "} bind def\n"
        "\n",
        fp_out
    );

    process (top);

    fputs (
        "pop pop\n"
        "\n",
	fp_out
     );

    if (ruler) {
	fputs ("% This draws the ruler\n", fp_out);
	if (numbers)
	    fputs ("Font1 setfont\n", fp_out);
	fputs (
	    "/setmark1 {\n"
	    "    Min sub EXP Width mul Max Min sub EXP div LeftMargin add\n"
	    "    y moveto\n"
	    "    0 2 rlineto\n"
	    "    stroke\n"
	    "} bind def\n"
	    "\n"
	    "/setmark {\n"
	    "    dup\n"
	    "    Min sub EXP Width mul Max Min sub EXP div LeftMargin add\n"
	    "    y moveto\n"
	    "    gsave\n"
	    "        0 4 rlineto\n"
	    "        stroke\n"
	    "    grestore\n"
	    "    0 FontSize neg rmoveto\n"
	    "    20 string cvs\n"
	    "    dup stringwidth pop 2 div neg 0 rmoveto\n"
	    "    show\n"
	    "} bind def\n"
	    "\n"
	    "/y y LineSkip add RulerSkip sub def\n"
	    "0 RulerStep 5 div Max {\n"
	    "    dup Min ge { setmark1 } { pop } ifelse\n"
	    "} for\n"
	    "0 RulerStep Max {\n"
	    "    dup Min ge { setmark } { pop } ifelse\n"
	    "} for\n"
	    "RulerStep neg 5 div dup Min {\n"
	    "    dup Max le { setmark1 } { pop } ifelse\n"
	    "} for\n"
	    "RulerStep neg dup Min {\n"
	    "    dup Max le { setmark } { pop } ifelse\n"
	    "} for\n"
	    "LeftMargin y moveto\n"
	    "Width 0 rlineto stroke\n"
	    "\n"
	    "% This draws the vertical line for X equals 0\n"
	    "Min 0 lt Max 0 gt and {\n"
	    "    Min neg EXP Width mul Max Min sub EXP div LeftMargin add\n"
	    "    dup\n"
	    "    y\n"
	    "    moveto\n"
	    "    TopMargin FontSize 2 div add\n"
	    "    lineto\n"
	    "    [ 3 ] 0 setdash\n"
	    "    stroke\n"
	    "} if\n"
	    "\n",
	    fp_out
	);
    }

    fputs (
        "end\n"
        "showpage\n"
        "%%EOF\n",
        fp_out
    );

    if (outfile)
	fclose (fp_out);

    return 0;
}
Пример #16
0
/*
| Core watches a filedescriptor to become ready,
| one of read_ready or write_ready may be zero
*/
extern void
observe_fd(
	int fd,
	void ( * ready  ) (lua_State *, struct observance * ),
	void ( * writey ) (lua_State *, struct observance * ),
	void ( * tidy   ) (struct observance * ),
	void *extra
)
{
	int pos;

	// looks if the fd is already there as pos or
	// stores the position to insert the new fd in pos
	for( pos = 0; pos < observances_len; pos++)
	{
		if( fd <= observances[ pos ].fd )
			{ break; }
	}

	if( pos < observances_len && observances[ pos ].fd == fd )
	{
		// just updates an existing observance
		logstring( "Masterloop", "updating fd observance" );
		observances[ pos ].ready  = ready;
		observances[ pos ].writey = writey;
		observances[ pos ].tidy   = tidy;
		observances[ pos ].extra  = extra;
		return;
	}

	if( observance_action )
	{
		// FIXME
		logstring(
			"Error",
			"New observances in ready/writey handlers not yet supported"
		);

		exit( -1 );
	}

	if( !tidy )
	{
		logstring(
			"Error",
			"internal, tidy() in observe_fd() must not be NULL."
		);
		exit( -1 );
	}

	if( observances_len + 1 > observances_size )
	{
		observances_size = observances_len + 1;
		observances = s_realloc(
			observances,
			observances_size * sizeof( struct observance )
		);
	}

	memmove(
		observances + pos + 1,
		observances + pos,
		(observances_len - pos) * sizeof(struct observance)
	);

	observances_len++;

	observances[ pos ].fd     = fd;
	observances[ pos ].ready  = ready;
	observances[ pos ].writey = writey;
	observances[ pos ].tidy   = tidy;
	observances[ pos ].extra  = extra;
}
Пример #17
0
int main (int argc, char *argv [])
{
    char
	c;
    int
	allinn,
	allout,
	bias,
	i,
	j,
	n,
	TP,
	FP,
	oldTP,
	oldFP,
	intarget,
	target;
    double
	P,
	R,
	AF,
	AP,
	AR,
	BP,
	BR,
	oldAF,
	oldAP,
	oldAR;

    no_mem_buffer = (char *) malloc (1024);

    get_programname (argv [0]);


    /* process args */

    if (argc != 4)
	syntax ();

    beta = atof (argv [2]);
    Limit = atof (argv [3]);


    /* read data */

    if (access ("../data/UTF", F_OK) == 0)
	utf = 1;

    openread ("current");
    GetLine ();
    sscanf (buffer, " %i %i", &i, &target);
    fclose (fp);
    openread ("clgroups.txt");
    while (GetLine ()) {
	sscanf (buffer, " %i%n", &i, &n);
	if (i != target)
	    continue;
	while (buffer [n] && isspace ((unsigned char) buffer [n]))
	    n++;
	memmove (buffer, buffer + n, strlen (buffer + n) + 1);
	unquote ();
	if (n_targets == max_targets) {
	    max_targets += 64;
	    targets = (char **) s_realloc (targets, max_targets * sizeof (char *));
	}
	targets [n_targets++] = s_strdup (buffer);
    }
    fclose (fp);
    qsort (targets, n_targets, sizeof (char **), cmpstr);

    if (utf)
	openread ("currentchars-u.txt");
    else
	openread ("currentchars-1.txt");
    while (GetLine ()) {
	if (n_valchars == max_valchars) {
	    max_valchars += 64;
	    valchars = (char **) s_realloc (valchars, max_valchars * sizeof (char *));
	}
	valchars [n_valchars++] = s_strdup (buffer);
    }
    fclose (fp);
    qsort (valchars, n_valchars, sizeof (char **), cmpstr);

    intarget = 0;
    openread (argv [1]);
    while (GetLine ()) {
	if (buffer [0] == ':') {
	    for (j = 1; buffer [j] && isspace ((unsigned char) buffer [j]); j++)
		;
	    if (bsearch (buffer + j, targets, n_targets, sizeof (char **), searchcmp))
		intarget = 1;
	    else
		intarget = 0;
	} else if (buffer [0] == '-') {
	    for (j = 1; buffer [j] && isspace ((unsigned char) buffer [j]); j++)
		;
	    memmove (buffer, buffer + j, strlen (buffer + j) + 1);
	    insert (intarget);
	}
    }
    fclose (fp);


    /* process data */

    fp = stdout;


    /* total response count inside and outside */

    allinn = 0;
    allout = 0;
    for (i = 0; i < n_patterns; i++) {
	allinn += patterns [i].i;
	allout += patterns [i].o;
    }

    /* bias: 0 or 1 */

    bias = 1;

    /* Baseline precision */

    BP = ((double)(allinn + 2 * bias)) / (double)(allinn + allout + 4 * bias);

    /* score all patterens */

    for (j = 0; j < n_patterns; j++) {
	if (! patterns [j].used) {
	    patterns [j].AF = -1;
	    continue;
	}
	TP = patterns [j].i;
	FP = patterns [j].o;
	R = ((double)(TP + bias)) / (double)(allinn + 2 * bias);
	BR = ((double)(TP + FP + 2 * bias)) / (double)(allinn + allout + 4 * bias);
	AR = (R - BR) / (1.0 - BR);
	P = ((double)(TP + bias)) / (double)(TP + FP + 2 * bias);
	AP = (P - BP) / (1.0 - BP);
	if (AP > 0.0 && AR > 0.0)
	    AF = (AP + beta * AR) / (1.0 + beta);
	else
	    AF = 0.0;
	patterns [j].AF = AF;
	patterns [j].AP = AP;
	patterns [j].AR = AR;

    }


    /* see what patterns will be used, print them, and sum up values for total score */

    qsort (patterns, n_patterns, sizeof (PATTERN_), cmppat); /* sort by score, descending */

    oldAF = oldAP = oldAR = 0.0;
    oldTP = oldFP = 0;
    for (j = 0; j < n_patterns; j++) {
	if (! patterns[j].used)
	    continue;
	TP = oldTP + patterns[j].i;
	FP = oldFP + patterns[j].o;
	R = ((double)(TP + bias)) / (double)(allinn + 2 * bias);
	BR = ((double)(TP + FP + 2 * bias)) / (double)(allinn + allout + 4 * bias);
	AR = (R - BR) / (1.0 - BR);
	P = ((double)(TP + bias)) / (double)(TP + FP + 2 * bias);
	AP = (P - BP) / (1.0 - BP);
	if (AP > 0.0 && AR > 0.0)
	    AF = (AP + beta * AR) / (1.0 + beta);
	else
	    AF = 0.0;
	if (patterns[j].i == 0 || AF < oldAF * Limit)
	    patterns[j].rejected = 1;
	else {
	    oldAF = AF;
	    oldAP = AP;
	    oldAR = AR;
	    oldTP = TP;
	    oldFP = FP;
	    c = '[';
	    fprintf (fp, "%.2f %.2f %.2f %s %i:%i",
		     patterns[j].AF, patterns[j].AP, patterns[j].AR,
		     escape((unsigned char *) patterns[j].s),
		     patterns[j].i, patterns[j].i + patterns[j].o);
	    qsort (patterns[j].forms, patterns[j].n_forms, sizeof (char **), cmpstr);
	    for (n = 0; n < patterns[j].n_forms; n++) {
		fprintf (fp, " %c %s", c, escape((unsigned char *) patterns[j].forms[n]));
		c = '|';
	    }
	    fprintf (fp, " ]\n");
	}

    }

    /* print the rejected patterns */

    qsort (patterns, n_patterns, sizeof (PATTERN_), cmppatstr); /* sort by pattern */

    for (i = 0; i < n_patterns; i++)
	if (patterns[i].rejected)
	    fprintf (fp, "[%s %i:%i]\n", escape((unsigned char *) patterns[i].s), patterns[i].i, patterns[i].i + patterns[i].o);


    /* print the total score */

    fprintf (fp, "\n%.2f %.2f %.2f %i:%i\n", oldAF, oldAP, oldAR, oldTP, oldTP + oldFP);


    return 0;
}
Пример #18
0
/*

    Function:   iPrsParseTextFile()

    Purpose:    Adds term to the index for a given file.

    Parameters: pppPrsParser    structure containing the various parser options 
                                we use to parse the data
                ppfPrsFormat    file profile pointing to the various file options 
                                we use to parse the data
                pucFilePath     file path to be parsed
                pfInputFile     data stream to be parsed
                pfIndexerFile   structured index stream output file
                pfDataLength    return pointer for the data length parsed

    Globals:    none

    Returns:    0 on success, -1 on error

*/
int iPrsParseTextFile
(
    struct prsParser *pppPrsParser,
    struct prsFormat *ppfPrsFormat,
    unsigned char *pucFilePath,
    FILE *pfInputFile,
    FILE *pfIndexerFile,
    float *pfDataLength
)
{

    int             iError = UTL_NoError;
    int             iStatus = 0;
    FILE            *pfLocalFile = NULL;
    unsigned char   *pucLine = NULL;
    unsigned char   *pucNormalizedLine = NULL;
    wchar_t         *pwcLine = NULL;
    unsigned int    uiLineLength = 0;
    unsigned int    ulLineCapacity = 0;
    unsigned int    uiNormalizedLineCapacity = 0;
    wchar_t         *pwcParseLinePtr = NULL;
    off_t           zCurrentOffset = 0;
    off_t           zStartOffset = 0;
    off_t           zEndOffset = 0;
    unsigned int    uiTermPosition = 0;
    unsigned char   pucTrueFilePath[UTL_FILE_PATH_MAX + 1] = {'\0'};

    unsigned int    uiLanguageID = LNG_LANGUAGE_ANY_ID;
    unsigned int    uiFieldID = 0;
    boolean         bIndexLine = false;
    boolean         bParseLine = false;
    boolean         bTermPositions = false;

    boolean         bIndexing = false;
    boolean         bSetStartCharacter = true;
    boolean         bFinishDocument = false;

    float           fLineLength = 0;
    float           fDataLength = 0;


    /* Check the parameters */
    if ( pppPrsParser == NULL ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Null 'pppPrsParser' parameter passed to 'iPrsParseTextFile'."); 
        return (-1);
    }

    if ( ppfPrsFormat == NULL ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Null 'ppfPrsFormat' parameter passed to 'iPrsParseTextFile'."); 
        return (-1);
    }

    if ( pfIndexerFile == NULL ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Null 'pfIndexerFile' parameter passed to 'iPrsParseTextFile'."); 
        return (-1);
    }

    if ( (bUtlStringsIsStringNULL(pucFilePath) == true) && (pfInputFile == NULL) ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Null or empty 'pucFilePath' &'pfInputFile' parameters passed to 'iPrsParseTextFile'."); 
        return (-1);
    }

    if ( (bUtlStringsIsStringNULL(pucFilePath) == false) && (pfInputFile != NULL) ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Invalid 'pucFilePath' &'pfInputFile' parameters passed to 'iPrsParseTextFile'."); 
        return (-1);
    }

    if ( pfDataLength == NULL ) {
        iUtlLogError(UTL_LOG_CONTEXT, "Null 'pfDataLength' parameter passed to 'iPrsParseTextFile'."); 
        return (-1);
    }


    /* Preset the data length return pointer */
    *pfDataLength = 0;
        

    /* Open the file path if it was provided */
    if ( bUtlStringsIsStringNULL(pucFilePath) == false ) {

        /* Get the real file path of this file */
        if ( (iError = iUtlFileGetTruePath(pucFilePath, pucTrueFilePath, UTL_FILE_PATH_MAX + 1)) != UTL_NoError ) {
            iUtlLogError(UTL_LOG_CONTEXT, "Failed to get the true path of the file path: '%s', utl error: %d.", pucFilePath, iError);
            iStatus = -1;
            goto bailFromlPrsParseTextFile;
        }
    
        /* Open the file to index */
        if ( (pfLocalFile = s_fopen(pucTrueFilePath, "r")) == NULL ) {
            /* Send a message 
            ** M    message
            */
            if ( fprintf(pfIndexerFile, "M File: '%s' could not be opened.\n", pucTrueFilePath) < 0 ) {
                iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a message line to the indexer");
            }
            iStatus = -1;
            goto bailFromlPrsParseTextFile;
        }

        /* Send a message to the indexer
        ** M    (Message to be displayed by the indexer)
        */
        if ( pppPrsParser->bSuppressMessages == false ) {
            if ( fprintf(pfIndexerFile, "M Parsing file: '%s'.\n", pucTrueFilePath) < 0 ) {
                iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a message line to the indexer");
            }
        }
    }
    /* Otherwise read from the input file */ 
    else if ( pfInputFile != NULL ) {
        pfLocalFile = pfInputFile;
    }
    /* Otherwise croak */
    else {
        iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to find data either from a file path or an input file stream");
    }


    
    /* Initialize for the first document */
    zCurrentOffset = 0;
    zStartOffset = 0;
    zEndOffset = 0;
    uiTermPosition = 1;

    bIndexing = false;
    bSetStartCharacter = true;
    bFinishDocument = false;


    /* Loop around reading every line in the file */
    while ( true ) {
    
        boolean         bEoF = false;
        unsigned char   *pucLineEndPtr = NULL;


        /* Reset the line to an empty string, note that pucLine is dynamically
        ** allocated so we make sure that it is allocated before doing so 
        */
        if ( pucLine != NULL ) {
            pucLine[0] = '\0';
        }

        /* Reset the line length */
        uiLineLength = 0;

        /* This ugly little loop reads stuff from the file we are indexing making sure that
        ** it reads an entire actual line (ie not limited by the fact that fgets() can only 
        ** read fixed length buffers) and erases any end of line characters
        */
        do {

            /* Allocate/reallocate lines if needed */
            if ( (pucLine == NULL) || (ulLineCapacity == 0) || ((uiLineLength + BUFSIZ) > ulLineCapacity) ) {

                unsigned char   *pucLinePtr = NULL;


                /* Extend the line */
                if ( (pucLinePtr = (unsigned char *)s_realloc(pucLine, (size_t)(sizeof(unsigned char) * (ulLineCapacity + BUFSIZ)))) == NULL ) {
                    iStatus = -1;
                    goto bailFromlPrsParseTextFile;
                }

                /* Hand over the pointer */
                pucLine = pucLinePtr;

                /* Clear the new allocation */
                s_memset(pucLine + ulLineCapacity, 0, BUFSIZ);
                
                /* Set the line capacity */
                ulLineCapacity += BUFSIZ;

                
                /* Extend the normalized line if normalization is supported */
                if ( pppPrsParser->pvLngUnicodeNormalizer != NULL ) {
                
                    unsigned char    *pucNormalizedLinePtr = NULL;
                    
                    /* Set the normalized line capacity */
                    uiNormalizedLineCapacity = ulLineCapacity * LNG_UNICODE_NORMALIZATION_EXPANSION_MULTIPLIER_MAX;

                    /* Extend the normalized line */
                    if ( (pucNormalizedLinePtr = (unsigned char *)s_realloc(pucNormalizedLine, (size_t)(sizeof(unsigned char) * uiNormalizedLineCapacity))) == NULL ) {
                        iStatus = -1;
                        goto bailFromlPrsParseTextFile;
                    }
    
                    /* Hand over the pointer */
                    pucNormalizedLine = pucNormalizedLinePtr;
                }

                
                /* Extend the wide character line */
                {
                    wchar_t     *pwcLinePtr = NULL;
                
                    /* Extend the wide character line */
                    if ( (pwcLinePtr = (wchar_t *)s_realloc(pwcLine, (size_t)(sizeof(wchar_t) * ulLineCapacity))) == NULL ) {
                        iStatus = -1;
                        goto bailFromlPrsParseTextFile;
                    }
    
                    /* Hand over the pointer */
                    pwcLine = pwcLinePtr;
                }
            }


            /* Read the next line chunk, appending to the current line and setting the end of file flag */
            bEoF = (s_fgets(pucLine + uiLineLength, ulLineCapacity - uiLineLength, pfLocalFile) == NULL) ? true : false;

            /* Get the new line length here for optimization */
            uiLineLength = s_strlen(pucLine);

            /* Erase the trailing new line - be platform sensitive, handle PC first, then Unix and Mac  */
            if ( (uiLineLength >= 2) && (pucLine[uiLineLength - 2] == '\r') ) {
                pucLineEndPtr = pucLine + (uiLineLength - 2);
                uiLineLength -= 2;
            }
            else if ( (uiLineLength >= 1) && ((pucLine[uiLineLength - 1] == '\n') || (pucLine[uiLineLength - 1] == '\r')) ) {
                pucLineEndPtr = pucLine + (uiLineLength - 1);
                uiLineLength -= 1;
            }
            else if ( (uiLineLength >= 1) && (bEoF == true) ) {
                pucLineEndPtr = pucLine + uiLineLength;
            }
            else {
                pucLineEndPtr = NULL;
            }

            if ( pucLineEndPtr != NULL ) {
                *pucLineEndPtr = '\0';
            }

        } while ( (pucLineEndPtr == NULL) && (bEoF == false) );


        /* Increment the line length */
        fLineLength++;

        /* Increment the data length */
        fDataLength += uiLineLength;
        

        /* Set the current character */
        zCurrentOffset += uiLineLength;


        /* Check to see if we have reached the end of the file, if we have we finish the document and bail */
        if ( (bEoF == true) && (pucLineEndPtr == NULL) ) {
            
            /* Finish the document if we are indexing */
            if ( bIndexing == true ) {
                
                /* Finish the document */
                if ( iPrsFinishDocument(pppPrsParser, ppfPrsFormat, pfIndexerFile, pucTrueFilePath, zStartOffset, zCurrentOffset - 1, uiTermPosition - 1) != 0 ) {
                    iStatus = -1;
                    goto bailFromlPrsParseTextFile;
                }
            }
            
            break;
        }


        /* Reset the wide character line */
        if ( pwcLine != NULL ) {
            pwcLine[0] = L'\0';
        }
        
        /* Set the parse line pointer */
        pwcParseLinePtr = pwcLine;

        /* Convert the line from its native character set to wide characters */
        if ( bUtlStringsIsStringNULL(pucLine) == false ) {
            
            /* Set the line pointer */
            unsigned char   *pucLinePtr = pucLine;
            
            /* Use a separate variable for the line length */
            unsigned int    uiLineAllocatedByteLength = ulLineCapacity * sizeof(wchar_t);


            /* Clean the unicode if requested */
            if ( pppPrsParser->bCleanUnicode == true ) {
                
                /* Clean the unicode */
                if ( (iError = iLngUnicodeCleanUtf8String(pucLinePtr, PRS_UNICODE_REPLACEMENT_CHARACTER)) != LNG_NoError ) {
                    iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to clean the string, lng error: %d, string: '%s'", iError, pucLinePtr);
                }
            }


            /* Normalize the line if the unicode normalizer is enabled */
            if ( pppPrsParser->pvLngUnicodeNormalizer != NULL ) {
                
                /* Normalize the line */
                if ( (iError = iLngUnicodeNormalizeString(pppPrsParser->pvLngUnicodeNormalizer, pucLinePtr, uiLineLength, &pucNormalizedLine, &uiNormalizedLineCapacity)) != LNG_NoError ) {
                    iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to normalize the string, lng error: %d, string: '%s'", iError, pucLinePtr);
                }
                
                /* Set the line pointer */
                pucLinePtr = pucNormalizedLine;
                uiLineLength = s_strlen(pucLinePtr);
            }


            /* Convert the line from utf-8 to wide character, note the conversion error handling */
            if ( (iError = iLngConverterConvertString(pppPrsParser->pvLngConverter, ((pppPrsParser->bSkipUnicodeErrors == true) ? LNG_CONVERTER_SKIP_ON_ERROR : LNG_CONVERTER_RETURN_ON_ERROR), 
                    pucLinePtr, uiLineLength, (unsigned char **)&pwcLine, &uiLineAllocatedByteLength)) != LNG_NoError ) {
                iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to convert the string from utf-8 set to wide characters, lng error: %d, string: '%s'", iError, pucLinePtr);
            }

            /* Set the parse line pointer */
            pwcParseLinePtr = pwcLine;
        }


        /* Check for a document start if a start function was supplied */
        if ( (ppfPrsFormat->bPrsDocumentStartFunction != NULL) && (ppfPrsFormat->bPrsDocumentStartFunction(pwcParseLinePtr) == true) ) {
            
            /* We need to finish the current document if we are currently indexing */
            if ( bIndexing == true ) {

                /* Set the end character if it has not been set, this occurs if we have 
                ** both a start function and an end function, and we detect a new document
                ** start without having first detected a document end
                */
                if ( zEndOffset <= zStartOffset ) {
                    zEndOffset = (zCurrentOffset - uiLineLength) - 1;
                }
                
                /* Finish the document, we do this here because we dont want to process the current line, it belongs to the new document */
                if ( iPrsFinishDocument(pppPrsParser, ppfPrsFormat, pfIndexerFile, pucTrueFilePath, zStartOffset, zEndOffset, uiTermPosition - 1) != 0 ) {
                    iStatus = -1;
                    goto bailFromlPrsParseTextFile;
                }

                /* Check to see if we have reached the document count limit and bail if we have */
                if ( (pppPrsParser->uiDocumentCountMax > 0) && (pppPrsParser->uiDocumentCount >= pppPrsParser->uiDocumentCountMax) ) {
                    break;
                }

                /* Initialize for the next document */
                uiTermPosition = 1;
            }
            else {
                /* Turn on indexing */
                bIndexing = true;
            }
            
            /* Set the start character */
            zStartOffset = zCurrentOffset - uiLineLength;
            bSetStartCharacter = false;
        }

        /* We are always indexing if there is no start function, because if we
        ** reach the end of a document, we are automatically indexing the next one
        */
        else if ( ppfPrsFormat->bPrsDocumentStartFunction == NULL ) {
            
            /* Make sure indexing is turned on */
            bIndexing = true;
            
            /* Set the start character if needed */
            if ( bSetStartCharacter == true ) {
                zStartOffset = zCurrentOffset - uiLineLength;
                bSetStartCharacter = false;
            }
        }

        
        /* Check for a document end if an end function was supplied */ 
        if ( (ppfPrsFormat->bPrsDocumentEndFunction != NULL) && (ppfPrsFormat->bPrsDocumentEndFunction(pwcParseLinePtr) == true) && (fLineLength > 1) ) {
            
            /* Finish the document if we run into a document end */ 
            if ( bIndexing == true ) {
            
                /* Request that we set a new start character, finish the document, and turn off indexing */
                bSetStartCharacter = true;
                bFinishDocument = true;
                bIndexing = false;
                
                /* Set the end character */
                zEndOffset = zCurrentOffset - 1;
            }
        }
        
        /* No end function */
        else if ( ppfPrsFormat->bPrsDocumentEndFunction == NULL ) {
            /* Set the end character */
            zEndOffset = zCurrentOffset - 1;
        }



        /* Just loop to read the next line if we are not indexing and we dont need to finish a document */
        if ( (bIndexing == false) && (bFinishDocument == false) ) {
            continue;
        }



        /* Clear the parameters */
        uiLanguageID = LNG_LANGUAGE_ANY_ID;
        uiFieldID = 0;
        bIndexLine = true;
        bParseLine = true;
        bTermPositions = true;

        /* Process the document line */
        if ( ppfPrsFormat->vPrsDocumentLineFunction != NULL ) {
            ppfPrsFormat->vPrsDocumentLineFunction(pwcParseLinePtr, &uiLanguageID, &uiFieldID, &bIndexLine, &bParseLine, &bTermPositions);
        }


        /* Index the contents of the line */
        if ( bIndexLine == true ) {

            /* Parse the line */
            if ( bParseLine == true ) {

                /* Parse the text line */
                if ( iPrsParseTextLine(pppPrsParser, ppfPrsFormat, pfIndexerFile, pwcParseLinePtr, pwcParseLinePtr + s_wcslen(pwcParseLinePtr), 
                        uiLanguageID, uiFieldID, (bTermPositions == true) ? &uiTermPosition : NULL) != 0 ) {
                    if ( fprintf(pfIndexerFile, "M Failed to add the document terms.\n") < 0 ) {
                        iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a message line to the indexer");
                    }
                }
            }
            /* Get a term from the line and add */
            else {

                wchar_t     *pwcLinePtr = NULL;


                /* Find the start of the term */
                for ( pwcLinePtr = pwcParseLinePtr; *pwcLinePtr != L'\0'; pwcLinePtr++ ) { 
                    if ( iswalnum(*pwcLinePtr) != 0 ) {
                        break;
                    }
                }


                /* Is the term long enough to add? */
                if ( s_wcslen(pwcLinePtr) >= pppPrsParser->uiTermLengthMinimum ) {
    
                    /* Send the language line if the language is known */
                    if ( uiLanguageID != LNG_LANGUAGE_ANY_ID ) {

                        unsigned char   pucLanguageCode[LNG_LANGUAGE_CODE_LENGTH + 1] = {'\0'};
                        
                        if ( iLngGetLanguageCodeFromID(uiLanguageID, pucLanguageCode, LNG_LANGUAGE_CODE_LENGTH + 1) == LNG_NoError ) {
                
                            /* Send the language
                            ** L language{A}
                            */
                            if ( fprintf(pfIndexerFile, "L %s\n", pucLanguageCode) < 0 ) {
                                iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a language line to the indexer");
                            }
                        }
                    }

                    /* Send the term to the indexer */
                    if ( iPrsSendTermToIndexer(pppPrsParser, ppfPrsFormat, pfIndexerFile, pwcLinePtr, pwcLinePtr + s_wcslen(pwcLinePtr), 
                            uiFieldID, (bTermPositions == true) ? uiTermPosition : 0) != 0 ) {
                        if ( fprintf(pfIndexerFile, "M Failed to add a document term.\n") < 0 ) {
                            iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a message line to the indexer");
                        }
                    }
                    
                    /* Increment the term position */
                    if ( bTermPositions == true ) {
                        uiTermPosition++;
                    }
                }
            }
        }

    
        /* Finish the document if we were requested to do so */    
        if ( bFinishDocument == true ) {

            /* Finish the current document */
            if ( iPrsFinishDocument(pppPrsParser, ppfPrsFormat, pfIndexerFile, pucTrueFilePath, zStartOffset, zEndOffset, uiTermPosition - 1) != 0 ) {
                if ( fprintf(pfIndexerFile, "M Failed to finish adding a document.\n") < 0 ) {
                    iUtlLogPanic(UTL_LOG_CONTEXT, "Failed to send a message line to the indexer");
                }
            }
    
            /* Check to see if we have reached the document count limit */
            if ( (pppPrsParser->uiDocumentCountMax > 0) && (pppPrsParser->uiDocumentCount >= pppPrsParser->uiDocumentCountMax) ) {
                break;
            }
            
            /* Initialize for the next document */
            uiTermPosition = 1;
    
            /* Turn off the flag requesting that we finish the document */
            bFinishDocument = false;
        }
        

    }    /* while (true) */



    /* Bail label */
    bailFromlPrsParseTextFile:
    

    /* Close the file descriptor if we opened it ourselves */
    if ( bUtlStringsIsStringNULL(pucFilePath) == false ) {
        s_fclose(pfLocalFile);
    }

    /* Free the line pointers */
    s_free(pucLine);
    s_free(pucNormalizedLine);
    s_free(pwcLine);

    
    /* Increment the data length return pointer */
    *pfDataLength += fDataLength;


    return (iStatus);

}
Пример #19
0
Файл: util.c Проект: 4z3/sxiv
char* absolute_path(const char *filename)
{
	size_t len;
	const char *basename;
	char *dir, *dirname = NULL, *path = NULL, *s;
	char *cwd = NULL, *twd = NULL;

	if (filename == NULL || *filename == '\0' || *filename == '/')
		return NULL;

	len = FNAME_LEN;
	cwd = (char*) s_malloc(len);
	while ((s = getcwd(cwd, len)) == NULL && errno == ERANGE) {
		len *= 2;
		cwd = (char*) s_realloc(cwd, len);
	}
	if (s == NULL)
		goto error;

	s = strrchr(filename, '/');
	if (s != NULL) {
		len = s - filename;
		dirname = (char*) s_malloc(len + 1);
		strncpy(dirname, filename, len);
		dirname[len] = '\0';
		basename = s + 1;

		if (chdir(cwd) < 0)
			/* we're not able to come back afterwards */
			goto error;
		if (chdir(dirname) < 0)
			goto error;

		len = FNAME_LEN;
		twd = (char*) s_malloc(len);
		while ((s = getcwd(twd, len)) == NULL && errno == ERANGE) {
			len *= 2;
			twd = (char*) s_realloc(twd, len);
		}
		if (chdir(cwd) < 0)
			die("could not revert to prior working directory");
		if (s == NULL)
			goto error;
		dir = twd;
	} else {
		/* only a single filename given */
		basename = filename;
		dir = cwd;
	}

	len = strlen(dir) + strlen(basename) + 2;
	path = (char*) s_malloc(len);
	snprintf(path, len, "%s/%s", dir, basename);

	goto end;

error:
	if (path != NULL) {
		free(path);
		path = NULL;
	}

end:
	if (dirname != NULL)
		free(dirname);
	if (cwd != NULL)
		free(cwd);
	if (twd != NULL)
		free(twd);

	return path;
}
Пример #20
0
/* Originally based on, but in its current form merely inspired by Imlib2's
 * src/modules/loaders/loader_gif.c:load(), written by Carsten Haitzler.
 */
bool img_load_gif(img_t *img, const fileinfo_t *file) {
	GifFileType *gif;
	GifRowType *rows = NULL;
	GifRecordType rec;
	ColorMapObject *cmap;
	DATA32 bgpixel, *data, *ptr;
	DATA32 *prev_frame = NULL;
	Imlib_Image *im;
	int i, j, bg, r, g, b;
	int x, y, w, h, sw, sh;
	int intoffset[] = { 0, 4, 2, 1 };
	int intjump[] = { 8, 8, 4, 2 };
	int transp = -1;
	unsigned int delay = 0;
	bool err = false;

	if (img->multi.cap == 0) {
		img->multi.cap = 8;
		img->multi.frames = (img_frame_t*)
		                    s_malloc(sizeof(img_frame_t) * img->multi.cap);
	}
	img->multi.cnt = 0;
	img->multi.sel = 0;

	gif = DGifOpenFileName(file->path);
	if (gif == NULL) {
		warn("could not open gif file: %s", file->name);
		return false;
	}
	bg = gif->SBackGroundColor;
	sw = gif->SWidth;
	sh = gif->SHeight;

	do {
		if (DGifGetRecordType(gif, &rec) == GIF_ERROR) {
			err = true;
			break;
		}
		if (rec == EXTENSION_RECORD_TYPE) {
			int ext_code;
			GifByteType *ext = NULL;

			DGifGetExtension(gif, &ext_code, &ext);
			while (ext) {
				if (ext_code == 0xf9) {
					if (ext[1] & 1)
						transp = (int) ext[4];
					else
						transp = -1;

					delay = 10 * ((unsigned int) ext[3] << 8 | (unsigned int) ext[2]);
					if (delay)
						delay = MAX(delay, MIN_GIF_DELAY);

					/* TODO: handle disposal method, section 23.c.iv of
					         http://www.w3.org/Graphics/GIF/spec-gif89a.txt */
				}
				ext = NULL;
				DGifGetExtensionNext(gif, &ext);
			}
		} else if (rec == IMAGE_DESC_RECORD_TYPE) {
			if (DGifGetImageDesc(gif) == GIF_ERROR) {
				err = true;
				break;
			}
			x = gif->Image.Left;
			y = gif->Image.Top;
			w = gif->Image.Width;
			h = gif->Image.Height;

			rows = (GifRowType*) s_malloc(h * sizeof(GifRowType));
			for (i = 0; i < h; i++)
				rows[i] = (GifRowType) s_malloc(w * sizeof(GifPixelType));
			if (gif->Image.Interlace) {
				for (i = 0; i < 4; i++) {
					for (j = intoffset[i]; j < h; j += intjump[i])
						DGifGetLine(gif, rows[j], w);
				}
			} else {
				for (i = 0; i < h; i++)
					DGifGetLine(gif, rows[i], w);
			}

			ptr = data = (DATA32*) s_malloc(sizeof(DATA32) * sw * sh);
			cmap = gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap;
			r = cmap->Colors[bg].Red;
			g = cmap->Colors[bg].Green;
			b = cmap->Colors[bg].Blue;
			bgpixel = 0x00ffffff & (r << 16 | g << 8 | b);

			for (i = 0; i < sh; i++) {
				for (j = 0; j < sw; j++) {
					if (i < y || i >= y + h || j < x || j >= x + w ||
					    rows[i-y][j-x] == transp)
					{
						if (prev_frame != NULL)
							*ptr = prev_frame[i * sw + j];
						else
							*ptr = bgpixel;
					} else {
						r = cmap->Colors[rows[i-y][j-x]].Red;
						g = cmap->Colors[rows[i-y][j-x]].Green;
						b = cmap->Colors[rows[i-y][j-x]].Blue;
						*ptr = 0xff << 24 | r << 16 | g << 8 | b;
					}
					ptr++;
				}
			}

			im = imlib_create_image_using_copied_data(sw, sh, data);

			for (i = 0; i < h; i++)
				free(rows[i]);
			free(rows);
			free(data);

			if (im == NULL) {
				err = true;
				break;
			}

			imlib_context_set_image(im);
			prev_frame = imlib_image_get_data_for_reading_only();

			imlib_image_set_format("gif");
			if (transp >= 0)
				imlib_image_set_has_alpha(1);

			if (img->multi.cnt == img->multi.cap) {
				img->multi.cap *= 2;
				img->multi.frames = (img_frame_t*)
				                    s_realloc(img->multi.frames,
				                              img->multi.cap * sizeof(img_frame_t));
			}
			img->multi.frames[img->multi.cnt].im = im;
			img->multi.frames[img->multi.cnt].delay = delay ? delay : GIF_DELAY;
			img->multi.cnt++;
		}
	} while (rec != TERMINATE_RECORD_TYPE);

	DGifCloseFile(gif);

	if (err && !file->loaded)
		warn("corrupted gif file: %s", file->name);

	if (img->multi.cnt > 1) {
		imlib_context_set_image(img->im);
		imlib_free_image();
		img->im = img->multi.frames[0].im;
		img->multi.animate = GIF_AUTOPLAY;
	} else if (img->multi.cnt == 1) {
		imlib_context_set_image(img->multi.frames[0].im);
		imlib_free_image();
		img->multi.cnt = 0;
		img->multi.animate = false;
	}

	imlib_context_set_image(img->im);

	return !err;
}
Пример #21
0
int main (int argc, char *argv [])
{
    int
	argn,
	argmax,
	max,
	used,
	i,
	j,
	k,
	n;
    char
	*p;
    GROUP_
	*gr;

    no_mem_buffer = (char *) malloc (1024);

    get_programname (argv [0]);

    while (argc > 1 && argv [1][0] == '-') {
	if (! strcmp (argv [1], "-o")) {
	    argc--;
	    argv++;
	    outfile = argv [1];
	} else if (! strcmp (argv [1], "-l")) {
	    argc--;
	    argv++;
	    listfile = argv [1];
	}
	argc--;
	argv++;
    }

    if (argc < 2 && ! listfile)
	syntax ();

    if (listfile) {
	argc = 1;
	argmax = 256;
	p = argv [0];
	argv = (char **) s_malloc (argmax * sizeof (char *));
	argv [0] = p;
	fileopen (listfile);
	while (mygetline (FALSE)) {
	    if (argc == argmax) {
		argmax += 256;
		argv = (char **) s_realloc (argv, argmax * sizeof (char *));
	    }
	    argv [argc++] = s_strdup (buffer);
	}
    }
    
    fileopen (argv [1]);
    while (mygetline (FALSE)) {
	if (buffer [0] == 'l' || buffer [0] == 'L') {
	    if (n_lbls == max_lbls) {
		max_lbls += 256;
		lbls = (char **) s_realloc (lbls, max_lbls * sizeof (char *));
	    }
	    i = 1;
	    while (buffer [i] && isspace ((unsigned char) buffer [i]))
		i++;
	    lbls [n_lbls++] = s_strdup (buffer + i);
	}
    }
    fclose (fp);

    qsort (lbls, n_lbls, sizeof (char *), scmp);

    if (outfile) {
	fpout = fopen (outfile, "w");
	if (! fpout)
	    errit ("Creating file \"%s\": %s", outfile, strerror (errno));
    } else
	fpout = stdout;

    fprintf (fpout, "# Number of cluster files:\n%i\n# Number of labels:\n%i\n# Labels:\n", argc - 1, n_lbls);
    for (i = 0; i < n_lbls; i++)
	fprintf (fpout, "%s\n", lbls [i]);
    fprintf (fpout, "# Cluster count, cluster members, average cophenetic distance:\n");

    max = n_lbls - 1;
    cl = (CLUSTER_ *) s_malloc (max * sizeof (CLUSTER_));

    members = (char *) s_malloc ((n_lbls + 1) * sizeof (char));
    members [n_lbls] = '\0';

    for (argn = 1; argn < argc; argn++) {
	fileopen (argv [argn]);
	for (used = 0; used < max; used++) {
	    mygetline (TRUE);
	    if (sscanf (buffer, "%i %f%n", &(cl [used].index), &(cl [used].value), &i) < 2)
		errit ("Syntax error in \"%s\", line %i: \"%s\"", filename, inputline, buffer);
	    for (n = 0; n < 2; n++) {
		mygetline (TRUE);
		switch (buffer [0]) {
                    case 'l':
                    case 'L':
			cl [used].node [n] = LBL;
			i = 1;
			while (buffer [i] && isspace ((unsigned char) buffer [i]))
			    i++;
			p = bsearch (buffer + i, lbls, n_lbls, sizeof (char *), lscmp);
			if (! p)
			    errit ("Unknown label in \"%s\", line %i: \"%s\"", filename, inputline, buffer + i);
			cl [used].n [n].label = ((char **)p) - lbls;
			break;
                    case 'c':
                    case 'C':
			cl [used].node [n] = CLS;
			if (sscanf (buffer + 1, "%i", &(cl [used].n [n].cluster)) != 1)
			    errit ("Missing cluster number at line %i", inputline);
			break;
                    default:
			errit ("Syntax error at line %i: \"%s\"", inputline, buffer);
		}
	    }
	}

	/* replace indexes */
	for (i = 0; i < max; i++)
	    for (j = 0; j < 2; j++)
		if (cl [i].node [j] == CLS)
		    for (k = 0; k < max; k++)
			if (cl [i].n [j].cluster == cl [k].index) {
			    cl [i].n [j].cluster = k;
			    break;
			}

	for (i = 0; i < max; i++) {
	    for (j = 0; j < n_lbls; j++)
		members [j] = '-';
	    walk (i);

	    gr = findgroup ();
	    gr->n++;
	    gr->value += cl [i].value;

	}
	fclose (fp);
    }

    walkgroups (root);

    if (outfile)
	fclose (fpout);

    return 0;
}
Пример #22
0
void process_args ()
{
    char
	*s;
    int
	i,
	i1,
	i2,
	ii;
    float
	f;
    while (arg_c > 1 && arg_v [1][0] == '-') {
        if ((! strcmp (arg_v [1], "-sl")) || ! strcmp (arg_v [1], "-n")) {
	    update_function = update_sl;
	    name_update =  a_sl;
        } else if (! strcmp (arg_v [1], "-cl")) {
	    update_function = update_cl;
	    name_update =  a_cl;
        } else if (! strcmp (arg_v [1], "-ga")) {
	    update_function = update_ga;
	    name_update =  a_ga;
        } else if (! strcmp (arg_v [1], "-wa")) {
	    update_function = update_wa;
	    name_update =  a_wa;
        } else if (! strcmp (arg_v [1], "-uc")) {
	    update_function = update_uc;
	    name_update =  a_uc;
        } else if (! strcmp (arg_v [1], "-wc")) {
	    update_function = update_wc;
	    name_update =  a_wc;
        } else if ((! strcmp (arg_v [1], "-wm")) || ! strcmp (arg_v [1], "-w")) {
	    update_function = update_wm;
	    name_update =  a_wm;
	} else if (arg_v [1][1] == 'm') {
	    s = get_arg ();
	    ii = 1;
	    buffer [0] = buffr2 [0] = buffr3 [0] = '\0';
	    i = sscanf (s, "%[0-9]-%[0-9]+%[0-9]", buffer, buffr2, buffr3);
	    if (i > 1) {
		i1 = atoi (buffer);
		i2 = atoi (buffr2);
		if (i1 < 2 || (i2 && i2 < i1))
		    errit ("Illegal range for -m: %s", s);
		if (!i2)
		    i2 = i1;
		if (i == 3)
		    ii = atoi (buffr3);
		if (ii < 1)
		    ii = 1;
	    } else {
		i1 = i2 = atoi (s);
		if (i1 < 2)
		    errit ("Illegal value for -m: %i", i1);		    
	    }
	    for (i = i1; i <= i2; i += ii) {
		if (n_maxcl == max_maxcl) {
		    max_maxcl += 64;
		    maxcl = (int *) s_realloc (maxcl, max_maxcl * sizeof (int));
		}
		maxcl [n_maxcl++] = i;
	    }
	} else if (arg_v [1][1] == 'N') {
	    f = atof (get_arg ());
	    if (f < 0.0)
		errit ("Illegal value for -N: %g", f);
	    if (n_noise == max_noise) {
		max_noise += 64;
		noise = (float *) s_realloc (noise, max_noise * sizeof (float));
	    }
	    noise [n_noise++] = f;
	} else if (arg_v [1][1] == 'r') {
	    n_runs = atoi (get_arg ());
	    if (n_runs < 2)
		errit ("Option -r : argument should be a number larger than 1");
	} else if (arg_v [1][1] == 's') {
	    seed = atoi (get_arg ());
	    if (seed < 1)
		errit ("Option -s : seed must be positive");
	} else if (arg_v [1][1] == 'o') {
	    outfile = get_arg ();
        } else if (! strcmp (arg_v [1], "-b")) {
	    cophenetic = 1;
	    binary = 1;
        } else if (! strcmp (arg_v [1], "-c")) {
	    cophenetic = 1;
	    binary = 0;
        } else if (! strcmp (arg_v [1], "-u")) {
	    sorted = 0;
	} else
	    errit ("Illegal option '%s'", arg_v [1]);

	arg_c--;
	arg_v++;
    }
}