Beispiel #1
0
static char *find_program(const char *pgm)
{
    char **path = G_tokenize(getenv("PATH"), ";");
    char **pathext = G_tokenize(getenv("PATHEXT"), ";");
    char *result = find_program_dir_ext(pgm, path, pathext);
    G_free_tokens(path);
    G_free_tokens(pathext);
    return result;
}
Beispiel #2
0
/* get list of running monitors */
void list_mon(char ***list, int *n)
{
    int i;
    const char *name;
    const char *env_prefix = "MONITOR_";
    int env_prefix_len;
    char **tokens;
    
    env_prefix_len = strlen(env_prefix);
    
    *list = NULL;
    *n    = 0;
    tokens = NULL;
    for (i = 0; (name = G_get_env_name(i)); i++) {
	if (strncmp(env_prefix, name, env_prefix_len) == 0) {
	    tokens = G_tokenize(name, "_");
	    if (G_number_of_tokens(tokens) != 3 ||
		strcmp(tokens[2], "ENVFILE") != 0)
		continue;
	    *list = G_realloc(*list, (*n + 1) * sizeof(char *));
	    /* GRASS variable names are upper case, but monitor names are lower
	     * case. */
	    (*list)[*n] = G_store_lower(tokens[1]);
	    (*n)++;
	    G_free_tokens(tokens);
	    tokens = NULL;
	}
    }
    
}
Beispiel #3
0
void clean_env(const char *name)
{
    int i;
    char *u_name;
    const char *env_prefix = "MONITOR_";
    const char *env;
    int env_prefix_len;
    char **tokens;

    u_name = G_store_upper(name);
    env_prefix_len = strlen(env_prefix);
    
    tokens = NULL;
    for (i = 0; (env = G_get_env_name(i)); i++) {
	if (strncmp(env_prefix, env, env_prefix_len) != 0)
	    continue;
	
	tokens = G_tokenize(env, "_");
	if (G_number_of_tokens(tokens) != 3 ||
	    strcmp(tokens[1], u_name) != 0)
	    continue;
	G_unsetenv(env);
	i--; /* env has been removed for the list */
	G_free_tokens(tokens);
	tokens = NULL;
    }

    G_unsetenv("MONITOR");
}
Beispiel #4
0
static void add_rule(struct context *ctx, int type, const char *data)
{
    char **tokens;
    int ntokens;
    void **opts;
    int i;

    tokens = G_tokenize(data, ",");
    ntokens = G_number_of_tokens(tokens);
    opts = G_malloc(ntokens * sizeof(void *));

    for (i = 0; i < ntokens; i++) {
	char buf[256];
	char *name;

	strcpy(buf, tokens[i]);
	name = G_chop(buf);
	opts[i] = (name[0] == '-')
	    ? find_flag(ctx, name[1])
	    : find_option(ctx, name);
    }

    G_free_tokens(tokens);

    G__option_rule(type, ntokens, opts);
}
Beispiel #5
0
/*
  \brief Parse connection string in form:
  1) 'database_name'
  2) 'host=xx,port=xx,dbname=xx'
  
  \returns DB_OK on success
  \return DB_FAILED on failure
*/
int parse_conn(const char *str, PGCONN * pgconn)
{
    int i;
    char **tokens, delm[2];

    /* reset */
    G_zero(pgconn, sizeof(PGCONN));

    G_debug(3, "parse_conn: '%s'", str);

    if (strchr(str, '=') == NULL) {	/* db name only */
	pgconn->dbname = G_store(str);
    }
    else {
	delm[0] = ',';
	delm[1] = '\0';
	tokens = G_tokenize(str, delm);
	i = 0;
	while (tokens[i]) {
	    G_chop(tokens[i]);
	    G_debug(3, "token %d : %s", i, tokens[i]);
	    if (strncmp(tokens[i], "host", 4) == 0)
		pgconn->host = G_store(tokens[i] + 5);
	    else if (strncmp(tokens[i], "port", 4) == 0)
		pgconn->port = G_store(tokens[i] + 5);
	    else if (strncmp(tokens[i], "options", 7) == 0)
		pgconn->options = G_store(tokens[i] + 8);
	    else if (strncmp(tokens[i], "tty", 3) == 0)
		pgconn->tty = G_store(tokens[i] + 4);
	    else if (strncmp(tokens[i], "dbname", 6) == 0)
		pgconn->dbname = G_store(tokens[i] + 7);
	    else if (strncmp(tokens[i], "user", 4) == 0)
		G_warning(_("'user' in database definition is not supported, use db.login"));
	    /* pgconn->user = G_store ( tokens[i] + 5 ); */
	    else if (strncmp(tokens[i], "password", 8) == 0)
		/* pgconn->password = G_store ( tokens[i] + 9 ); */
		G_warning(_("'password' in database definition is not supported, use db.login"));
	    else if (strncmp(tokens[i], "schema", 6) == 0)
		pgconn->schema = G_store(tokens[i] + 7);
	    else {
		db_d_append_error("%s %s",
				  _("Unknown option in database definition "
				    "for PostgreSQL: "),
				  tokens[i]);
		return DB_FAILED;
	    }
	    i++;
	}
	G_free_tokens(tokens);
    }

    return DB_OK;
}
Beispiel #6
0
void parse_toplevel(struct context *ctx, const char *cmd)
{
    char **tokens;
    
    if (G_strcasecmp(cmd, "module") == 0) {
	ctx->state = S_MODULE;
	ctx->module = G_define_module();
	return;
    }

    if (G_strcasecmp(cmd, "flag") == 0) {
	ctx->state = S_FLAG;
	ctx->flag = G_define_flag();
	if (!ctx->first_flag)
	    ctx->first_flag = ctx->flag;
	return;
    }

    if (G_strncasecmp(cmd, "option", strlen("option")) == 0) {
	ctx->state = S_OPTION;
	
	tokens = G_tokenize(cmd, " ");
	if (G_number_of_tokens(tokens) > 1) {
	    /* standard option */
	    ctx->option = define_standard_option(tokens[1]);
	}
	else { 
	    ctx->option = G_define_option();
	}
	
	if (!ctx->first_option)
		ctx->first_option = ctx->option;
	
	G_free_tokens(tokens);
	return;
    }

    if (G_strcasecmp(cmd, "rules") == 0) {
	ctx->state = S_RULES;
	return;
    }

    fprintf(stderr, _("Unknown command \"%s\" at line %d\n"), cmd, ctx->line);
}
Beispiel #7
0
int parse_option_pg(const char *option, char **key, char **value)
{
    char **tokens;
    
    tokens = G_tokenize(option, "=");
    if (G_number_of_tokens(tokens) != 2) {
        G_warning(_("Unable to parse option '%s'"), option);
        return 1;
    }
    
    *key = G_store(tokens[0]);
    G_str_to_lower(*key);
    
    *value = G_store(tokens[1]);
    G_str_to_lower(*value);

    G_free_tokens(tokens);

    return 0;
}
Beispiel #8
0
int read_env_file(const char *path)
{
    FILE *fd;
    char buf[1024];
    char **token;
    
    fd = fopen(path, "r");
    if (!fd)
	return -1;

    token = NULL;
    while (G_getl2(buf, sizeof(buf) - 1, fd) != 0) {
	token = G_tokenize(buf, "=");
	if (G_number_of_tokens(token) != 2)
	    continue;
	G_debug(3, "\tread_env_file(): %s=%s", token[0], token[1]);
	G_putenv(token[0], token[1]);
	G_free_tokens(token);
	token = NULL;
    }

    return 0;
}
Beispiel #9
0
int main(int argc, char *argv[])
{
    char file[GPATH_MAX], name[GNAME_MAX];
    const char *search_mapset, *mapset;
    struct GModule *module;
    struct Option *elem_opt;
    struct Option *mapset_opt;
    struct Option *file_opt;
    struct Flag *n_flag, *l_flag;

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("map management"));
    G_add_keyword(_("data base files"));
    module->description =
	_("Searches for GRASS data base files "
	  "and sets variables for the shell.");

    G_gisinit(argv[0]);

    /* Define the different options */

    elem_opt = G_define_option();
    elem_opt->key = "element";
    elem_opt->type = TYPE_STRING;
    elem_opt->required = YES;
    elem_opt->description = _("Name of an element");

    file_opt = G_define_option();
    file_opt->key = "file";
    file_opt->type = TYPE_STRING;
    file_opt->required = YES;
    file_opt->description = _("Name of an existing map");

    mapset_opt = G_define_option();
    mapset_opt->key = "mapset";
    mapset_opt->type = TYPE_STRING;
    mapset_opt->required = NO;
    mapset_opt->label = _("Name of a mapset (default: search path)");
    mapset_opt->description = _("'.' for current mapset");

    n_flag = G_define_flag();
    n_flag->key = 'n';
    n_flag->description = _("Don't add quotes");

    l_flag = G_define_flag();
    l_flag->key = 'l';
    l_flag->description = _("List available elements and exit");
    l_flag->suppress_required = YES;

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (l_flag->answer) {
	list_elements();
	return EXIT_SUCCESS;
    }

    search_mapset = mapset_opt->answer;
    if (!search_mapset) {
	search_mapset = G_store("");
    }
    if (strcmp(".", search_mapset) == 0)
	search_mapset = G_mapset();
    
    if (mapset_opt->answer && strlen(mapset_opt->answer) > 0) {
	char **map_mapset = G_tokenize(file_opt->answer, "@");

	if (G_number_of_tokens(map_mapset) > 1) {
	    if (strcmp(map_mapset[1], mapset_opt->answer))
		G_fatal_error(_("Parameter 'file' contains reference to <%s> mapset, "
				"but mapset parameter <%s> does not correspond"),
			      map_mapset[1], mapset_opt->answer);
	    else
		strcpy(name, file_opt->answer);
	}
	if (G_number_of_tokens(map_mapset) == 1)
	    strcpy(name, file_opt->answer);
	G_free_tokens(map_mapset);
    }
    else
	strcpy(name, file_opt->answer);

    mapset = G_find_file2(elem_opt->answer, name, search_mapset);
    if (mapset) {
	char xname[GNAME_MAX], xmapset[GMAPSET_MAX];
	const char *qchar = n_flag->answer ? "" : "'";
	const char *qual = G_fully_qualified_name(name, mapset);
	G_unqualified_name(name, mapset, xname, xmapset);
	G_file_name(file, elem_opt->answer, name, mapset);
	fprintf(stdout, "name=%s%s%s\n", qchar, xname, qchar);
	fprintf(stdout, "mapset=%s%s%s\n", qchar, xmapset, qchar);
	fprintf(stdout, "fullname=%s%s%s\n", qchar, qual, qchar);
	fprintf(stdout, "file=%s%s%s\n", qchar, file, qchar);

	return EXIT_SUCCESS;
    }
    else {
	fprintf(stdout, "name=\n");
	fprintf(stdout, "mapset=\n");
	fprintf(stdout, "fullname=\n");
	fprintf(stdout, "file=\n");
    }
    
    return EXIT_FAILURE;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
    struct file_info Current, Trans, Coord;

    struct GModule *module;

    struct Option *vold, *vnew, *pointsfile, *xshift, *yshift, *zshift,
	*xscale, *yscale, *zscale, *zrot, *columns, *table, *field;
    struct Flag *quiet_flag, *tozero_flag, *shift_flag, *print_mat_flag;

    char *mapset, mon[4], date[40], buf[1000];
    struct Map_info Old, New;
    int ifield;
    int day, yr;
    BOUND_BOX box;

    double ztozero;
    double trans_params[7];	/* xshift, ..., xscale, ..., zrot */

    /* columns */
    unsigned int i;
    int idx, out3d;
    char **tokens;
    char *columns_name[7];	/* xshift, yshift, zshift, xscale, yscale, zscale, zrot */

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, transformation");
    module->description =
	_("Performs an affine transformation (shift, scale and rotate, "
	  "or GPCs) on vector map.");

    /* remove in GRASS7 */
    quiet_flag = G_define_flag();
    quiet_flag->key = 'q';
    quiet_flag->description =
	_("Suppress display of residuals or other information");

    tozero_flag = G_define_flag();
    tozero_flag->key = 't';
    tozero_flag->description = _("Shift all z values to bottom=0");
    tozero_flag->guisection = _("Custom");

    print_mat_flag = G_define_flag();
    print_mat_flag->key = 'm';
    print_mat_flag->description =
	_("Print the transformation matrix to stdout");
    
    shift_flag = G_define_flag();
    shift_flag->key = 's';
    shift_flag->description =
	_("Instead of points use transformation parameters "
	  "(xshift, yshift, zshift, xscale, yscale, zscale, zrot)");
    shift_flag->guisection = _("Custom");
	
    vold = G_define_standard_option(G_OPT_V_INPUT);

    field = G_define_standard_option(G_OPT_V_FIELD);
    field->answer = "-1";
    
    vnew = G_define_standard_option(G_OPT_V_OUTPUT);

    pointsfile = G_define_standard_option(G_OPT_F_INPUT);
    pointsfile->key = "pointsfile";
    pointsfile->required = NO;
    pointsfile->label = _("ASCII file holding transform coordinates");
    pointsfile->description = _("If not given, transformation parameters "
				"(xshift, yshift, zshift, xscale, yscale, zscale, zrot) are used instead");

    pointsfile->gisprompt = "old_file,file,points";
    pointsfile->guisection = _("Points");
    
    xshift = G_define_option();
    xshift->key = "xshift";
    xshift->type = TYPE_DOUBLE;
    xshift->required = NO;
    xshift->multiple = NO;
    xshift->description = _("Shifting value for x coordinates");
    xshift->answer = "0.0";
    xshift->guisection = _("Custom");

    yshift = G_define_option();
    yshift->key = "yshift";
    yshift->type = TYPE_DOUBLE;
    yshift->required = NO;
    yshift->multiple = NO;
    yshift->description = _("Shifting value for y coordinates");
    yshift->answer = "0.0";
    yshift->guisection = _("Custom");

    zshift = G_define_option();
    zshift->key = "zshift";
    zshift->type = TYPE_DOUBLE;
    zshift->required = NO;
    zshift->multiple = NO;
    zshift->description = _("Shifting value for z coordinates");
    zshift->answer = "0.0";
    zshift->guisection = _("Custom");

    xscale = G_define_option();
    xscale->key = "xscale";
    xscale->type = TYPE_DOUBLE;
    xscale->required = NO;
    xscale->multiple = NO;
    xscale->description = _("Scaling factor for x coordinates");
    xscale->answer = "1.0";
    xscale->guisection = _("Custom");

    yscale = G_define_option();
    yscale->key = "yscale";
    yscale->type = TYPE_DOUBLE;
    yscale->required = NO;
    yscale->multiple = NO;
    yscale->description = _("Scaling factor for y coordinates");
    yscale->answer = "1.0";
    yscale->guisection = _("Custom");

    zscale = G_define_option();
    zscale->key = "zscale";
    zscale->type = TYPE_DOUBLE;
    zscale->required = NO;
    zscale->multiple = NO;
    zscale->description = _("Scaling factor for z coordinates");
    zscale->answer = "1.0";
    zscale->guisection = _("Custom");

    zrot = G_define_option();
    zrot->key = "zrot";
    zrot->type = TYPE_DOUBLE;
    zrot->required = NO;
    zrot->multiple = NO;
    zrot->description =
	_("Rotation around z axis in degrees counterclockwise");
    zrot->answer = "0.0";
    zrot->guisection = _("Custom");

    table = G_define_standard_option(G_OPT_TABLE);
    table->description =
	_("Name of table containing transformation parameters");
    table->guisection = _("Attributes");

    columns = G_define_option();
    columns->key = "columns";
    columns->type = TYPE_STRING;
    columns->required = NO;
    columns->multiple = NO;
    columns->label =
	_("Name of attribute column(s) used as transformation parameters");
    columns->description =
	_("Format: parameter:column, e.g. xshift:xs,yshift:ys,zrot:zr");
    columns->guisection = _("Attributes");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_strcpy(Current.name, vold->answer);
    G_strcpy(Trans.name, vnew->answer);

    Vect_check_input_output_name(vold->answer, vnew->answer, GV_FATAL_EXIT);
    
    out3d = WITHOUT_Z;
    
    ifield = atoi(field->answer);

    if (shift_flag->answer)
	G_warning(_("The '%c' flag is deprecated and will be removed in future. "
		   "Transformation parameters are used automatically when no pointsfile is given."),
		  shift_flag->key);

    /* please remove in GRASS7 */
    if (quiet_flag->answer) {
	G_warning(_("The '%c' flag is deprecated and will be removed in future. "
		   "Please use '--quiet' instead."), quiet_flag->key);
	G_putenv("GRASS_VERBOSE", "0");
    }

    /* if a table is specified, require columns and layer */
    /* if columns are specified, but no table, require layer > 0 and use 
     * the table attached to that layer */
    if (table->answer && !columns->answer) {
	G_fatal_error(_("Column names are not defined. Please use '%s' parameter."),
		      columns->key);
    }

    if ((columns->answer || table->answer) && ifield < 1) {
	G_fatal_error(_("Please specify a valid layer with '%s' parameter."),
		      field->key);
    }

    if (table->answer && strcmp(vnew->answer, table->answer) == 0) {
	G_fatal_error(_("Name of table and name for output vector map must be different. "
		       "Otherwise the table is overwritten."));
    }

    if (!columns->answer && !table->answer)
	ifield = -1;

    if (pointsfile->answer != NULL && !shift_flag->answer) {
	G_strcpy(Coord.name, pointsfile->answer);
    }
    else {
	Coord.name[0] = '\0';
    }

    /* open coord file */
    if (Coord.name[0] != '\0') {
	if ((Coord.fp = fopen(Coord.name, "r")) == NULL)
	    G_fatal_error(_("Unable to open file with coordinates <%s>"),
			  Coord.name);
    }

    /* tokenize columns names */
    for (i = 0; i <= IDX_ZROT; i++) {
	columns_name[i] = NULL;
    }
    i = 0;
    if (columns->answer) {
	while (columns->answers[i]) {
	    tokens = G_tokenize(columns->answers[i], ":");
	    if (G_number_of_tokens(tokens) == 2) {
		if (strcmp(tokens[0], xshift->key) == 0)
		    idx = IDX_XSHIFT;
		else if (strcmp(tokens[0], yshift->key) == 0)
		    idx = IDX_YSHIFT;
		else if (strcmp(tokens[0], zshift->key) == 0)
		    idx = IDX_ZSHIFT;
		else if (strcmp(tokens[0], xscale->key) == 0)
		    idx = IDX_XSCALE;
		else if (strcmp(tokens[0], yscale->key) == 0)
		    idx = IDX_YSCALE;
		else if (strcmp(tokens[0], zscale->key) == 0)
		    idx = IDX_ZSCALE;
		else if (strcmp(tokens[0], zrot->key) == 0)
		    idx = IDX_ZROT;
		else
		    idx = -1;

		if (idx != -1)
		    columns_name[idx] = G_store(tokens[1]);

		G_free_tokens(tokens);
	    }
	    else {
		G_fatal_error(_("Unable to tokenize column string: [%s]"),
			      columns->answers[i]);
	    }
	    i++;
	}
    }

    /* determine transformation parameters */
    trans_params[IDX_XSHIFT] = atof(xshift->answer);
    trans_params[IDX_YSHIFT] = atof(yshift->answer);
    trans_params[IDX_ZSHIFT] = atof(zshift->answer);
    trans_params[IDX_XSCALE] = atof(xscale->answer);
    trans_params[IDX_YSCALE] = atof(yscale->answer);
    trans_params[IDX_ZSCALE] = atof(zscale->answer);
    trans_params[IDX_ZROT] = atof(zrot->answer);

    /* open vector maps */
    if ((mapset = G_find_vector2(vold->answer, "")) == NULL)
	G_fatal_error(_("Vector map <%s> not found"), vold->answer);

    Vect_open_old(&Old, vold->answer, mapset);
    
    /* should output be 3D ? 
     * note that z-scale and ztozero have no effect with input 2D */
    if (Vect_is_3d(&Old) || trans_params[IDX_ZSHIFT] != 0. ||
	columns_name[IDX_ZSHIFT])
	out3d = WITH_Z;

    Vect_open_new(&New, vnew->answer, out3d);
    
    /* copy and set header */
    Vect_copy_head_data(&Old, &New);

    Vect_hist_copy(&Old, &New);
    Vect_hist_command(&New);

    sprintf(date, "%s", G_date());
    sscanf(date, "%*s%s%d%*s%d", mon, &day, &yr);
    sprintf(date, "%s %d %d", mon, day, yr);
    Vect_set_date(&New, date);

    Vect_set_person(&New, G_whoami());

    sprintf(buf, "transformed from %s", vold->answer);
    Vect_set_map_name(&New, buf);

    Vect_set_scale(&New, 1);
    Vect_set_zone(&New, 0);
    Vect_set_thresh(&New, 0.0);

    /* points file */
    if (Coord.name[0]) {
	create_transform_from_file(&Coord, quiet_flag->answer);

	if (Coord.name[0] != '\0')
	    fclose(Coord.fp);
    }

    Vect_get_map_box(&Old, &box);

    /* z to zero */
    if (tozero_flag->answer)
	ztozero = 0 - box.B;
    else
	ztozero = 0;

    /* do the transformation */
    transform_digit_file(&Old, &New, Coord.name[0] ? 1 : 0,
			 ztozero, trans_params,
			 table->answer, columns_name, ifield);

    if (Vect_copy_tables(&Old, &New, 0))
        G_warning(_("Failed to copy attribute table to output map"));
    Vect_close(&Old);
    Vect_build(&New);

    if (!quiet_flag->answer) {
	Vect_get_map_box(&New, &box);
	G_message(_("\nNew vector map <%s> boundary coordinates:"),
		  vnew->answer);
	G_message(_(" N: %-10.3f    S: %-10.3f"), box.N, box.S);
	G_message(_(" E: %-10.3f    W: %-10.3f"), box.E, box.W);
	G_message(_(" B: %6.3f    T: %6.3f"), box.B, box.T);

	/* print the transformation matrix if requested */
	if (print_mat_flag->answer)
	    print_transform_matrix();
    }

    Vect_close(&New);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Beispiel #11
