Esempio n. 1
0
/*!
   \brief Pack color table (floating-point map)

   Passed a array of floats that will be converted from cell values
   to packed colors (0xbbggrr) and float to int 
   Floating point data not freed here, use: 
   gsds_free_data_buff(id, ATTY_FLOAT)

   \param filename raster map name
   \param fbuf
   \param ibuf
   \param rows number of rows
   \param cols number of cols
 */
void Gs_pack_colors_float(const char *filename, float *fbuf, int *ibuf,
			  int rows, int cols)
{
    const char *mapset;
    struct Colors colrules;
    unsigned char *r, *g, *b, *set;
    int i, j, *icur;
    FCELL *fcur;

    mapset = G_find_cell2(filename, "");
    if (!mapset) {
	G_warning(_("Raster map <%s> not found"), filename);
	return;
    }

    r = (unsigned char *)G_malloc(cols);
    g = (unsigned char *)G_malloc(cols);
    b = (unsigned char *)G_malloc(cols);
    set = (unsigned char *)G_malloc(cols);

    G_read_colors(filename, mapset, &colrules);

    fcur = fbuf;
    icur = ibuf;

    G_message(_("Translating colors from raster map <%s>..."),
	      G_fully_qualified_name(filename, mapset));
    
    for (i = 0; i < rows; i++) {
	G_lookup_f_raster_colors(fcur, r, g, b, set, cols, &colrules);
	G_percent(i, rows, 2);

	for (j = 0; j < cols; j++) {
	    if (set[j]) {
		icur[j] =
		    (r[j] & 0xff) | ((g[j] & 0xff) << 8) | ((b[j] & 0xff) <<
							    16);
	    }
	    else {
		icur[j] = NO_DATA_COL;
	    }
	}

	icur = &(icur[cols]);
	fcur = &(fcur[cols]);
    }
    G_percent(1, 1, 1);
    
    G_free_colors(&colrules);

    G_free(r);
    G_free(g);
    G_free(b);
    G_free(set);

    return;
}
Esempio n. 2
0
/*!
   \brief Build color table (256)

   Calling function must have already allocated space in buff for range of
   data (256 for now) - simply calls get_color for each cat in color range

   \param filename raster map name
   \param[out] buff data buffer

   \return 1 on success
   \return 0 on failure
 */
int Gs_build_256lookup(const char *filename, int *buff)
{
    const char *mapset;
    struct Colors colrules;
    CELL min, max, cats[256];
    int i;
    unsigned char r[256], g[256], b[256], set[256];

    G_debug(3, "building color table");

    mapset = G_find_cell2(filename, "");
    if (!mapset) {
	G_warning(_("Raster map <%s> not found"), filename);
	return 0;
    }

    G_read_colors(filename, mapset, &colrules);
    G_get_color_range(&min, &max, &colrules);

    if (min < 0 || max > 255) {
	G_warning(_("Color table range doesn't match data (mincol=%d, maxcol=%d"),
		  min, max);

	min = min < 0 ? 0 : min;
	max = max > 255 ? 255 : max;
    }

    G_zero(cats, 256 * sizeof(CELL));

    for (i = min; i <= max; i++) {
	cats[i] = i;
    }

    G_lookup_colors(cats, r, g, b, set, 256, &colrules);

    for (i = 0; i < 256; i++) {

	if (set[i]) {
	    buff[i] =
		(r[i] & 0xff) | ((g[i] & 0xff) << 8) | ((b[i] & 0xff) << 16);
	}
	else {
	    buff[i] = NO_DATA_COL;
	}
    }

    return (1);
}
Esempio n. 3
0
int display( char *name,
             char *mapset,
             RASTER_MAP_TYPE data_type )
{
  struct Colors colors;

  if ( G_read_colors( name, mapset, &colors ) == -1 )
    G_fatal_error(( "Color file for <%s> not available" ), name );

  //G_set_null_value_color(r, g, b, &colors);

  /* Go draw the raster map */
  cell_draw( name, mapset, &colors, data_type );

  /* release the colors now */
  G_free_colors( &colors );

  return 0;
}
Esempio n. 4
0
int
process(char *name, char *mapset, int change_null, RASTER_MAP_TYPE map_type)
{
    struct Colors colr;
    struct History hist;
    struct Categories cats;
    struct Quant quant;
    int colr_ok;
    int hist_ok;
    int cats_ok;
    int quant_ok;

    G_suppress_warnings(1);
    colr_ok = G_read_colors(name, mapset, &colr) > 0;
    hist_ok = G_read_history(name, mapset, &hist) >= 0;
    cats_ok = G_read_raster_cats(name, mapset, &cats) >= 0;

    if (map_type != CELL_TYPE) {
	G_quant_init(&quant);
	quant_ok = G_read_quant(name, mapset, &quant);
	G_suppress_warnings(0);
    }

    if (doit(name, mapset, change_null, map_type))
	return 1;

    if (colr_ok) {
	G_write_colors(name, mapset, &colr);
	G_free_colors(&colr);
    }
    if (hist_ok)
	G_write_history(name, &hist);
    if (cats_ok) {
	cats.num = G_number_of_cats(name, mapset);
	G_write_raster_cats(name, &cats);
	G_free_cats(&cats);
    }
    if (map_type != CELL_TYPE && quant_ok)
	G_write_quant(name, mapset, &quant);

    return 0;
}
Esempio n. 5
0
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand,
                                  const char * pszMapset,
                                  const char * pszCellName )

{
    struct Cell_head	sCellInfo;

    // Note: GISDBASE, LOCATION_NAME ans MAPSET was set in GRASSDataset::Open

    this->poDS = poDS;
    this->nBand = nBand;
    this->valid = false;

    this->pszCellName = G_store ( (char *) pszCellName );
    this->pszMapset = G_store ( (char *) pszMapset );

    G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo );
    nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset );

/* -------------------------------------------------------------------- */
/*      Get min/max values.                                             */
/* -------------------------------------------------------------------- */
    struct FPRange sRange;

    if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, 
                         &sRange ) == -1 )
    {
        bHaveMinMax = FALSE;
    }
    else
    {
        bHaveMinMax = TRUE;
        G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax );
    }

/* -------------------------------------------------------------------- */
/*      Setup band type, and preferred nodata value.                    */
/* -------------------------------------------------------------------- */
    // Negative values are also (?) stored as 4 bytes (format = 3) 
    //       => raster with format < 3 has only positive values

    // GRASS modules usually do not waste space and only the format necessary to keep 
    // full raster values range is used -> no checks if shorter type could be used
    
    if( nGRSType == CELL_TYPE ) {
	if ( sCellInfo.format == 0 ) {  // 1 byte / cell -> possible range 0,255
	    if ( bHaveMinMax && dfCellMin > 0 ) {
                this->eDataType = GDT_Byte;
		dfNoData = 0.0;
	    } else if ( bHaveMinMax && dfCellMax < 255 ) {
                this->eDataType = GDT_Byte;
		dfNoData = 255.0;
	    } else { // maximum is not known or full range is used
		this->eDataType = GDT_UInt16;
		dfNoData = 256.0;
	    }
	    nativeNulls = false;
	} else if ( sCellInfo.format == 1 ) {  // 2 bytes / cell -> possible range 0,65535
	    if ( bHaveMinMax && dfCellMin > 0 ) {
		this->eDataType = GDT_UInt16;
		dfNoData = 0.0;
	    } else if ( bHaveMinMax && dfCellMax < 65535 ) {
                this->eDataType = GDT_UInt16;
		dfNoData = 65535;
	    } else { // maximum is not known or full range is used
		CELL cval;
		this->eDataType = GDT_Int32; 
		G_set_c_null_value ( &cval, 1);
		dfNoData = (double) cval;
		nativeNulls = true;
	    }
	    nativeNulls = false;
	} else {  // 3-4 bytes 
	    CELL cval;
	    this->eDataType = GDT_Int32;
	    G_set_c_null_value ( &cval, 1);
	    dfNoData = (double) cval;
	    nativeNulls = true;
	}
    } 
    else if( nGRSType == FCELL_TYPE ) {
	FCELL fval;
        this->eDataType = GDT_Float32;
	G_set_f_null_value ( &fval, 1);
	dfNoData = (double) fval;
	nativeNulls = true;
    }
    else if( nGRSType == DCELL_TYPE )
    {
	DCELL dval;
        this->eDataType = GDT_Float64;
	G_set_d_null_value ( &dval, 1);
	dfNoData = (double) dval;
	nativeNulls = true;
    }

    nBlockXSize = poDS->nRasterXSize;;
    nBlockYSize = 1;

    G_set_window( &(((GRASSDataset *)poDS)->sCellInfo) );
    if ( (hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset)) < 0 ) {
	CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName );
	return;
    }
    G_copy((void *) &sOpenWindow, (void *) &(((GRASSDataset *)poDS)->sCellInfo), sizeof(struct Cell_head));

/* -------------------------------------------------------------------- */
/*      Do we have a color table?                                       */
/* -------------------------------------------------------------------- */
    poCT = NULL;
    if( G_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 )
    {
	int maxcolor; 
	CELL min, max;

	G_get_color_range ( &min, &max, &sGrassColors);

        if ( bHaveMinMax ) {
	    if ( max < dfCellMax ) {
	       maxcolor = max;
            } else {
	       maxcolor = (int) ceil ( dfCellMax );
	    }
	    if ( maxcolor > GRASS_MAX_COLORS ) { 
		maxcolor = GRASS_MAX_COLORS;
                CPLDebug( "GRASS", "Too many values, color table cut to %d entries.", maxcolor );
	    }
	} else {
	    if ( max < GRASS_MAX_COLORS ) {
	       maxcolor = max;
            } else {
	       maxcolor = GRASS_MAX_COLORS;
               CPLDebug( "GRASS", "Too many values, color table set to %d entries.", maxcolor );
	    }
        }
	    
        poCT = new GDALColorTable();
        for( int iColor = 0; iColor <= maxcolor; iColor++ )
        {
            int	nRed, nGreen, nBlue;
            GDALColorEntry    sColor;

#if GRASS_VERSION_MAJOR  >= 7
            if( Rast_get_c_color( &iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) )
#else
            if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) )