0
int main(int argc, char *argv[])
{

    FILE *in_fp;
    int out_fd;
    char *infile, *outmap;
    int xcol, ycol, zcol, max_col, percent;
    int do_zfilter;
    int method = -1;
    int bin_n, bin_min, bin_max, bin_sum, bin_sumsq, bin_index;
    double zrange_min, zrange_max, d_tmp;
    char *fs;			/* field delim */
    off_t filesize;
    int linesize;
    long estimated_lines;
    int from_stdin;
    int can_seek;

    RASTER_MAP_TYPE rtype;
    struct History history;
    char title[64];
    void *n_array, *min_array, *max_array, *sum_array, *sumsq_array,
	*index_array;
    void *raster_row, *ptr;
    struct Cell_head region;
    int rows, cols;		/* scan box size */
    int row, col;		/* counters */

    int pass, npasses;
    unsigned long line;
    char buff[BUFFSIZE];
    double x, y, z;
    char **tokens;
    int ntokens;		/* number of tokens */
    double pass_north, pass_south;
    int arr_row, arr_col;
    unsigned long count, count_total;

    double min = 0.0 / 0.0;	/* init as nan */
    double max = 0.0 / 0.0;	/* init as nan */
    double zscale = 1.0;
    size_t offset, n_offset;
    int n = 0;
    double sum = 0.;
    double sumsq = 0.;
    double variance, mean, skew, sumdev;
    int pth = 0;
    double trim = 0.0;

    int j, k;
    int head_id, node_id;
    int r_low, r_up;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *delim_opt, *percent_opt,
	*type_opt;
    struct Option *method_opt, *xcol_opt, *ycol_opt, *zcol_opt, *zrange_opt,
	*zscale_opt;
    struct Option *trim_opt, *pth_opt;
    struct Flag *scan_flag, *shell_style, *skipline;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, import, LIDAR");
    module->description =
	_("Create a raster map from an assemblage of many coordinates using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_INPUT);
    input_opt->description =
	_("ASCII file containing input data (or \"-\" to read from stdin)");

    output_opt = G_define_standard_option(G_OPT_R_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");

    type_opt = G_define_option();
    type_opt->key = "type";
    type_opt->type = TYPE_STRING;
    type_opt->required = NO;
    type_opt->options = "CELL,FCELL,DCELL";
    type_opt->answer = "FCELL";
    type_opt->description = _("Storage type for resultant raster map");

    delim_opt = G_define_standard_option(G_OPT_F_SEP);
    delim_opt->guisection = _("Input");

    xcol_opt = G_define_option();
    xcol_opt->key = "x";
    xcol_opt->type = TYPE_INTEGER;
    xcol_opt->required = NO;
    xcol_opt->answer = "1";
    xcol_opt->description =
	_("Column number of x coordinates in input file (first column is 1)");
    xcol_opt->guisection = _("Input");

    ycol_opt = G_define_option();
    ycol_opt->key = "y";
    ycol_opt->type = TYPE_INTEGER;
    ycol_opt->required = NO;
    ycol_opt->answer = "2";
    ycol_opt->description = _("Column number of y coordinates in input file");
    ycol_opt->guisection = _("Input");

    zcol_opt = G_define_option();
    zcol_opt->key = "z";
    zcol_opt->type = TYPE_INTEGER;
    zcol_opt->required = NO;
    zcol_opt->answer = "3";
    zcol_opt->description = _("Column number of data values in input file");
    zcol_opt->guisection = _("Input");

    zrange_opt = G_define_option();
    zrange_opt->key = "zrange";
    zrange_opt->type = TYPE_DOUBLE;
    zrange_opt->required = NO;
    zrange_opt->key_desc = "min,max";
    zrange_opt->description = _("Filter range for z data (min,max)");

    zscale_opt = G_define_option();
    zscale_opt->key = "zscale";
    zscale_opt->type = TYPE_DOUBLE;
    zscale_opt->required = NO;
    zscale_opt->answer = "1.0";
    zscale_opt->description = _("Scale to apply to z data");

    percent_opt = G_define_option();
    percent_opt->key = "percent";
    percent_opt->type = TYPE_INTEGER;
    percent_opt->required = NO;
    percent_opt->answer = "100";
    percent_opt->options = "1-100";
    percent_opt->description = _("Percent of map to keep in memory");

    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

    trim_opt = G_define_option();
    trim_opt->key = "trim";
    trim_opt->type = TYPE_DOUBLE;
    trim_opt->required = NO;
    trim_opt->options = "0-50";
    trim_opt->description =
	_("Discard <trim> percent of the smallest and <trim> percent of the largest observations");
    trim_opt->guisection = _("Statistic");

    scan_flag = G_define_flag();
    scan_flag->key = 's';
    scan_flag->description = _("Scan data file for extent then exit");

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description =
	_("In scan mode, print using shell script style");

    skipline = G_define_flag();
    skipline->key = 'i';
    skipline->description = _("Ignore broken lines");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* parse input values */
    infile = input_opt->answer;
    outmap = output_opt->answer;

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1;
    }

    fs = delim_opt->answer;
    if (strcmp(fs, "\\t") == 0)
	fs = "\t";
    if (strcmp(fs, "tab") == 0)
	fs = "\t";
    if (strcmp(fs, "space") == 0)
	fs = " ";

    xcol = atoi(xcol_opt->answer);
    ycol = atoi(ycol_opt->answer);
    zcol = atoi(zcol_opt->answer);
    if ((xcol < 0) || (ycol < 0) || (zcol < 0))
	G_fatal_error(_("Please specify a reasonable column number."));
    max_col = (xcol > ycol) ? xcol : ycol;
    max_col = (zcol > max_col) ? zcol : max_col;

    percent = atoi(percent_opt->answer);
    zscale = atof(zscale_opt->answer);

    /* parse zrange */
    do_zfilter = FALSE;
    if (zrange_opt->answer != NULL) {
	if (zrange_opt->answers[0] == NULL)
	    G_fatal_error(_("Invalid zrange"));

	sscanf(zrange_opt->answers[0], "%lf", &zrange_min);
	sscanf(zrange_opt->answers[1], "%lf", &zrange_max);
	do_zfilter = TRUE;

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }

    /* figure out what maps we need in memory */
    /*  n               n
       min              min
       max              max
       range            min max         max - min
       sum              sum
       mean             sum n           sum/n
       stddev           sum sumsq n     sqrt((sumsq - sum*sum/n)/n)
       variance         sum sumsq n     (sumsq - sum*sum/n)/n
       coeff_var        sum sumsq n     sqrt((sumsq - sum*sum/n)/n) / (sum/n)
       median           n               array index to linked list
       percentile       n               array index to linked list
       skewness         n               array index to linked list
       trimmean         n               array index to linked list
     */
    bin_n = FALSE;
    bin_min = FALSE;
    bin_max = FALSE;
    bin_sum = FALSE;
    bin_sumsq = FALSE;
    bin_index = FALSE;

    if (strcmp(method_opt->answer, "n") == 0) {
	method = METHOD_N;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "min") == 0) {
	method = METHOD_MIN;
	bin_min = TRUE;
    }
    if (strcmp(method_opt->answer, "max") == 0) {
	method = METHOD_MAX;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "range") == 0) {
	method = METHOD_RANGE;
	bin_min = TRUE;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "sum") == 0) {
	method = METHOD_SUM;
	bin_sum = TRUE;
    }
    if (strcmp(method_opt->answer, "mean") == 0) {
	method = METHOD_MEAN;
	bin_sum = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "stddev") == 0) {
	method = METHOD_STDDEV;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "variance") == 0) {
	method = METHOD_VARIANCE;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "coeff_var") == 0) {
	method = METHOD_COEFF_VAR;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "median") == 0) {
	method = METHOD_MEDIAN;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "percentile") == 0) {
	if (pth_opt->answer != NULL)
	    pth = atoi(pth_opt->answer);
	else
	    G_fatal_error(_("Unable to calculate percentile without the pth option specified!"));
	method = METHOD_PERCENTILE;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "skewness") == 0) {
	method = METHOD_SKEWNESS;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "trimmean") == 0) {
	if (trim_opt->answer != NULL)
	    trim = atof(trim_opt->answer) / 100.0;
	else
	    G_fatal_error(_("Unable to calculate trimmed mean without the trim option specified!"));
	method = METHOD_TRIMMEAN;
	bin_index = TRUE;
    }

    if (strcmp("CELL", type_opt->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", type_opt->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (method == METHOD_N)
	rtype = CELL_TYPE;


    G_get_window(&region);
    rows = (int)(region.rows * (percent / 100.0));
    cols = region.cols;

    G_debug(2, "region.n=%f  region.s=%f  region.ns_res=%f", region.north,
	    region.south, region.ns_res);
    G_debug(2, "region.rows=%d  [box_rows=%d]  region.cols=%d", region.rows,
	    rows, region.cols);

    npasses = (int)ceil(1.0 * region.rows / rows);

    if (!scan_flag->answer) {
	/* allocate memory (test for enough before we start) */
	if (bin_n)
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	if (bin_min)
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_max)
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sum)
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sumsq)
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_index)
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));

	/* and then free it again */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index)
	    G_free(index_array);

	/** end memory test **/
    }


    /* open input file */
    if (strcmp("-", infile) == 0) {
	from_stdin = TRUE;
	in_fp = stdin;
	infile = G_store("stdin");	/* filename for history metadata */
    }
    else {
	if ((in_fp = fopen(infile, "r")) == NULL)
	    G_fatal_error(_("Unable to open input file <%s>"), infile);
    }

    can_seek = fseek(in_fp, 0, SEEK_SET) == 0;

    /* can't rewind() non-files */
    if (!can_seek && npasses != 1) {
	G_warning(_("If input is not from a file it is only possible to perform a single pass."));
	npasses = 1;
    }

    if (scan_flag->answer) {
	if (zrange_opt->answer)
	    G_warning(_("zrange will not be taken into account during scan"));

	scan_bounds(in_fp, xcol, ycol, zcol, fs, shell_style->answer,
		    skipline->answer, zscale);

	if (!from_stdin)
	    fclose(in_fp);

	exit(EXIT_SUCCESS);
    }


    /* open output map */
    out_fd = G_open_raster_new(outmap, rtype);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), outmap);

    if (can_seek) {
	/* guess at number of lines in the file without actually reading it all in */
	for (line = 0; line < 10; line++) {	/* arbitrarily use 10th line for guess */
	    if (0 == G_getl2(buff, BUFFSIZE - 1, in_fp))
		break;
	    linesize = strlen(buff) + 1;
	}
	fseek(in_fp, 0L, SEEK_END);
	filesize = ftell(in_fp);
	rewind(in_fp);
	if (linesize < 6)	/* min possible: "0,0,0\n" */
	    linesize = 6;
	estimated_lines = filesize / linesize;
	G_debug(2, "estimated number of lines in file: %ld", estimated_lines);
    }
    else
	estimated_lines = -1;

    /* allocate memory for a single row of output data */
    raster_row = G_allocate_raster_buf(rtype);

    G_message(_("Reading data ..."));

    count_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {
	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	if (can_seek)
	    rewind(in_fp);

	/* figure out segmentation */
	pass_north = region.north - (pass - 1) * rows * region.ns_res;
	if (pass == npasses)
	    rows = region.rows - (pass - 1) * rows;
	pass_south = pass_north - rows * region.ns_res;

	G_debug(2, "pass=%d/%d  pass_n=%f  pass_s=%f  rows=%d",
		pass, npasses, pass_north, pass_south, rows);


	if (bin_n) {
	    G_debug(2, "allocating n_array");
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(n_array, rows, cols, CELL_TYPE, 0);
	}
	if (bin_min) {
	    G_debug(2, "allocating min_array");
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(min_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_max) {
	    G_debug(2, "allocating max_array");
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(max_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_sum) {
	    G_debug(2, "allocating sum_array");
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sum_array, rows, cols, rtype, 0);
	}
	if (bin_sumsq) {
	    G_debug(2, "allocating sumsq_array");
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sumsq_array, rows, cols, rtype, 0);
	}
	if (bin_index) {
	    G_debug(2, "allocating index_array");
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(index_array, rows, cols, CELL_TYPE, -1);	/* fill with NULLs */
	}

	line = 0;
	count = 0;
	G_percent_reset();

	while (0 != G_getl2(buff, BUFFSIZE - 1, in_fp)) {
	    line++;

	    if (line % 10000 == 0) {	/* mod for speed */
		if (!can_seek)
		    G_clicker();
		else if (line < estimated_lines)
		    G_percent(line, estimated_lines, 3);
	    }

	    if ((buff[0] == '#') || (buff[0] == '\0')) {
		continue;	/* line is a comment or blank */
	    }

	    G_chop(buff);	/* remove leading and trailing whitespace from the string.  unneded?? */
	    tokens = G_tokenize(buff, fs);
	    ntokens = G_number_of_tokens(tokens);

	    if ((ntokens < 3) || (max_col > ntokens)) {
		if (skipline->answer) {
		    G_warning(_("Not enough data columns. "
				"Incorrect delimiter or column number? "
				"Found the following character(s) in row %lu:\n[%s]"),
			      line, buff);
		    G_warning(_("Line ignored as requested"));
		    continue;	/* line is garbage */
		}
		else {
		    G_fatal_error(_("Not enough data columns. "
				    "Incorrect delimiter or column number? "
				    "Found the following character(s) in row %lu:\n[%s]"),
				  line, buff);
		}
	    }

	    /* too slow?
	       if ( G_projection() == PROJECTION_LL ) {
	       G_scan_easting( tokens[xcol-1], &x, region.proj);
	       G_scan_northing( tokens[ycol-1], &y, region.proj);
	       }
	       else {
	     */
	    if (1 != sscanf(tokens[ycol - 1], "%lf", &y))
		G_fatal_error(_("Bad y-coordinate line %lu column %d. <%s>"),
			      line, ycol, tokens[ycol - 1]);
	    if (y <= pass_south || y > pass_north) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[xcol - 1], "%lf", &x))
		G_fatal_error(_("Bad x-coordinate line %lu column %d. <%s>"),
			      line, xcol, tokens[xcol - 1]);
	    if (x < region.west || x > region.east) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[zcol - 1], "%lf", &z))
		G_fatal_error(_("Bad z-coordinate line %lu column %d. <%s>"),
			      line, zcol, tokens[zcol - 1]);

	    z = z * zscale;

	    if (zrange_opt->answer) {
		if (z < zrange_min || z > zrange_max) {
		    G_free_tokens(tokens);
		    continue;
		}
	    }

	    count++;
	    /*          G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */
	    G_free_tokens(tokens);

	    /* find the bin in the current array box */
	    arr_row = (int)((pass_north - y) / region.ns_res);
	    arr_col = (int)((x - region.west) / region.ew_res);

	    /*          G_debug(5, "arr_row: %d   arr_col: %d", arr_row, arr_col); */

	    /* The range should be [0,cols-1]. We use (int) to round down,
	       but if the point exactly on eastern edge arr_col will be /just/
	       on the max edge .0000000 and end up on the next row.
	       We could make above bounds check "if(x>=region.east) continue;"
	       But instead we go to all sorts of trouble so that not one single
	       data point is lost. GE is too small to catch them all.
	       We don't try to make y happy as percent segmenting will make some
	       points happen twice that way; so instead we use the y<= test above.
	     */
	    if (arr_col >= cols) {
		if (((x - region.west) / region.ew_res) - cols <
		    10 * GRASS_EPSILON)
		    arr_col--;
		else {		/* oh well, we tried. */
		    G_debug(3,
			    "skipping extraneous data point [%.3f], column %d of %d",
			    x, arr_col, cols);
		    continue;
		}
	    }

	    if (bin_n)
		update_n(n_array, cols, arr_row, arr_col);
	    if (bin_min)
		update_min(min_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_max)
		update_max(max_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sum)
		update_sum(sum_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sumsq)
		update_sumsq(sumsq_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_index) {
		ptr = index_array;
		ptr =
		    G_incr_void_ptr(ptr,
				    ((arr_row * cols) +
				     arr_col) * G_raster_size(CELL_TYPE));

		if (G_is_null_value(ptr, CELL_TYPE)) {	/* first node */
		    head_id = new_node();
		    nodes[head_id].next = -1;
		    nodes[head_id].z = z;
		    G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
		else {		/* head is already there */

		    head_id = G_get_raster_value_c(ptr, CELL_TYPE);	/* get index to head */
		    head_id = add_node(head_id, z);
		    if (head_id != -1)
			G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
	    }
	}			/* while !EOF */

	G_percent(1, 1, 1);	/* flush */
	G_debug(2, "pass %d finished, %lu coordinates in box", pass, count);
	count_total += count;


	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {

	    switch (method) {
	    case METHOD_N:	/* n is a straight copy */
		G_raster_cpy(raster_row,
			     n_array +
			     (row * cols * G_raster_size(CELL_TYPE)), cols,
			     CELL_TYPE);
		break;

	    case METHOD_MIN:
		G_raster_cpy(raster_row,
			     min_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_MAX:
		G_raster_cpy(raster_row,
			     max_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_SUM:
		G_raster_cpy(raster_row,
			     sum_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_RANGE:	/* (max-min) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    min = G_get_raster_value_d(min_array + offset, rtype);
		    max = G_get_raster_value_d(max_array + offset, rtype);
		    G_set_raster_value_d(ptr, max - min, rtype);
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_MEAN:	/* (sum / n) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else
			G_set_raster_value_d(ptr, (sum / n), rtype);

		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_STDDEV:	/*  sqrt(variance)        */
	    case METHOD_VARIANCE:	/*  (sumsq - sum*sum/n)/n */
	    case METHOD_COEFF_VAR:	/*  100 * stdev / mean    */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);
		    sumsq = G_get_raster_value_d(sumsq_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else {
			variance = (sumsq - sum * sum / n) / n;
			if (variance < GRASS_EPSILON)
			    variance = 0.0;

			if (method == METHOD_STDDEV)
			    G_set_raster_value_d(ptr, sqrt(variance), rtype);

			else if (method == METHOD_VARIANCE)
			    G_set_raster_value_d(ptr, variance, rtype);

			else if (method == METHOD_COEFF_VAR)
			    G_set_raster_value_d(ptr,
						 100 * sqrt(variance) / (sum /
									 n),
						 rtype);

		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_MEDIAN:	/* median, if only one point in cell we will use that */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {	/* one or more points in cell */

			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (n == 1)	/* only one point, use that */
			    G_set_raster_value_d(ptr, nodes[head_id].z,
						 rtype);
			else if (n % 2 != 0) {	/* odd number of points: median_i = (n + 1) / 2 */
			    n = (n + 1) / 2;
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get "median element" */
				node_id = nodes[node_id].next;

			    G_set_raster_value_d(ptr, nodes[node_id].z,
						 rtype);
			}
			else {	/* even number of points: median = (val_below + val_above) / 2 */

			    z = (n + 1) / 2.0;
			    n = floor(z);
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get element "below" */
				node_id = nodes[node_id].next;

			    z = (nodes[node_id].z +
				 nodes[nodes[node_id].next].z) / 2;
			    G_set_raster_value_d(ptr, z, rtype);
			}
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_PERCENTILE:	/* rank = (pth*(n+1))/100; interpolate linearly */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;
			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			z = (pth * (n + 1)) / 100.0;
			r_low = floor(z);	/* lower rank */
			if (r_low < 1)
			    r_low = 1;
			else if (r_low > n)
			    r_low = n;

			r_up = ceil(z);	/* upper rank */
			if (r_up > n)
			    r_up = n;

			node_id = head_id;
			for (j = 1; j < r_low; j++)	/* search lower value */
			    node_id = nodes[node_id].next;

			z = nodes[node_id].z;	/* save lower value */
			node_id = head_id;
			for (j = 1; j < r_up; j++)	/* search upper value */
			    node_id = nodes[node_id].next;

			z = (z + nodes[node_id].z) / 2;
			G_set_raster_value_d(ptr, z, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_SKEWNESS:	/* skewness = sum(xi-mean)^3/(N-1)*s^3 */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;	/* count */
			sum = 0.0;	/* sum */
			sumsq = 0.0;	/* sum of squares */
			sumdev = 0.0;	/* sum of (xi - mean)^3 */
			skew = 0.0;	/* skewness */

			while (node_id != -1) {
			    z = nodes[node_id].z;
			    n++;
			    sum += z;
			    sumsq += (z * z);
			    node_id = nodes[node_id].next;
			}

			if (n > 1) {	/* if n == 1, skew is "0.0" */
			    mean = sum / n;
			    node_id = head_id;
			    while (node_id != -1) {
				z = nodes[node_id].z;
				sumdev += pow((z - mean), 3);
				node_id = nodes[node_id].next;
			    }

			    variance = (sumsq - sum * sum / n) / n;
			    if (variance < GRASS_EPSILON)
				skew = 0.0;
			    else
				skew =
				    sumdev / ((n - 1) *
					      pow(sqrt(variance), 3));
			}
			G_set_raster_value_d(ptr, skew, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_TRIMMEAN:
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);

			node_id = head_id;
			n = 0;
			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (1 == n)
			    mean = nodes[head_id].z;
			else {
			    k = floor(trim * n + 0.5);	/* number of ranks to discard on each tail */

			    if (k > 0 && (n - 2 * k) > 0) {	/* enough elements to discard */
				node_id = head_id;
				for (j = 0; j < k; j++)	/* move to first rank to consider */
				    node_id = nodes[node_id].next;

				j = k + 1;
				k = n - k;
				n = 0;
				sum = 0.0;

				while (j <= k) {	/* get values in interval */
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				    j++;
				}
			    }
			    else {
				node_id = head_id;
				n = 0;
				sum = 0.0;
				while (node_id != -1) {
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				}
			    }
			    mean = sum / n;
			}
			G_set_raster_value_d(ptr, mean, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    default:
		G_fatal_error("?");
	    }

	    /* write out line of raster data */
	    if (1 != G_put_raster_row(out_fd, raster_row, rtype)) {
		G_close_cell(out_fd);
		G_fatal_error(_("Writing map, row %d"),
			      ((pass - 1) * rows) + row);
	    }
	}

	/* free memory */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index) {
	    G_free(index_array);
	    G_free(nodes);
	    num_nodes = 0;
	    max_nodes = 0;
	    nodes = NULL;
	}

    }				/* passes loop */

    G_percent(1, 1, 1);		/* flush */
    G_free(raster_row);

    /* close input file */
    if (!from_stdin)
	fclose(in_fp);

    /* close raster file & write history */
    G_close_cell(out_fd);

    sprintf(title, "Raw x,y,z data binned into a raster grid by cell %s",
	    method_opt->answer);
    G_put_cell_title(outmap, title);

    G_short_history(outmap, "raster", &history);
    G_command_history(&history);
    strncpy(history.datsrc_1, infile, RECORD_LEN);
    history.datsrc_1[RECORD_LEN - 1] = '\0';	/* strncpy() doesn't null terminate if maxfill */
    G_write_history(outmap, &history);


    sprintf(buff, _("%lu points found in region."), count_total);
    G_done_msg(buff);
    G_debug(1, "Processed %lu lines.", line);

    exit(EXIT_SUCCESS);

}
Beispiel #12
0
int scan_bounds(FILE * fp, int xcol, int ycol, int zcol, char *fs,
		int shell_style, int skipline, double zscale)
{
    unsigned long line;
    int first, max_col;
    char buff[BUFFSIZE];
    double min_x, max_x, min_y, max_y, min_z, max_z;
    char **tokens;
    int ntokens;		/* number of tokens */
    double x, y, z;

    max_col = (xcol > ycol) ? xcol : ycol;
    max_col = (zcol > max_col) ? zcol : max_col;

    line = 0;
    first = TRUE;

    G_verbose_message(_("Scanning data ..."));

    while (0 != G_getl2(buff, BUFFSIZE - 1, fp)) {
	line++;

	if ((buff[0] == '#') || (buff[0] == '\0')) {
	    continue;		/* line is a comment or blank */
	}

	G_chop(buff);		/* remove leading and trailing whitespace. unneded?? */
	tokens = G_tokenize(buff, fs);
	ntokens = G_number_of_tokens(tokens);

	if ((ntokens < 3) || (max_col > ntokens)) {
	    if (skipline) {
		G_warning(_("Not enough data columns. "
			    "Incorrect delimiter or column number? "
			    "Found the following character(s) in row %lu:\n[%s]"),
			  line, buff);
		G_warning(_("Line ignored as requested"));
		continue;	/* line is garbage */
	    }
	    else {
		G_fatal_error(_("Not enough data columns. "
				"Incorrect delimiter or column number? "
				"Found the following character(s) in row %lu:\n[%s]"),
			      line, buff);
	    }
	}

	/* too slow?
	   if ( G_projection() == PROJECTION_LL ) {
	   G_scan_easting( tokens[xcol-1], &x, region.proj);
	   G_scan_northing( tokens[ycol-1], &y, region.proj);
	   }
	   else {
	 */
	if (1 != sscanf(tokens[xcol - 1], "%lf", &x))
	    G_fatal_error(_("Bad x-coordinate line %lu column %d. <%s>"), line,
			  xcol, tokens[xcol - 1]);

	if (first) {
	    min_x = x;
	    max_x = x;
	}
	else {
	    if (x < min_x)
		min_x = x;
	    if (x > max_x)
		max_x = x;
	}

	if (1 != sscanf(tokens[ycol - 1], "%lf", &y))
	    G_fatal_error(_("Bad y-coordinate line %lu column %d. <%s>"), line,
			  ycol, tokens[ycol - 1]);

	if (first) {
	    min_y = y;
	    max_y = y;
	}
	else {
	    if (y < min_y)
		min_y = y;
	    if (y > max_y)
		max_y = y;
	}

	if (1 != sscanf(tokens[zcol - 1], "%lf", &z))
	    G_fatal_error(_("Bad z-coordinate line %lu column %d. <%s>"), line,
			  zcol, tokens[zcol - 1]);

	if (first) {
	    min_z = z;
	    max_z = z;
	    first = FALSE;
	}
	else {
	    if (z < min_z)
		min_z = z;
	    if (z > max_z)
		max_z = z;
	}


	G_free_tokens(tokens);
    }

    if (!shell_style) {
	fprintf(stderr, _("Range:     min         max\n"));
	fprintf(stdout, "x: %11f %11f\n", min_x, max_x);
	fprintf(stdout, "y: %11f %11f\n", min_y, max_y);
	fprintf(stdout, "z: %11f %11f\n", min_z * zscale, max_z * zscale);
    }
    else
	fprintf(stdout, "n=%f s=%f e=%f w=%f b=%f t=%f\n",
		max_y, min_y, max_x, min_x, min_z * zscale, max_z * zscale);

    G_debug(1, "Processed %lu lines.", line);
    G_debug(1, "region template: g.region n=%f s=%f e=%f w=%f",
	    max_y, min_y, max_x, min_x);

    return 0;
}
Beispiel #13
0
int parse_sql_update(const char *sql, char **table, column_info **cols, int *ncols, char **where)
{
    int nprefix, n;
    int has_where;
    char *prefix;
    char *p, *w, *c, *t;
    char **token, **itoken;

    prefix = "UPDATE";
    nprefix = strlen(prefix);
    if (G_strncasecmp(sql, prefix, nprefix) != 0)
	return 1;
	
    p = (char *) sql + nprefix; /* skip 'UPDATE' */
    if (*p != ' ')
	return 1;
    p++;
    
    /* table */
    t = strchr(p, ' ');
    n = t - p;
    *table = G_malloc(n + 1);
    strncpy(*table, p, n);
    (*table)[n] = '\0';
    G_strip(*table);
    
    p += n;
    if (*p != ' ')
	return 1;
    p++;

    if (G_strncasecmp(p, "SET", 3) != 0)
	return 1;

    p += 3; /* skip 'SET' */

    if (*p != ' ')
	return 1;
    p++;
    
    w = G_strcasestr(p, "WHERE");
    
    if (!w) {
	has_where = FALSE;
	w = (char *)sql + strlen(sql);
    }
    else {
	has_where = TRUE;
    }
    
    /* process columns & values */
    n = w - p;
    c = G_malloc(n + 1);
    strncpy(c, p, n);
    c[n] = '\0';
    
    token = G_tokenize2(c, ",", "'");
    *ncols = G_number_of_tokens(token);
    *cols = (column_info *)G_malloc(sizeof(column_info) * (*ncols));
    
    for (n = 0; n < (*ncols); n++) {
	itoken = G_tokenize(token[n], "=");
	if (G_number_of_tokens(itoken) != 2)
	    return FALSE;
	G_strip(itoken[0]);
	G_strip(itoken[1]);
	(*cols)[n].name  = G_store(itoken[0]);
	(*cols)[n].value = G_store(itoken[1]);
	G_free_tokens(itoken);
    }
    
    G_free_tokens(token);
    G_free(c);

    if (!has_where) {
	*where = NULL;
	return 0;
    }
    
    /* where */
    w += strlen("WHERE");
    if (*w != ' ')
	return 1;
    w++;

    G_strip(w);
    *where = G_store(w);
    
    return 0;
}
Beispiel #14
0
int main(int argc, char *argv[])
{
    int n, i;
    int skip;
    const char *cur_mapset, *mapset;
    char **ptr;
    char **tokens;
    int no_tokens;
    FILE *fp;
    char path_buf[GPATH_MAX];
    char *path, *fs;
    int operation, nchoices;
    
    char **mapset_name;
    int nmapsets;
    
    struct GModule *module;    
    struct _opt {
        struct Option *mapset, *op, *fs;
        struct Flag *print, *list, *dialog;
    } opt;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("settings"));
    G_add_keyword(_("search path"));
    module->label = _("Modifies/prints the user's current mapset search path.");
    module->description = _("Affects the user's access to data existing "
                            "under the other mapsets in the current location.");

    opt.mapset = G_define_standard_option(G_OPT_M_MAPSET);
    opt.mapset->required = YES;
    opt.mapset->multiple = YES;
    opt.mapset->description = _("Name(s) of existing mapset(s) to add/remove or set");
    opt.mapset->guisection = _("Search path");
    
    opt.op = G_define_option();
    opt.op->key = "operation";
    opt.op->type = TYPE_STRING;
    opt.op->required = YES;
    opt.op->multiple = NO;
    opt.op->options = "set,add,remove";
    opt.op->description = _("Operation to be performed");
    opt.op->guisection = _("Search path");
    opt.op->answer = "add";
    
    opt.fs = G_define_standard_option(G_OPT_F_SEP);
    opt.fs->label = _("Field separator for printing (-l and -p flags)");
    opt.fs->answer = "space";
    opt.fs->guisection = _("Print");
    
    opt.list = G_define_flag();
    opt.list->key = 'l';
    opt.list->description = _("List all available mapsets in alphabetical order");
    opt.list->guisection = _("Print");
    opt.list->suppress_required = YES;

    opt.print = G_define_flag();
    opt.print->key = 'p';
    opt.print->description = _("Print mapsets in current search path");
    opt.print->guisection = _("Print");
    opt.print->suppress_required = YES;

    opt.dialog = G_define_flag();
    opt.dialog->key = 's';
    opt.dialog->description = _("Launch mapset selection GUI dialog");
    opt.dialog->suppress_required = YES;
    
    path = NULL;
    mapset_name = NULL;
    nmapsets = nchoices = 0;

    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);

    operation = OP_UKN;
    if (opt.mapset->answer && opt.op->answer) {
        switch(opt.op->answer[0]) {
        case 's':
            operation = OP_SET;
            break;
        case 'a':
            operation = OP_ADD;
            break;
        case 'r':
            operation = OP_REM;
            break;
        default:
            G_fatal_error(_("Unknown operation '%s'"), opt.op->answer);
            break;
        }
    }
    
    fs = G_option_to_separator(opt.fs);

    /* list available mapsets */
    if (opt.list->answer) {
        if (opt.print->answer)
            G_warning(_("Flag -%c ignored"), opt.print->key);
        if (opt.dialog->answer)
            G_warning(_("Flag -%c ignored"), opt.dialog->key);
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        mapset_name = get_available_mapsets(&nmapsets);
        list_available_mapsets((const char **)mapset_name, nmapsets, fs);
        exit(EXIT_SUCCESS);
    }

    if (opt.print->answer) {
        if (opt.dialog->answer)
            G_warning(_("Flag -%c ignored"), opt.dialog->key);
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        list_accessible_mapsets(fs);
        exit(EXIT_SUCCESS);
    }
    
    /* show GUI dialog */
    if (opt.dialog->answer) {
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        sprintf(path_buf, "%s/gui/wxpython/modules/mapsets_picker.py", G_gisbase());
        G_spawn(getenv("GRASS_PYTHON"), "mapsets_picker.py", path_buf, NULL);
        exit(EXIT_SUCCESS);
    }

    cur_mapset = G_mapset();
    
    /* modify search path */
    if (operation == OP_SET) {
        int cur_found;
        
        cur_found = FALSE;
        for (ptr = opt.mapset->answers; *ptr != NULL; ptr++) {
            mapset = substitute_mapset(*ptr);
            if (G__mapset_permissions(mapset) < 0)
                G_fatal_error(_("Mapset <%s> not found"), mapset);
            if (strcmp(mapset, cur_mapset) == 0)
                cur_found = TRUE;
            nchoices++;
            append_mapset(&path, mapset);
        }
        if (!cur_found)
            G_warning(_("Current mapset (<%s>) must always included in the search path"),
                      cur_mapset);
    }
    else if (operation == OP_ADD) {
        /* add to existing search path */
        const char *oldname;
        
        if (path) {
            G_free(path);
            path = NULL;
        }

        /* read existing mapsets from SEARCH_PATH */
        for (n = 0; (oldname = G_get_mapset_name(n)); n++)
            append_mapset(&path, oldname);

        /* fetch and add new mapsets from param list */
        for (ptr = opt.mapset->answers; *ptr != NULL; ptr++) {

            mapset = substitute_mapset(*ptr);

            if (G_is_mapset_in_search_path(mapset)) {
                G_message(_("Mapset <%s> already in the path"), mapset);
                continue;
            }
            
            if (G__mapset_permissions(mapset) < 0)
                G_fatal_error(_("Mapset <%s> not found"), mapset);
            else
                G_verbose_message(_("Mapset <%s> added to search path"),
                                  mapset);

            nchoices++;
            append_mapset(&path, mapset);
        }
    }
    else if (operation == OP_REM) {
        /* remove from existing search path */
        const char *oldname;
        int found;
        
        if (path) {
            G_free(path);
            path = NULL;
        }
        
        /* read existing mapsets from SEARCH_PATH */
        for (n = 0; (oldname = G_get_mapset_name(n)); n++) {
            found = FALSE;
            
            for (ptr = opt.mapset->answers; *ptr && !found; ptr++)

                mapset = substitute_mapset(*ptr);
            
                if (strcmp(oldname, mapset) == 0)
                    found = TRUE;
            
                if (found) {
                    if (strcmp(oldname, cur_mapset) == 0)
                        G_warning(_("Current mapset (<%s>) must always included in the search path"),
                                  cur_mapset);
                    else
                        G_verbose_message(_("Mapset <%s> removed from search path"),
                                          oldname);
                    continue;
                }
                
                nchoices++;
                append_mapset(&path, oldname);
        }
    }
    /* stuffem sets nchoices */

    if (nchoices == 0) {
        G_important_message(_("Search path not modified"));
        if (path)
            G_free(path);
        
        if (nmapsets) {
            for(nmapsets--; nmapsets >= 0; nmapsets--)
                G_free(mapset_name[nmapsets]);
            G_free(mapset_name);
        }
        
        exit(EXIT_SUCCESS);
    }
    
    /* note I'm assuming that mapsets cannot have ' 's in them */
    tokens = G_tokenize(path, " ");

    fp = G_fopen_new("", "SEARCH_PATH");
    if (!fp)
        G_fatal_error(_("Unable to open SEARCH_PATH for write"));

    /*
     * make sure current mapset is specified in the list if not add it
     * to the head of the list
     */
    
    skip = 0;
    for (n = 0; n < nchoices; n++)
        if (strcmp(cur_mapset, tokens[n]) == 0) {
            skip = 1;
            break;
        }
    if (!skip) {
        fprintf(fp, "%s\n", cur_mapset);
    }

    /*
     * output the list, removing duplicates
     */

    no_tokens = G_number_of_tokens(tokens);

    for (n = 0; n < no_tokens; n++) {
        skip = 0;
        for (i = n; i < no_tokens; i++) {
            if (i != n) {
                if (strcmp(tokens[i], tokens[n]) == 0)
                    skip = 1;
            }
        }

        if (!skip)
            fprintf(fp, "%s\n", tokens[n]);
    }

    fclose(fp);
    G_free_tokens(tokens);

    if (path)
        G_free(path);

    if (nmapsets) {
        for(nmapsets--; nmapsets >= 0; nmapsets--)
            G_free(mapset_name[nmapsets]);
        G_free(mapset_name);
    }

    exit(EXIT_SUCCESS);
}
Beispiel #15
0
int stats(void)
{
    char buf[1024];
    char mname[GNAME_MAX], rname[GMAPSET_MAX];
    const char *mmapset, *rmapset;
    int i, nl;
    size_t ns;
    FILE *fd;
    char **tokens;
    const char *argv[9];
    int argc = 0;

    strcpy(mname, maps[0]);
    mmapset = G_find_raster2(mname, "");
    if (mmapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), maps[0]);

    strcpy(rname, maps[1]);
    rmapset = G_find_raster2(rname, "");
    if (rmapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), maps[1]);

    stats_file = G_tempfile();

    argv[argc++] = "r.stats";

    argv[argc++] = "-cin";

    argv[argc++] = "fs=:";

    sprintf(buf, "input=%s,%s",
	    G_fully_qualified_name(maps[1], mmapset),
	    G_fully_qualified_name(maps[0], rmapset));
    argv[argc++] = buf;

    argv[argc++] = SF_REDIRECT_FILE;
    argv[argc++] = SF_STDOUT;
    argv[argc++] = SF_MODE_OUT;
    argv[argc++] = stats_file;

    argv[argc++] = NULL;

    if (G_vspawn_ex(argv[0], argv) != 0) {
	remove(stats_file);
	G_fatal_error("error running r.stats");
    }

    fd = fopen(stats_file, "r");
    if (fd == NULL) {
	unlink(stats_file);
	sprintf(buf, "Unable to open result file <%s>\n", stats_file);
    }

    while (G_getl(buf, sizeof buf, fd)) {
	tokens = G_tokenize(buf, ":");
	i = 0;
	ns = nstats++;
	Gstats = (GSTATS *) G_realloc(Gstats, nstats * sizeof(GSTATS));
	Gstats[ns].cats = (long *)G_calloc(nlayers, sizeof(long));
	for (nl = 0; nl < nlayers; nl++) {
	    if (sscanf(tokens[i++], "%ld", &Gstats[ns].cats[nl]) != 1)
		die();
	}
	if (sscanf(tokens[i++], "%ld", &Gstats[ns].count) != 1)
	    die();
	G_free_tokens(tokens);
    }
    fclose(fd);
    unlink(stats_file);

    return 0;
}
Beispiel #16
0
static int read_dblinks_nat(struct Map_info *Map)
{
    FILE *fd;
    char file[1024], buf[2001];
    char tab[1024], col[1024], db[1024], drv[1024], fldstr[1024], *fldname;
    int fld;
    char *c, *path;
    int row, rule;
    struct dblinks *dbl;
    char **tokens;
    int ntok, i;

    dbl = Map->dblnk;

    /* Read dblink for native format */
    path = Vect__get_path(Map);
    fd = G_fopen_old(path, GV_DBLN_ELEMENT, Map->mapset);
    G_free(path);
    if (fd == NULL) {		/* This may be correct, no tables defined */
	G_debug(1, "Cannot open vector database definition file");
	return -1;
    }

    row = 0;
    rule = 0;
    while (G_getl2(buf, 2000, fd)) {
	row++;
	G_chop(buf);
	G_debug(1, "dbln: %s", buf);

	c = (char *)strchr(buf, '#');
	if (c != NULL)
	    *c = '\0';

	if (strlen(buf) == 0)
	    continue;

#ifdef NOT_ABLE_TO_READ_GRASS_6
	int ndef;
	ndef = sscanf(buf, "%s|%s|%s|%s|%s", fldstr, tab, col, db, drv);

        if (ndef < 2 || (ndef < 5 && rule < 1)) {
            G_warning(_("Error in rule on row %d in <%s>"), row, file);
            continue;
        }
#else
	tokens = G_tokenize(buf, " |");
	ntok = G_number_of_tokens(tokens);

	if (ntok < 2 || (ntok < 5 && rule < 1)) {
	    G_warning(_("Error in rule on row %d in <%s>"), row, file);
	    continue;
	}

	strcpy(fldstr, tokens[0]);
	strcpy(tab, tokens[1]);
	if (ntok > 2) {
	    strcpy(col, tokens[2]);
	    if (ntok > 3) {
		strcpy(db, tokens[3]);
		/* allow for spaces in path names */
		for (i=4; i < ntok-1; i++) {
		    strcat(db, " ");
		    strcat(db, tokens[i]);
		}

		strcpy(drv, tokens[ntok-1]);
	    }
	}
	G_free_tokens(tokens);
#endif

	/* get field and field name */
	fldname = strchr(fldstr, '/');
	if (fldname != NULL) {	/* field has name */
	    fldname[0] = 0;
	    fldname++;
	}
	fld = atoi(fldstr);

	Vect_add_dblink(dbl, fld, fldname, tab, col, db, drv);

	G_debug(1,
		"field = %d name = %s, table = %s, key = %s, database = %s, driver = %s",
		fld, fldname, tab, col, db, drv);

	rule++;
    }
    fclose(fd);

    G_debug(1, "Dblinks read");
    
    return rule;
}
Beispiel #17
0
int main(int argc, char *argv[])
{
    char file[GPATH_MAX], name[GNAME_MAX], *mapset;
    char *search_mapset;
    struct GModule *module;
    struct Option *elem_opt;
    struct Option *mapset_opt;
    struct Option *file_opt;
    struct Flag *n_flag;

    module = G_define_module();
    module->keywords = _("general, map management");
    module->description =
	_("Searches for GRASS data base files "
	  "and sets variables for the shell.");

    G_gisinit(argv[0]);

    /* Define the different options */

    elem_opt = G_define_option();
    elem_opt->key = "element";
    elem_opt->type = TYPE_STRING;
    elem_opt->required = YES;
    elem_opt->description = _("Name of an element");

    file_opt = G_define_option();
    file_opt->key = "file";
    file_opt->type = TYPE_STRING;
    file_opt->required = YES;
    file_opt->description = _("Name of an existing map");

    mapset_opt = G_define_option();
    mapset_opt->key = "mapset";
    mapset_opt->type = TYPE_STRING;
    mapset_opt->required = NO;
    mapset_opt->description = _("Name of a mapset");
    mapset_opt->answer = "";

    n_flag = G_define_flag();
    n_flag->key = 'n';
    n_flag->description = _("Don't add quotes");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    search_mapset = mapset_opt->answer;
    if (strcmp(".", search_mapset) == 0)
	search_mapset = G_mapset();
    
    if (mapset_opt->answer && strlen(mapset_opt->answer) > 0) {
	char **map_mapset = G_tokenize(file_opt->answer, "@");

	if (G_number_of_tokens(map_mapset) > 1) {
	    if (strcmp(map_mapset[1], mapset_opt->answer))
		G_fatal_error(_("Parameter 'file' contains reference to <%s> mapset, "
				"but mapset parameter <%s> does not correspond"),
			      map_mapset[1], mapset_opt->answer);
	    else
		strcpy(name, file_opt->answer);
	}
	if (G_number_of_tokens(map_mapset) == 1)
	    strcpy(name, file_opt->answer);
	G_free_tokens(map_mapset);
    }
    else
	strcpy(name, file_opt->answer);

    mapset = G_find_file2(elem_opt->answer, name, search_mapset);
    if (mapset) {
	const char *qchar = n_flag->answer ? "" : "'";
	const char *qual = G_fully_qualified_name(name, mapset);
	G__file_name(file, elem_opt->answer, name, mapset);
	fprintf(stdout, "name=%s%s%s\n", qchar, name, qchar);
	fprintf(stdout, "mapset=%s%s%s\n", qchar, mapset, qchar);
	fprintf(stdout, "fullname=%s%s%s\n", qchar, qual, qchar);
	fprintf(stdout, "file=%s%s%s\n", qchar, file, qchar);
    }
    else {
	fprintf(stdout, "name=\n");
	fprintf(stdout, "mapset=\n");
	fprintf(stdout, "fullname=\n");
	fprintf(stdout, "file=\n");
    }
    
    exit(mapset == NULL);
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    const char *name;
    const char *mapset;

    long x, y;
    double dx;
    RASTER_MAP_TYPE map_type;
    int i;
    int from_stdin = FALSE;
    struct GModule *module;

    struct
    {
	struct Option *map, *fs, *cats, *vals, *raster, *file, *fmt_str,
	    *fmt_coeff;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("category"));
    module->description =
	_("Manages category values and labels associated "
	  "with user-specified raster map layers.");

    parm.map = G_define_standard_option(G_OPT_R_MAP);

    parm.cats = G_define_standard_option(G_OPT_V_CATS);
    parm.cats->multiple = YES;
    parm.cats->guisection = _("Selection");

    parm.vals = G_define_option();
    parm.vals->key = "vals";
    parm.vals->type = TYPE_DOUBLE;
    parm.vals->multiple = YES;
    parm.vals->required = NO;
    parm.vals->label = _("Comma separated value list");
    parm.vals->description = _("Example: 1.4,3.8,13");
    parm.vals->guisection = _("Selection");

    parm.fs = G_define_standard_option(G_OPT_F_SEP);
    parm.fs->answer = "tab";

    parm.raster = G_define_standard_option(G_OPT_R_INPUT);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->description =
	_("Raster map from which to copy category table");
    parm.raster->guisection = _("Define");

    parm.file = G_define_standard_option(G_OPT_F_INPUT);
    parm.file->key = "rules";
    parm.file->required = NO;
    parm.file->description =
	_("File containing category label rules (or \"-\" to read from stdin)");
    parm.file->guisection = _("Define");

    parm.fmt_str = G_define_option();
    parm.fmt_str->key = "format";
    parm.fmt_str->type = TYPE_STRING;
    parm.fmt_str->required = NO;
    parm.fmt_str->label =
	_("Default label or format string for dynamic labeling");
    parm.fmt_str->description =
	_("Used when no explicit label exists for the category");

    parm.fmt_coeff = G_define_option();
    parm.fmt_coeff->key = "coefficients";
    parm.fmt_coeff->type = TYPE_DOUBLE;
    parm.fmt_coeff->required = NO;
    parm.fmt_coeff->key_desc = "mult1,offset1,mult2,offset2";
    /*    parm.fmt_coeff->answer   = "0.0,0.0,0.0,0.0"; */
    parm.fmt_coeff->label = _("Dynamic label coefficients");
    parm.fmt_coeff->description =
	_("Two pairs of category multiplier and offsets, for $1 and $2");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    name = parm.map->answer;

    fs = G_option_to_separator(parm.fs);
    
    mapset = G_find_raster2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    map_type = Rast_map_type(name, mapset);


    /* create category labels */
    if (parm.raster->answer || parm.file->answer ||
	parm.fmt_str->answer || parm.fmt_coeff->answer) {

	/* restrict editing to current mapset */
	if (strcmp(mapset, G_mapset()) != 0)
	    G_fatal_error(_("Raster map <%s> not found in current mapset"),
			  name);

	/* use cats from another map */
	if (parm.raster->answer) {
	    int fd;
	    const char *cmapset;

	    cmapset = G_find_raster2(parm.raster->answer, "");
	    if (cmapset == NULL)
		G_fatal_error(_("Raster map <%s> not found"),
			      parm.raster->answer);

	    fd = Rast_open_old(name, mapset);

	    Rast_init_cats("", &cats);

	    if (0 > Rast_read_cats(parm.raster->answer, cmapset, &cats))
		G_fatal_error(_("Unable to read category file of raster map <%s@%s>"),
			      parm.raster->answer, cmapset);

	    Rast_write_cats(name, &cats);
	    G_message(_("Category table for <%s> set from <%s>"),
		      name, parm.raster->answer);

	    Rast_close(fd);
	}

	/* load cats from rules file */
	if (parm.file->answer) {
	    FILE *fp;
	    char **tokens;
	    int ntokens;
	    char *e1;
	    char *e2;

	    if (strcmp("-", parm.file->answer) == 0) {
		from_stdin = TRUE;
		fp = stdin;
	    }
	    else {
		fp = fopen(parm.file->answer, "r");
		if (!fp)
		    G_fatal_error(_("Unable to open file <%s>"),
				  parm.file->answer);
	    }

	    Rast_init_cats("", &cats);

	    for (;;) {
		char buf[1024];
		DCELL d1, d2;
		int parse_error = 0;

		if (!G_getl2(buf, sizeof(buf), fp))
		    break;

		tokens = G_tokenize(buf, fs);
		ntokens = G_number_of_tokens(tokens);

		if (ntokens == 3) {
		    d1 = strtod(tokens[0], &e1);
		    d2 = strtod(tokens[1], &e2);
		    if (*e1 == 0 && *e2 == 0)
			Rast_set_d_cat(&d1, &d2, tokens[2], &cats);
		    else
			parse_error = 1;
		}
		else if (ntokens == 2) {
		    d1 = strtod(tokens[0], &e1);
		    if (*e1 == 0)
			Rast_set_d_cat(&d1, &d1, tokens[1], &cats);
		    else
			parse_error = 1;
		}
		else if (!strlen(buf))
		    continue;
		else
		    parse_error = 1;

		if (parse_error)
		    G_fatal_error(_("Incorrect format of input rules. "
				    "Check separators. Invalid line is:\n%s"), buf);
	    }
	    G_free_tokens(tokens);
	    Rast_write_cats(name, &cats);

	    if (!from_stdin)
		fclose(fp);
	}

	/* set dynamic cat rules for cats without explicit labels */
	if (parm.fmt_str->answer || parm.fmt_coeff->answer) {
	    char *fmt_str;
	    double m1, a1, m2, a2;

	    /* read existing values */
	    Rast_init_cats("", &cats);

	    if (0 > Rast_read_cats(name, G_mapset(), &cats))
		G_warning(_("Unable to read category file of raster map <%s@%s>"),
			  name, G_mapset());

	    if (parm.fmt_str->answer) {
		fmt_str =
		    G_malloc(strlen(parm.fmt_str->answer) > strlen(cats.fmt)
			     ? strlen(parm.fmt_str->answer) +
			     1 : strlen(cats.fmt) + 1);
		strcpy(fmt_str, parm.fmt_str->answer);
	    }
	    else {
		fmt_str = G_malloc(strlen(cats.fmt) + 1);
		strcpy(fmt_str, cats.fmt);
	    }

	    m1 = cats.m1;
	    a1 = cats.a1;
	    m2 = cats.m2;
	    a2 = cats.a2;

	    if (parm.fmt_coeff->answer) {
		m1 = atof(parm.fmt_coeff->answers[0]);
		a1 = atof(parm.fmt_coeff->answers[1]);
		m2 = atof(parm.fmt_coeff->answers[2]);
		a2 = atof(parm.fmt_coeff->answers[3]);
	    }

	    Rast_set_cats_fmt(fmt_str, m1, a1, m2, a2, &cats);

	    Rast_write_cats(name, &cats);
	}

	Rast_free_cats(&cats);
	exit(EXIT_SUCCESS);
    }
    else {
	if (Rast_read_cats(name, mapset, &cats) < 0)
	    G_fatal_error(_("Unable to read category file of raster map <%s> in <%s>"),
			  name, mapset);
    }

    /* describe the category labels */
    /* if no cats requested, use r.describe to get the cats */
    if (parm.cats->answer == NULL) {
	if (map_type == CELL_TYPE) {
	    get_cats(name, mapset);
	    while (next_cat(&x))
		print_label(x);
	    exit(EXIT_SUCCESS);
	}
    }
    else {
	if (map_type != CELL_TYPE)
	    G_warning(_("The map is floating point! Ignoring cats list, using vals list"));
	else {			/* integer map */

	    for (i = 0; parm.cats->answers[i]; i++)
		if (!scan_cats(parm.cats->answers[i], &x, &y)) {
		    G_usage();
		    exit(EXIT_FAILURE);
		}
	    for (i = 0; parm.cats->answers[i]; i++) {
		scan_cats(parm.cats->answers[i], &x, &y);
		while (x <= y)
		    print_label(x++);
	    }
	    exit(EXIT_SUCCESS);
	}
    }
    if (parm.vals->answer == NULL)
	G_fatal_error(_("vals argument is required for floating point map!"));
    for (i = 0; parm.vals->answers[i]; i++)
	if (!scan_vals(parm.vals->answers[i], &dx)) {
	    G_usage();
	    exit(EXIT_FAILURE);
	}
    for (i = 0; parm.vals->answers[i]; i++) {
	scan_vals(parm.vals->answers[i], &dx);
	print_d_label(dx);
    }
    exit(EXIT_SUCCESS);
}
Beispiel #19
0
int db__driver_open_database(dbHandle * handle)
{
    const char *name;
    int len;
    dbConnection connection;
    char buf[1024];
    DIR *dir;
    struct dirent *ent;
    char **tokens;
    int no_tokens, n;

    G_debug(2, "DBF: db__driver_open_database() name = '%s'",
	    db_get_handle_dbname(handle));

    db.name[0] = '\0';
    db.tables = NULL;
    db.atables = 0;
    db.ntables = 0;

    db_get_connection(&connection);
    name = db_get_handle_dbname(handle);

    /* if name is empty use connection.databaseName */
    if (strlen(name) == 0) {
	name = connection.databaseName;
    }

    strcpy(db.name, name);

    /* open database dir and read table ( *.dbf files ) names 
     * to structure */

    /* parse variables in db.name if present */
    if (db.name[0] == '$') {
	tokens = G_tokenize(db.name, "/");
	no_tokens = G_number_of_tokens(tokens);
	db.name[0] = '\0';	/* re-init */

	for (n = 0; n < no_tokens; n++) {
	    G_debug(3, "tokens[%d] = %s", n, tokens[n]);
	    if (tokens[n][0] == '$') {
		G_strchg(tokens[n], '$', ' ');
		G_chop(tokens[n]);
		strcat(db.name, G__getenv(tokens[n]));
		G_debug(3, "   -> %s", G__getenv(tokens[n]));
	    }
	    else
		strcat(db.name, tokens[n]);

	    strcat(db.name, "/");
	}
	G_free_tokens(tokens);
    }

    G_debug(2, "db.name = %s", db.name);

    errno = 0;
    dir = opendir(db.name);
    if (dir == NULL) {
	if (errno == ENOENT) {
	    int status;

	    status = G_mkdir(db.name);
	    if (status != 0) {	/* mkdir failed */
		append_error("Cannot create dbf database: %s\n", name);
		report_error();
		return DB_FAILED;
	    }
	}
	else {			/* some other problem */
	    append_error("Cannot open dbf database: %s\n", name);
	    report_error();
	    return DB_FAILED;
	}
    }

    while ((ent = readdir(dir))) {
	len = strlen(ent->d_name) - 4;
	if ((len > 0) && (G_strcasecmp(ent->d_name + len, ".dbf") == 0)) {
	    strcpy(buf, ent->d_name);
	    buf[len] = '\0';
	    add_table(buf, ent->d_name);
	}
    }

    closedir(dir);
    return DB_OK;
}
Beispiel #20
0
/*
 * \brief Parse connection string in form:
 *    1) 'database_name'
 *    2) 'host=xx,port=xx,dbname=xx'
 *  \return DB_OK Success
 *  \return DB_FAILED Failed to parse database
 */
int parse_conn(char *str, CONNPAR * conn)
{
    int i;
    char **tokens, delm[2];

    G_debug(3, "parse_conn : %s", str);

    /* reset */
    conn->host = NULL;
    conn->port = 0;
    conn->dbname = NULL;
    conn->user = NULL;
    conn->password = NULL;

    if (strchr(str, '=') == NULL) {	/*db name only */
	conn->dbname = G_store(str);
    }
    else {
	delm[0] = ',';
	delm[1] = '\0';
	tokens = G_tokenize(str, delm);
	i = 0;
	while (tokens[i]) {
	    G_debug(3, "token %d : %s", i, tokens[i]);
	    if (strncmp(tokens[i], "host", 4) == 0) {
		conn->host = G_store(tokens[i] + 5);
	    }
	    else if (strncmp(tokens[i], "port", 4) == 0) {
		long port = atol(tokens[i] + 5);

		if (port <= 0) {
		    append_error(_("Wrong port number in MySQL database "
				   "definition: "));
		    append_error(tokens[i] + 5);
		    return DB_FAILED;
		}
		conn->port = (unsigned int)port;
	    }
	    else if (strncmp(tokens[i], "dbname", 6) == 0) {
		conn->dbname = G_store(tokens[i] + 7);
	    }
	    else if (strncmp(tokens[i], "user", 4) == 0) {
		G_warning(_("'user' in database definition "
			    "is not supported, use db.login"));
	    }
	    else if (strncmp(tokens[i], "password", 8) == 0) {
		G_warning(_("'password' in database definition "
			    "is not supported, use db.login"));
	    }
	    else {
		append_error(_("Unknown option in database definition for "));
		append_error("MySQL: ");
		append_error(tokens[i]);
		return DB_FAILED;
	    }
	    i++;
	}
	G_free_tokens(tokens);
    }

    return DB_OK;
}
Beispiel #21
0
// read, parse and set values of scanning variables when new input from stdin comes
void read_new_input(char* &routput, double &zrange_min, double &zrange_max,
                    double &clip_N, double &clip_S, double &clip_E, double &clip_W,
                    double &trim_tolerance, double &rotate, double &zexag, char* &method,
                    int &numscan, double &smooth, double &resolution, bool &use_equalized,
                    struct Cell_head &window, double &offset, bool &region3D,
                    char* &color_output, char* &voutput, char * &ply,
                    char* &contours_output, double &contours_step,
                    int &draw_type, int &draw_threshold, char* &draw_output, bool &paused) {
    char buf[200];
    char **tokens;
    char **tokens2;
    int line;
    // TODO: this leaks

    for (line = 1;; line++) {
        if (G_getl2(buf, 200, stdin)) {
            if(buf[0] == '\0')
                break;
            tokens = G_tokenize(buf, "=");
            if (strcmp(tokens[0], "resolution") == 0)
                resolution = atof(tokens[1]);
            else if (strcmp(tokens[0], "smooth_radius") == 0)
                smooth = atof(tokens[1]);
            else if (strcmp(tokens[0], "output") == 0) {
                if (tokens[1][0] == '\0')
                    routput = NULL;
                else
                    routput = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "zrange") == 0) {
                tokens2 = G_tokenize(tokens[1], ",");
                zrange_min = atof(tokens2[0])/100;
                zrange_max = atof(tokens2[1])/100;
                G_free_tokens(tokens2);
            }
            else if (strcmp(tokens[0], "trim") == 0) {
                tokens2 = G_tokenize(tokens[1], ",");
                clip_N = atof(tokens2[0])/100;
                clip_S = atof(tokens2[1])/100;
                clip_E = atof(tokens2[2])/100;
                clip_W = atof(tokens2[3])/100;
                G_free_tokens(tokens2);
            }
            else if (strcmp(tokens[0], "trim_tolerance") == 0)
                trim_tolerance = atof(tokens[1]);
            else if (strcmp(tokens[0], "rotate") == 0)
                rotate = pcl::deg2rad(atof(tokens[1]) + 180);
            else if (strcmp(tokens[0], "zexag") == 0)
                zexag = atof(tokens[1]);
            else if (strcmp(tokens[0], "method") == 0)
                method = G_store(tokens[1]);
            else if (strcmp(tokens[0], "numscan") == 0)
                numscan = atoi(tokens[1]);
            else if (strcmp(tokens[0], "region") == 0)
                update_input_region(NULL, tokens[1], window, offset, region3D);
            else if (strcmp(tokens[0], "raster") == 0)
                update_input_region(tokens[1], NULL, window, offset, region3D);
            // export
            else if (strcmp(tokens[0], "color_output") == 0) {
                if (tokens[1][0] == '\0')
                    color_output = NULL;
                else
                    color_output = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "vector") == 0) {
                if (tokens[1][0] == '\0')
                    voutput = NULL;
                else
                    voutput = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "ply") == 0) {
                if (tokens[1][0] == '\0')
                    ply = NULL;
                else
                    ply = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "flags") == 0) {
                if (G_strcasestr(tokens[1], "e"))
                    use_equalized = true;
                else
                    use_equalized = false;
            }
            // contours
            else if (strcmp(tokens[0], "contours") == 0) {
                if (tokens[1][0] == '\0')
                    contours_output = NULL;
                else
                    contours_output = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "contours_step") == 0)
                contours_step = atof(tokens[1]);
            // drawing
            else if (strcmp(tokens[0], "draw") == 0)
                get_draw_type(tokens[1], draw_type);
            else if (strcmp(tokens[0], "draw_threshold") == 0)
                draw_threshold = atoi(tokens[1]);
            else if (strcmp(tokens[0], "draw_output") == 0) {
                if (tokens[1][0] == '\0')
                    draw_output = NULL;
                else
                    draw_output = G_store(tokens[1]);
            }
            else if (strcmp(tokens[0], "pause") == 0) {
                paused = true;
            }
            else if (strcmp(tokens[0], "resume") == 0) {
                paused = false;
            }
            G_free_tokens(tokens);
        }
        else
            break;
    }
}