#endif
            {
                sColor.c1 = nRed;
                sColor.c2 = nGreen;
                sColor.c3 = nBlue;
                sColor.c4 = 255;

                poCT->SetColorEntry( iColor, &sColor );
            }
            else
            {
                sColor.c1 = 0;
                sColor.c2 = 0;
                sColor.c3 = 0;
                sColor.c4 = 0;

                poCT->SetColorEntry( iColor, &sColor );
            }
        }
	    
	/* Create metadata enries for color table rules */
	char key[200], value[200];
	int rcount = G_colors_count ( &sGrassColors );

	sprintf ( value, "%d", rcount );
	this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", value );

	/* Add the rules in reverse order */
	for ( int i = rcount-1; i >= 0; i-- ) {
	    DCELL val1, val2;
	    unsigned char r1, g1, b1, r2, g2, b2;

	     G_get_f_color_rule ( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &sGrassColors, i );
		

	     sprintf ( key, "COLOR_TABLE_RULE_RGB_%d", rcount-i-1 );
	     sprintf ( value, "%e %e %d %d %d %d %d %d", val1, val2, r1, g1, b1, r2, g2, b2 );
	     this->SetMetadataItem( key, value );
	}
    } else {
	this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", "0" );
    }
    
    this->valid = true;
}
Esempio n. 6
0
int main( int argc, char **argv )
{
  struct GModule *module;
  struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt, *north_opt, *south_opt, *east_opt, *west_opt, *rows_opt, *cols_opt;
  struct Cell_head window;

  /* Initialize the GIS calls */
  G_gisinit( argv[0] );

  module = G_define_module();
  module->description = ( "Get info about locations,mapsets,maps" );

  info_opt = G_define_option();
  info_opt->key = "info";
  info_opt->type = TYPE_STRING;
  info_opt->description = "info key";
  info_opt->options = "proj,window,size,query,info,colors,stats";

  rast_opt = G_define_standard_option( G_OPT_R_INPUT );
  rast_opt->key = "rast";
  rast_opt->required = NO;

  vect_opt = G_define_standard_option( G_OPT_V_INPUT );
  vect_opt->key = "vect";
  vect_opt->required = NO;

  coor_opt = G_define_option();
  coor_opt->key = "coor";
  coor_opt->type = TYPE_DOUBLE;
  coor_opt->multiple = YES;

  north_opt = G_define_option();
  north_opt->key = "north";
  north_opt->type = TYPE_STRING;

  south_opt = G_define_option();
  south_opt->key = "south";
  south_opt->type = TYPE_STRING;

  east_opt = G_define_option();
  east_opt->key = "east";
  east_opt->type = TYPE_STRING;

  west_opt = G_define_option();
  west_opt->key = "west";
  west_opt->type = TYPE_STRING;

  rows_opt = G_define_option();
  rows_opt->key = "rows";
  rows_opt->type = TYPE_INTEGER;

  cols_opt = G_define_option();
  cols_opt->key = "cols";
  cols_opt->type = TYPE_INTEGER;

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


  if ( strcmp( "proj", info_opt->answer ) == 0 )
  {
    G_get_window( &window );
    /* code from g.proj */
    if ( window.proj != PROJECTION_XY )
    {
      struct Key_Value *projinfo, *projunits;
      char *wkt;
      projinfo = G_get_projinfo();
      projunits = G_get_projunits();
      wkt = GPJ_grass_to_wkt( projinfo, projunits,  0, 0 );
      fprintf( stdout, "%s", wkt );
    }
  }
  else if ( strcmp( "window", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster width and height
  else if ( strcmp( "size", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%d,%d", window.cols, window.rows );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster informations
  else if ( strcmp( "info", info_opt->answer ) == 0 )
  {
    struct FPRange range;
    double zmin, zmax;

    // Data type
    RASTER_MAP_TYPE raster_type = G_raster_map_type( rast_opt->answer, "" );
    fprintf( stdout, "TYPE:%d\n", raster_type );

    // Statistics
    if ( G_read_fp_range( rast_opt->answer, "", &range ) < 0 )
    {
      G_fatal_error(( "Unable to read range file" ) );
    }
    G_get_fp_range_min_max( &range, &zmin, &zmax );
    fprintf( stdout, "MIN_VALUE:%.17e\n", zmin );
    fprintf( stdout, "MAX_VALUE:%.17e\n", zmax );
  }
  else if ( strcmp( "colors", info_opt->answer ) == 0 )
  {
    // Color table
    struct Colors colors;
    int i, ccount;
    if ( G_read_colors( rast_opt->answer, "", &colors ) == 1 )
    {
      //int maxcolor;
      //CELL min, max;

      //G_get_color_range ( &min, &max, &colors);
      ccount = G_colors_count( &colors );
      for ( i = ccount - 1; i >= 0; i-- )
      {
        DCELL val1, val2;
        unsigned char r1, g1, b1, r2, g2, b2;

        G_get_f_color_rule( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &colors, i );
        fprintf( stdout, "%.17e %.17e %d %d %d %d %d %d\n", val1, val2, r1, g1, b1, r2, g2, b2 );
      }
    }
  }

  else if ( strcmp( "query", info_opt->answer ) == 0 )
  {
    double x, y;
    int row, col;
    //x = atof( coor_opt->answers[0] );
    //y = atof( coor_opt->answers[1] );
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      char buff[101];
      G_get_cellhd( rast_opt->answer, "", &window );
      G_set_window( &window );
      fd = G_open_cell_old( rast_opt->answer, "" );
      // wait for coors from stdin
      while ( fgets( buff, 100, stdin ) != 0 )
      {
        if ( sscanf( buff, "%lf%lf", &x, &y ) != 2 )
        {
          fprintf( stdout, "value:error\n" );
        }
        else
        {
          col = ( int ) G_easting_to_col( x, &window );
          row = ( int ) G_northing_to_row( y, &window );
          if ( col == window.cols )
            col--;
          if ( row == window.rows )
            row--;

          if ( col < 0 || col > window.cols || row < 0 || row > window.rows )
          {
            fprintf( stdout, "value:out\n" );
          }
          else
          {
            void *ptr;
            double val;

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
            rast_type = G_get_raster_map_type( fd );
#else
            rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
            cell = G_allocate_c_raster_buf();
            dcell = G_allocate_d_raster_buf();

            if ( rast_type == CELL_TYPE )
            {
              if ( G_get_c_raster_row( fd, cell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
              val = cell[col];
              ptr = &( cell[col] );
            }
            else
            {
              if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
              val = dcell[col];
              ptr = &( dcell[col] );
            }
            if ( G_is_null_value( ptr, rast_type ) )
            {
              fprintf( stdout, "value:null\n" );
            }
            else
            {
              fprintf( stdout, "value:%f\n", val );
            }
          }
        }
        fflush( stdout );
      }
      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  else if ( strcmp( "stats", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      int ncols, nrows;
      int row, col;
      void *ptr;
      double val;
      double min = DBL_MAX;
      double max = -DBL_MAX;
      double sum = 0; // sum of values
      int count = 0; // count of non null values
      double mean = 0;
      double squares_sum = 0; // sum of squares
      double stdev = 0; // standard deviation

      G_get_cellhd( rast_opt->answer, "", &window );
      window.north = atof( north_opt->answer );
      window.south = atof( south_opt->answer );
      window.east = atof( east_opt->answer );
      window.west = atof( west_opt->answer );
      window.rows = ( int ) atoi( rows_opt->answer );
      window.cols = ( int ) atoi( cols_opt->answer );

      G_set_window( &window );
      fd = G_open_cell_old( rast_opt->answer, "" );

      ncols = G_window_cols();
      nrows = G_window_rows();

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
      rast_type = G_get_raster_map_type( fd );
#else
      rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
      cell = G_allocate_c_raster_buf();
      dcell = G_allocate_d_raster_buf();

      // Calc stats is very slow for large rasters -> prefer optimization for speed over
      // code length and readability (which is not currently true)
      for ( row = 0; row < nrows; row++ )
      {
        if ( rast_type == CELL_TYPE )
        {
          if ( G_get_c_raster_row( fd, cell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
        }
        else
        {
          if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
        }

        for ( col = 0; col < ncols; col++ )
        {
          if ( rast_type == CELL_TYPE )
          {
            val = cell[col];
            ptr = &( cell[col] );
          }
          else
          {
            val = dcell[col];
            ptr = &( dcell[col] );
          }
          if ( ! G_is_null_value( ptr, rast_type ) )
          {
            if ( val < min ) min = val;
            if ( val > max ) max = val;
            sum += val;
            count++;
            squares_sum += pow( val, 2 );
          }
        }
      }
      mean = sum / count;
      squares_sum -= count * pow( mean, 2 );
      stdev = sqrt( squares_sum / ( count - 1 ) );

      fprintf( stdout, "MIN:%.17e\n", min );
      fprintf( stdout, "MAX:%.17e\n", max );
      fprintf( stdout, "SUM:%.17e\n", sum );
      fprintf( stdout, "MEAN:%.17e\n", mean );
      fprintf( stdout, "COUNT:%d\n", count );
      fprintf( stdout, "STDEV:%.17e\n", stdev );
      fprintf( stdout, "SQSUM:%.17e\n", squares_sum );

      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }

  exit( EXIT_SUCCESS );
}
Esempio n. 7
0
int main(int argc, char **argv)
{
    int overwrite;
    int interactive;
    int remove;
    int have_colors;
    struct Colors colors, colors_tmp;
    struct Cell_stats statf;
    int have_stats = 0;
    struct FPRange range;
    DCELL min, max;
    char *name, *mapset;
    char *style, *cmap, *cmapset;
    char *rules;
    int fp;
    struct GModule *module;
    struct
    {
	struct Flag *r, *w, *l, *g, *a, *e, *i, *q, *n;
    } flag;
    struct
    {
	struct Option *map, *colr, *rast, *rules;
    } opt;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, color table");
    module->description =
	_("Creates/modifies the color table associated with a raster map layer.");

    opt.map = G_define_standard_option(G_OPT_R_MAP);
    opt.map->required = NO;
    opt.map->guisection = _("Required");

    scan_rules();

    opt.colr = G_define_option();
    opt.colr->key = "color";
    opt.colr->key_desc = "style";
    opt.colr->type = TYPE_STRING;
    opt.colr->required = NO;
    opt.colr->options = rules_list();
    opt.colr->description = _("Type of color table");
    opt.colr->descriptions = rules_descriptions();
    opt.colr->guisection = _("Colors");

    opt.rast = G_define_option();
    opt.rast->key = "raster";
    opt.rast->type = TYPE_STRING;
    opt.rast->required = NO;
    opt.rast->gisprompt = "old,cell,raster";
    opt.rast->description =
	_("Raster map name from which to copy color table");

    opt.rules = G_define_standard_option(G_OPT_F_INPUT);
    opt.rules->key = "rules";
    opt.rules->required = NO;
    opt.rules->description = _("Path to rules file (\"-\" to read rules from stdin)");
    opt.rules->guisection = _("Colors");

    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description = _("Remove existing color table");

    flag.w = G_define_flag();
    flag.w->key = 'w';
    flag.w->description =
	_("Only write new color table if one doesn't already exist");

    flag.l = G_define_flag();
    flag.l->key = 'l';
    flag.l->description = _("List available rules then exit");

    flag.n = G_define_flag();
    flag.n->key = 'n';
    flag.n->description = _("Invert colors");
    flag.n->guisection = _("Colors");

    flag.g = G_define_flag();
    flag.g->key = 'g';
    flag.g->description = _("Logarithmic scaling");
    flag.g->guisection = _("Colors");

    flag.a = G_define_flag();
    flag.a->key = 'a';
    flag.a->description = _("Logarithmic-absolute scaling");
    flag.a->guisection = _("Colors");

    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Histogram equalization");
    flag.e->guisection = _("Colors");

    flag.i = G_define_flag();
    flag.i->key = 'i';
    flag.i->description = _("Enter rules interactively");

    /* please, remove before GRASS 7 released */
    flag.q = G_define_flag();
    flag.q->key = 'q';
    flag.q->description = _("Run quietly");


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

    /* please, remove before GRASS 7 released */
    if (flag.q->answer) {
	G_putenv("GRASS_VERBOSE", "0");
	G_warning(_("The '-q' flag is superseded and will be removed "
		    "in future. Please use '--quiet' instead."));
    }

    if (flag.l->answer) {
	list_rules();
	return EXIT_SUCCESS;
    }

    overwrite = !flag.w->answer;
    interactive = flag.i->answer;
    remove = flag.r->answer;

    name = opt.map->answer;

    style = opt.colr->answer;
    cmap = opt.rast->answer;
    rules = opt.rules->answer;

    if (!name)
	G_fatal_error(_("No raster map specified"));

    if (!cmap && !style && !rules && !interactive && !remove)
	G_fatal_error(_("One of \"-i\" or \"-r\" or options \"color\", \"rast\" or \"rules\" must be specified!"));

    if (interactive && (style || rules || cmap))
	G_fatal_error(_("Interactive mode is incompatible with \"color\", \"rules\", and \"raster\" options"));

    if ((style && (cmap || rules)) || (cmap && rules)) {
	if ((style && rules && !cmap) && strcmp(style, "rules") == 0)
	    style = NULL;
	else
	    G_fatal_error(
		_("\"color\", \"rules\", and \"raster\" options are mutually exclusive"));
    }

    /* handle rules="-" (from stdin) by translating that to colors=rules */
    /* this method should not be ported to GRASS 7 verbatim, as color=rules DNE */
    if (rules && strcmp(rules, "-") == 0) {
	style = G_store("rules");
	rules = NULL;
    }

    if (flag.g->answer && flag.a->answer)
	G_fatal_error(_("-g and -a flags are mutually exclusive"));

    mapset = G_find_cell2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    if (remove) {
	int stat = G_remove_colors(name, mapset);

	if (stat < 0)
	    G_fatal_error(_("Unable to remove color table of raster map <%s>"), name);
	if (stat == 0)
	    G_warning(_("Color table of raster map <%s> not found"), name);
	return EXIT_SUCCESS;
    }

    G_suppress_warnings(1);
    have_colors = G_read_colors(name, mapset, &colors);
    /*if (have_colors >= 0)
       G_free_colors(&colors); */

    if (have_colors > 0 && !overwrite) {
	G_warning(_("Color table exists. Exiting."));
	exit(EXIT_FAILURE);
    }

    G_suppress_warnings(0);

    fp = G_raster_map_is_fp(name, mapset);
    G_read_fp_range(name, mapset, &range);
    G_get_fp_range_min_max(&range, &min, &max);

    if (interactive) {
	if (!read_color_rules(stdin, &colors, min, max, fp))
	    exit(EXIT_FAILURE);
    }
    else if (style) {
	/* 
	 * here the predefined color-table color-styles are created by GRASS library calls. 
	 */
	if (strcmp(style, "random") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'random' is not supported for floating point raster map"));
	    G_make_random_colors(&colors, (CELL) min, (CELL) max);
	}
	else if (strcmp(style, "grey.eq") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'grey.eq' is not supported for floating point raster map"));
	    if (!have_stats)
		have_stats = get_stats(name, mapset, &statf);
	    G_make_histogram_eq_colors(&colors, &statf);
	}
	else if (strcmp(style, "grey.log") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'grey.log' is not supported for floating point raster map"));
	    if (!have_stats)
		have_stats = get_stats(name, mapset, &statf);
	    G_make_histogram_log_colors(&colors, &statf, (CELL) min,
					(CELL) max);
	}
	else if (strcmp(style, "rules") == 0) {
	    if (!read_color_rules(stdin, &colors, min, max, fp))
		exit(EXIT_FAILURE);
	}
	else if (find_rule(style))
	    G_make_fp_colors(&colors, style, min, max);
	else
	    G_fatal_error(_("Unknown color request '%s'"), style);
    }
    else if (rules) {
	if (!G_load_fp_colors(&colors, rules, min, max)) {
	    /* for backwards compatibility try as std name; remove for GRASS 7 */
	    char path[GPATH_MAX];

	    /* don't bother with native dirsep as not needed for backwards compatibility */
	    sprintf(path, "%s/etc/colors/%s", G_gisbase(), rules);

	    if (!G_load_fp_colors(&colors, path, min, max))
		G_fatal_error(_("Unable to load rules file <%s>"), rules);
	}
    }
    else {
	/* use color from another map (cmap) */
	cmapset = G_find_cell2(cmap, "");
	if (cmapset == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), cmap);

	if (G_read_colors(cmap, cmapset, &colors) < 0)
	    G_fatal_error(_("Unable to read color table for raster map <%s>"), cmap);
    }

    if (fp)
	G_mark_colors_as_fp(&colors);

    if (flag.n->answer)
	G_invert_colors(&colors);

    if (flag.e->answer) {
	if (fp) {
	    struct FP_stats fpstats;
	    get_fp_stats(name, mapset, &fpstats, min, max, flag.g->answer, flag.a->answer);
	    G_histogram_eq_colors_fp(&colors_tmp, &colors, &fpstats);
	}
	else {
	    if (!have_stats) 
		have_stats = get_stats(name, mapset, &statf);
	    G_histogram_eq_colors(&colors_tmp, &colors, &statf);
	}
	colors = colors_tmp;
    }

    if (flag.g->answer) {
	G_log_colors(&colors_tmp, &colors, 100);
	colors = colors_tmp;
    }

    if (flag.a->answer) {
	G_abs_log_colors(&colors_tmp, &colors, 100);
	colors = colors_tmp;
    }

    if (fp)
	G_mark_colors_as_fp(&colors);

    if (G_write_colors(name, mapset, &colors) >= 0)
	G_message(_("Color table for raster map <%s> set to '%s'"), name,
		  interactive ? "rules" : style ? style : rules ? rules :
		  cmap);

    exit(EXIT_SUCCESS);
}
Esempio n. 8
0
int read_rgb(char *key, char *data)
{
    char names[3][100];
    char fullname[100];
    int i;

    if (sscanf(data, "%s %s %s", names[0], names[1], names[2]) != 3) {
	error(key, data, "illegal request (rgb)");
	return 0;
    }

    PS.do_raster = 0;
    PS.do_colortable = 0;
    if (PS.cell_fd >= 0) {
	G_close_cell(PS.cell_fd);
	G_free(PS.cell_name);
	G_free(PS.cell_mapset);
	G_free_colors(&PS.colors);
	PS.cell_fd = -1;
    }

    /* initialize group structure (for compatibility with PS_raster_plot()) */
    I_init_group_ref(&grp.ref);

    /*
     * not relevant here
     *
     if (I_get_group_ref(grp.group_name, &grp.ref) == 0)
     G_fatal_error(_("Can't get group information"));
     */

    grp.group_name = "RGB Group";

    /* get file names for R, G, & B */

    for (i = 0; i < 3; i++) {
	char *mapset, *name, *p;

	name = names[i];

	p = strchr(name, '@');
	if (p) {
	    *p = '\0';
	    mapset = p + 1;
	}
	else {
	    mapset = G_find_file2("cell", name, "");
	    if (!mapset) {
		error(name, "", "not found");
		return 0;
	    }
	}

	grp.name[i] = G_store(name);
	grp.mapset[i] = G_store(mapset);

	/* read in colors */
	if (G_read_colors(grp.name[i], grp.mapset[i], &(grp.colors[i])) == -1) {
	    sprintf(fullname, "%s in %s", grp.name[i], grp.mapset[i]);
	    error(fullname, "", "can't read color table");
	    return 0;
	}

	/* open raster maps for reading */
	if ((grp.fd[i] = G_open_cell_old(grp.name[i], grp.mapset[i])) < 0) {
	    sprintf(fullname, "%s in %s", grp.name[i], grp.mapset[i]);
	    error(fullname, "", "can't open raster map");
	    G_free_colors(&(grp.colors[i]));
	    return 0;
	}
    }

    strcpy(PS.celltitle, grp.group_name);
    G_strip(PS.celltitle);
    return 1;
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *rastin, *rastout, *method;
    struct History history;
    char title[64];
    char buf_nsres[100], buf_ewres[100];
    struct Colors colors;
    char *inmap;
    int infile, outfile;
    DCELL *outbuf;
    int row, col;
    struct Cell_head dst_w, src_w;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, resample");
    module->description =
	_("Resamples raster map layers to a finer grid using interpolation.");

    rastin = G_define_standard_option(G_OPT_R_INPUT);
    rastout = G_define_standard_option(G_OPT_R_OUTPUT);

    method = G_define_option();
    method->key = "method";
    method->type = TYPE_STRING;
    method->required = NO;
    method->description = _("Interpolation method");
    method->options = "nearest,bilinear,bicubic";
    method->answer = "bilinear";

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

    if (G_strcasecmp(method->answer, "nearest") == 0)
	neighbors = 1;
    else if (G_strcasecmp(method->answer, "bilinear") == 0)
	neighbors = 2;
    else if (G_strcasecmp(method->answer, "bicubic") == 0)
	neighbors = 4;
    else
	G_fatal_error(_("Invalid method: %s"), method->answer);

    G_get_set_window(&dst_w);

    inmap = G_find_cell2(rastin->answer, "");
    if (!inmap)
	G_fatal_error(_("Raster map <%s> not found"), rastin->answer);

    /* set window to old map */
    G_get_cellhd(rastin->answer, inmap, &src_w);

    /* enlarge source window */
    {
	double north = G_row_to_northing(0.5, &dst_w);
	double south = G_row_to_northing(dst_w.rows - 0.5, &dst_w);
	int r0 = (int)floor(G_northing_to_row(north, &src_w) - 0.5) - 1;
	int r1 = (int)floor(G_northing_to_row(south, &src_w) - 0.5) + 3;
	double west = G_col_to_easting(0.5, &dst_w);
	double east = G_col_to_easting(dst_w.cols - 0.5, &dst_w);
	int c0 = (int)floor(G_easting_to_col(west, &src_w) - 0.5) - 1;
	int c1 = (int)floor(G_easting_to_col(east, &src_w) - 0.5) + 3;

	src_w.south -= src_w.ns_res * (r1 - src_w.rows);
	src_w.north += src_w.ns_res * (-r0);
	src_w.west -= src_w.ew_res * (-c0);
	src_w.east += src_w.ew_res * (c1 - src_w.cols);
	src_w.rows = r1 - r0;
	src_w.cols = c1 - c0;
    }

    G_set_window(&src_w);

    /* allocate buffers for input rows */
    for (row = 0; row < neighbors; row++)
	bufs[row] = G_allocate_d_raster_buf();

    cur_row = -100;

    /* open old map */
    infile = G_open_cell_old(rastin->answer, inmap);
    if (infile < 0)
	G_fatal_error(_("Unable to open raster map <%s>"), rastin->answer);

    /* reset window to current region */
    G_set_window(&dst_w);

    outbuf = G_allocate_d_raster_buf();

    /* open new map */
    outfile = G_open_raster_new(rastout->answer, DCELL_TYPE);
    if (outfile < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), rastout->answer);

    G_suppress_warnings(1);
    /* otherwise get complaints about window changes */

    switch (neighbors) {
    case 1:			/* nearest */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f + 0.5);

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f + 0.5);

		double c = bufs[0][mapcol0];

		if (G_is_d_null_value(&c)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = c;
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;

    case 2:			/* bilinear */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f);
	    double v = maprow_f - maprow0;

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f);
		int mapcol1 = mapcol0 + 1;
		double u = mapcol_f - mapcol0;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];

		if (G_is_d_null_value(&c00) ||
		    G_is_d_null_value(&c01) ||
		    G_is_d_null_value(&c10) || G_is_d_null_value(&c11)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = G_interp_bilinear(u, v, c00, c01, c10, c11);
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;

    case 4:			/* bicubic */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow1 = (int)floor(maprow_f);
	    int maprow0 = maprow1 - 1;
	    double v = maprow_f - maprow1;

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol1 = (int)floor(mapcol_f);
		int mapcol0 = mapcol1 - 1;
		int mapcol2 = mapcol1 + 1;
		int mapcol3 = mapcol1 + 2;
		double u = mapcol_f - mapcol1;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c02 = bufs[0][mapcol2];
		double c03 = bufs[0][mapcol3];

		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];
		double c12 = bufs[1][mapcol2];
		double c13 = bufs[1][mapcol3];

		double c20 = bufs[2][mapcol0];
		double c21 = bufs[2][mapcol1];
		double c22 = bufs[2][mapcol2];
		double c23 = bufs[2][mapcol3];

		double c30 = bufs[3][mapcol0];
		double c31 = bufs[3][mapcol1];
		double c32 = bufs[3][mapcol2];
		double c33 = bufs[3][mapcol3];

		if (G_is_d_null_value(&c00) ||
		    G_is_d_null_value(&c01) ||
		    G_is_d_null_value(&c02) ||
		    G_is_d_null_value(&c03) ||
		    G_is_d_null_value(&c10) ||
		    G_is_d_null_value(&c11) ||
		    G_is_d_null_value(&c12) ||
		    G_is_d_null_value(&c13) ||
		    G_is_d_null_value(&c20) ||
		    G_is_d_null_value(&c21) ||
		    G_is_d_null_value(&c22) ||
		    G_is_d_null_value(&c23) ||
		    G_is_d_null_value(&c30) ||
		    G_is_d_null_value(&c31) ||
		    G_is_d_null_value(&c32) || G_is_d_null_value(&c33)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = G_interp_bicubic(u, v,
						   c00, c01, c02, c03,
						   c10, c11, c12, c13,
						   c20, c21, c22, c23,
						   c30, c31, c32, c33);
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;
    }

    G_percent(dst_w.rows, dst_w.rows, 2);

    G_close_cell(infile);
    G_close_cell(outfile);


    /* record map metadata/history info */
    sprintf(title, "Resample by %s interpolation", method->answer);
    G_put_cell_title(rastout->answer, title);

    G_short_history(rastout->answer, "raster", &history);
    strncpy(history.datsrc_1, rastin->answer, RECORD_LEN);
    history.datsrc_1[RECORD_LEN - 1] = '\0';	/* strncpy() doesn't null terminate if maxfill */
    G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj);
    G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj);
    sprintf(history.datsrc_2, "Source map NS res: %s   EW res: %s", buf_nsres,
	    buf_ewres);
    G_command_history(&history);
    G_write_history(rastout->answer, &history);

    /* copy color table from source map */
    if (G_read_colors(rastin->answer, inmap, &colors) < 0)
	G_fatal_error(_("Unable to read color table for %s"), rastin->answer);
    G_mark_colors_as_fp(&colors);
    if (G_write_colors(rastout->answer, G_mapset(), &colors) < 0)
	G_fatal_error(_("Unable to write color table for %s"),
		      rastout->answer);

    return (EXIT_SUCCESS);
}
Esempio n. 10
0
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand,
                                  const char * pszMapset,
                                  const char * pszCellName )

{
    struct Cell_head	sCellInfo;

    this->poDS = poDS;
    this->nBand = nBand;

    G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo );
    nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset );

/* -------------------------------------------------------------------- */
/*      Get min/max values.                                             */
/* -------------------------------------------------------------------- */
    struct FPRange sRange;

    if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, 
                         &sRange ) == -1 )
    {
        bHaveMinMax = FALSE;
    }
    else
    {
        bHaveMinMax = TRUE;
        G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax );
    }

/* -------------------------------------------------------------------- */
/*      Setup band type, and preferred nodata value.                    */
/* -------------------------------------------------------------------- */
    dfNoData = 0.0;
    if( nGRSType == CELL_TYPE && sCellInfo.format == 0 )
    {
        if( bHaveMinMax && dfCellMin < 1.0 && dfCellMax > 254.0 )
        {
            this->eDataType = GDT_UInt16;
            dfNoData = 256.0;
        }
        else
        {
            this->eDataType = GDT_Byte;
            if( dfCellMax < 255.0 )
                dfNoData = 255.0;
            else
                dfNoData = 0.0;
        }
    }
    else if( nGRSType == CELL_TYPE && sCellInfo.format == 1 )
    {
        this->eDataType = GDT_UInt16;
        dfNoData = 65535.0;
    }
    else if( nGRSType == CELL_TYPE )
    {
        this->eDataType = GDT_UInt32;
        dfNoData = 65535.0;
    }
    else if( nGRSType == FCELL_TYPE )
    {
        this->eDataType = GDT_Float32;
        dfNoData = -12345.0;
    }
    else if( nGRSType == DCELL_TYPE )
    {
        this->eDataType = GDT_Float64;
        dfNoData = -12345.0;
    }
    
    nBlockXSize = poDS->nRasterXSize;;
    nBlockYSize = 1;

    hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset);

/* -------------------------------------------------------------------- */
/*      Do we have a color table?                                       */
/* -------------------------------------------------------------------- */
    struct Colors sGrassColors;

    poCT = NULL;
    if( G_read_colors( (char *) pszCellName, (char *) pszMapset, 
                       &sGrassColors ) == 1 )
    {
        poCT = new GDALColorTable();
        for( int iColor = 0; iColor < 256; iColor++ )
        {
            int	nRed, nGreen, nBlue;
            GDALColorEntry    sColor;

            if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) )
            {
                sColor.c1 = nRed;
                sColor.c2 = nGreen;
                sColor.c3 = nBlue;
                sColor.c4 = 255;

                poCT->SetColorEntry( iColor, &sColor );
            }
            else
            {
                sColor.c1 = 0;
                sColor.c2 = 0;
                sColor.c3 = 0;
                sColor.c4 = 0;

                poCT->SetColorEntry( iColor, &sColor );
            }
        }

        G_free_colors( &sGrassColors );
    }
}
Esempio n. 11
0
int IL_resample_output_2d(struct interp_params *params, double zmin, double zmax,	/* min,max input z-values */
			  double zminac, double zmaxac,	/* min,max interpolated values */
			  double c1min, double c1max, double c2min, double c2max, double gmin, double gmax, double ertot,	/* total interplating func. error */
			  char *input,	/* input file name */
			  double *dnorm, struct Cell_head *outhd,	/* Region with desired resolution */
			  struct Cell_head *winhd,	/* Current region */
			  char *smooth, int n_points)

/*
 * Creates output files as well as history files  and color tables for
 * them.
 */
{
    FCELL *cell1;		/* cell buffer */
    int cf1 = 0, cf2 = 0, cf3 = 0, cf4 = 0, cf5 = 0, cf6 = 0;	/* cell file descriptors */
    int nrows, ncols;		/* current region rows and columns */
    int i;			/* loop counter */
    char *mapset;
    float dat1, dat2;
    struct Colors colors, colors2;
    double value1, value2;
    struct History hist, hist1, hist2, hist3, hist4, hist5;
    struct _Color_Rule_ *rule;
    char *maps, *type;
    int cond1, cond2;

    cond2 = ((params->pcurv != NULL) ||
	     (params->tcurv != NULL) || (params->mcurv != NULL));
    cond1 = ((params->slope != NULL) || (params->aspect != NULL) || cond2);

    /* change region to output cell file region */
    fprintf(stderr,
	    "Temporarily changing the region to desired resolution...\n");
    if (G_set_window(outhd) < 0) {
	fprintf(stderr, "Cannot set region to output region!\n");
	return -1;
    }
    mapset = G_mapset();

    cell1 = G_allocate_f_raster_buf();

    if (params->elev != NULL) {
	cf1 = G_open_fp_cell_new(params->elev);
	if (cf1 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n", params->elev);
	    return -1;
	}
    }

    if (params->slope != NULL) {
	cf2 = G_open_fp_cell_new(params->slope);
	if (cf2 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->slope);
	    return -1;
	}
    }

    if (params->aspect != NULL) {
	cf3 = G_open_fp_cell_new(params->aspect);
	if (cf3 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->aspect);
	    return -1;
	}
    }

    if (params->pcurv != NULL) {
	cf4 = G_open_fp_cell_new(params->pcurv);
	if (cf4 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->pcurv);
	    return -1;
	}
    }

    if (params->tcurv != NULL) {
	cf5 = G_open_fp_cell_new(params->tcurv);
	if (cf5 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->tcurv);
	    return -1;
	}
    }

    if (params->mcurv != NULL) {
	cf6 = G_open_fp_cell_new(params->mcurv);
	if (cf6 < 0) {
	    fprintf(stderr, "unable to create raster map %s\n",
		    params->mcurv);
	    return -1;
	}
    }

    nrows = outhd->rows;
    if (nrows != params->nsizr) {
	fprintf(stderr, "first change your rows number(%d) to %d!\n",
		nrows, params->nsizr);
	return -1;
    }

    ncols = outhd->cols;
    if (ncols != params->nsizc) {
	fprintf(stderr, "first change your rows number(%d) to %d!\n",
		ncols, params->nsizc);
	return -1;
    }

    if (params->elev != NULL) {
	fseek(params->Tmp_fd_z, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_z, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_z);
	    if (G_put_f_raster_row(cf1, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->slope != NULL) {
	fseek(params->Tmp_fd_dx, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_dx, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dx);
	    /*
	     * for (ii==0;ii<params->nsizc;ii++) { fprintf(stderr,"ii=%d ",ii);
	     * fprintf(stderr,"%f ",cell1[ii]); }
	     * fprintf(stderr,"params->nsizc=%d \n",params->nsizc);
	     */
	    if (G_put_f_raster_row(cf2, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->aspect != NULL) {
	fseek(params->Tmp_fd_dy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_dy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dy);
	    if (G_put_f_raster_row(cf3, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->pcurv != NULL) {
	fseek(params->Tmp_fd_xx, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_xx, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xx);
	    if (G_put_f_raster_row(cf4, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->tcurv != NULL) {
	fseek(params->Tmp_fd_yy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_yy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_yy);
	    if (G_put_f_raster_row(cf5, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (params->mcurv != NULL) {
	fseek(params->Tmp_fd_xy, 0L, 0);	/* seek to the beginning */
	for (i = 0; i < params->nsizr; i++) {
	    /* seek to the right row */
	    if (fseek(params->Tmp_fd_xy, (long)
		      ((params->nsizr - 1 -
			i) * params->nsizc * sizeof(FCELL)), 0) == -1) {
		fprintf(stderr, "cannot fseek to the right spot\n");
		return -1;
	    }
	    fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xy);
	    if (G_put_f_raster_row(cf6, cell1) < 0) {
		fprintf(stderr, "cannot write file\n");
		return -1;
	    }
	}
    }

    if (cf1)
	G_close_cell(cf1);
    if (cf2)
	G_close_cell(cf2);
    if (cf3)
	G_close_cell(cf3);
    if (cf4)
	G_close_cell(cf4);
    if (cf5)
	G_close_cell(cf5);
    if (cf6)
	G_close_cell(cf6);

    /* write colormaps and history for output cell files */
    /* colortable for elevations */
    maps = G_find_file("cell", input, "");

    if (params->elev != NULL) {
	if (maps == NULL) {
	    fprintf(stderr, "file [%s] not found\n", input);
	    return -1;
	}
	G_init_colors(&colors2);
	/*
	 * G_mark_colors_as_fp(&colors2);
	 */

	if (G_read_colors(input, maps, &colors) >= 0) {
	    if (colors.modular.rules) {
		rule = colors.modular.rules;

		while (rule->next)
		    rule = rule->next;

		for (; rule; rule = rule->prev) {
		    value1 = rule->low.value * params->zmult;
		    value2 = rule->high.value * params->zmult;
		    G_add_modular_d_raster_color_rule(&value1, rule->low.red,
						      rule->low.grn,
						      rule->low.blu, &value2,
						      rule->high.red,
						      rule->high.grn,
						      rule->high.blu,
						      &colors2);
		}
	    }

	    if (colors.fixed.rules) {
		rule = colors.fixed.rules;

		while (rule->next)
		    rule = rule->next;

		for (; rule; rule = rule->prev) {
		    value1 = rule->low.value * params->zmult;
		    value2 = rule->high.value * params->zmult;
		    G_add_d_raster_color_rule(&value1, rule->low.red,
					      rule->low.grn, rule->low.blu,
					      &value2, rule->high.red,
					      rule->high.grn, rule->high.blu,
					      &colors2);
		}
	    }

	    maps = NULL;
	    maps = G_find_file("cell", params->elev, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->elev);
		return -1;
	    }

	    if (G_write_colors(params->elev, maps, &colors2) < 0) {
		fprintf(stderr, "Cannot write color table\n");
		return -1;
	    }
	    G_quantize_fp_map_range(params->elev, mapset,
				    zminac - 0.5, zmaxac + 0.5,
				    (CELL) (zminac - 0.5),
				    (CELL) (zmaxac + 0.5));
	}
	else
	    fprintf(stderr,
		    "No color table for input file -- will not create color table\n");
    }

    /* colortable for slopes */
    if (cond1 & (!params->deriv)) {
	G_init_colors(&colors);
	G_add_color_rule(0, 255, 255, 255, 2, 255, 255, 0, &colors);
	G_add_color_rule(2, 255, 255, 0, 5, 0, 255, 0, &colors);
	G_add_color_rule(5, 0, 255, 0, 10, 0, 255, 255, &colors);
	G_add_color_rule(10, 0, 255, 255, 15, 0, 0, 255, &colors);
	G_add_color_rule(15, 0, 0, 255, 30, 255, 0, 255, &colors);
	G_add_color_rule(30, 255, 0, 255, 50, 255, 0, 0, &colors);
	G_add_color_rule(50, 255, 0, 0, 90, 0, 0, 0, &colors);

	if (params->slope != NULL) {
	    maps = NULL;
	    maps = G_find_file("cell", params->slope, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->slope);
		return -1;
	    }
	    G_write_colors(params->slope, maps, &colors);
	    G_quantize_fp_map_range(params->slope, mapset, 0., 90., 0, 90);

	    type = "raster";
	    G_short_history(params->slope, type, &hist1);
	    if (params->elev != NULL)
		sprintf(hist1.edhist[0], "The elevation map is %s",
			params->elev);

	    sprintf(hist1.datsrc_1, "raster map %s", input);
	    hist1.edlinecnt = 1;

	    G_write_history(params->slope, &hist1);
	}

	/* colortable for aspect */
	G_init_colors(&colors);
	G_add_color_rule(0, 255, 255, 255, 0, 255, 255, 255, &colors);
	G_add_color_rule(1, 255, 255, 0, 90, 0, 255, 0, &colors);
	G_add_color_rule(90, 0, 255, 0, 180, 0, 255, 255, &colors);
	G_add_color_rule(180, 0, 255, 255, 270, 255, 0, 0, &colors);
	G_add_color_rule(270, 255, 0, 0, 360, 255, 255, 0, &colors);

	if (params->aspect != NULL) {
	    maps = NULL;
	    maps = G_find_file("cell", params->aspect, "");
	    if (maps == NULL) {
		fprintf(stderr, "file [%s] not found\n", params->aspect);
		return -1;
	    }
	    G_write_colors(params->aspect, maps, &colors);
	    G_quantize_fp_map_range(params->aspect, mapset, 0., 360., 0, 360);

	    type = "raster";
	    G_short_history(params->aspect, type, &hist2);
	    if (params->elev != NULL)
		sprintf(hist2.edhist[0], "The elevation map is %s",
			params->elev);

	    sprintf(hist2.datsrc_1, "raster map %s", input);
	    hist2.edlinecnt = 1;

	    G_write_history(params->aspect, &hist2);
	}

	/* colortable for curvatures */
	if (cond2) {
	    G_init_colors(&colors);

	    dat1 = (FCELL) amin1(c1min, c2min);
	    dat2 = (FCELL) - 0.01;

	    G_add_f_raster_color_rule(&dat1, 50, 0, 155,
				      &dat2, 0, 0, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) - 0.001;
	    G_add_f_raster_color_rule(&dat1, 0, 0, 255,
				      &dat2, 0, 127, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) - 0.00001;
	    G_add_f_raster_color_rule(&dat1, 0, 127, 255,
				      &dat2, 0, 255, 255, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.00;
	    G_add_f_raster_color_rule(&dat1, 0, 255, 255,
				      &dat2, 200, 255, 200, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.00001;
	    G_add_f_raster_color_rule(&dat1, 200, 255, 200,
				      &dat2, 255, 255, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.001;
	    G_add_f_raster_color_rule(&dat1, 255, 255, 0,
				      &dat2, 255, 127, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) 0.01;
	    G_add_f_raster_color_rule(&dat1, 255, 127, 0,
				      &dat2, 255, 0, 0, &colors);
	    dat1 = dat2;
	    dat2 = (FCELL) amax1(c1max, c2max);
	    G_add_f_raster_color_rule(&dat1, 255, 0, 0,
				      &dat2, 155, 0, 20, &colors);
	    maps = NULL;
	    if (params->pcurv != NULL) {
		maps = G_find_file("cell", params->pcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->pcurv);
		    return -1;
		}
		G_write_colors(params->pcurv, maps, &colors);

		fprintf(stderr, "color map written\n");

		G_quantize_fp_map_range(params->pcurv, mapset,
					dat1, dat2,
					(CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));
		type = "raster";
		G_short_history(params->pcurv, type, &hist3);
		if (params->elev != NULL)
		    sprintf(hist3.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist3.datsrc_1, "raster map %s", input);
		hist3.edlinecnt = 1;

		G_write_history(params->pcurv, &hist3);
	    }

	    if (params->tcurv != NULL) {
		maps = NULL;
		maps = G_find_file("cell", params->tcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->tcurv);
		    return -1;
		}
		G_write_colors(params->tcurv, maps, &colors);
		G_quantize_fp_map_range(params->tcurv, mapset,
					dat1, dat2, (CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));

		type = "raster";
		G_short_history(params->tcurv, type, &hist4);
		if (params->elev != NULL)
		    sprintf(hist4.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist4.datsrc_1, "raster map %s", input);
		hist4.edlinecnt = 1;

		G_write_history(params->tcurv, &hist4);
	    }

	    if (params->mcurv != NULL) {
		maps = NULL;
		maps = G_find_file("cell", params->mcurv, "");
		if (maps == NULL) {
		    fprintf(stderr, "file [%s] not found\n", params->mcurv);
		    return -1;
		}
		G_write_colors(params->mcurv, maps, &colors);
		G_quantize_fp_map_range(params->mcurv, mapset,
					dat1, dat2,
					(CELL) (dat1 * MULT),
					(CELL) (dat2 * MULT));

		type = "raster";
		G_short_history(params->mcurv, type, &hist5);
		if (params->elev != NULL)
		    sprintf(hist5.edhist[0], "The elevation map is %s",
			    params->elev);

		sprintf(hist5.datsrc_1, "raster map %s", input);
		hist5.edlinecnt = 1;

		G_write_history(params->mcurv, &hist5);
	    }
	}
    }

    if (params->elev != NULL) {
	maps = G_find_file("cell", params->elev, "");
	if (maps == NULL) {
	    fprintf(stderr, "file [%s] not found \n", params->elev);
	    return -1;
	}
	G_short_history(params->elev, "raster", &hist);

	if (smooth != NULL)
	    sprintf(hist.edhist[0], "tension=%f, smoothing=%s",
		    params->fi * 1000. / (*dnorm), smooth);
	else
	    sprintf(hist.edhist[0], "tension=%f",
		    params->fi * 1000. / (*dnorm));
	sprintf(hist.edhist[1], "dnorm=%f, zmult=%f", *dnorm, params->zmult);
	sprintf(hist.edhist[2], "KMAX=%d, KMIN=%d, errtotal=%f", params->kmax,
		params->kmin, sqrt(ertot / n_points));
	sprintf(hist.edhist[3], "zmin_data=%f, zmax_data=%f", zmin, zmax);
	sprintf(hist.edhist[4], "zmin_int=%f, zmax_int=%f", zminac, zmaxac);

	sprintf(hist.datsrc_1, "raster map %s", input);

	hist.edlinecnt = 5;

	G_write_history(params->elev, &hist);
    }

    /* change region to initial region */
    fprintf(stderr, "Changing the region back to initial...\n");
    if (G_set_window(winhd) < 0) {
	fprintf(stderr, "Cannot set region to back to initial region!\n");
	return -1;
    }

    return 1;
}