Example #1
0
/* checks if user-supplied parameters are valid */
int
check_parms (char *map_answer, char *input_answer, char *output_answer, int all )
{

	if ( map_answer != NULL ) {
		if ((G_find_file ("fcell", map_answer, "") == NULL)
	    	&& (G_find_file ("dcell", map_answer, "") == NULL)
	    	&& (G_find_file ("cell", map_answer, "") == NULL))	
		{
			/* no coverage map found */
			G_fatal_error
				("No raster map exists with the given name.");
		}
		
		/* specifying all means to disregard the map! */
		if ( all == 1 ) {
			G_warning ("Map was specified, but the -a flag disregards map values!\n Your results might not be what you expect.");
		}
	}

	/* check if sample sites exist */
	if (G_find_file ("vector", input_answer, "") == NULL)
	{
		G_fatal_error
			("No sample/sites list exists with the given name!");
	}	

	/* check if a legal file name was given for output map
	   this just overwrites existing sites */ 
	if (G_legal_filename (output_answer) == -1)
	{
		G_fatal_error
			("Name chosen for result map is not a valid file name!");
	}
		
	/* return raster mode to caller */
	if ( map_answer != NULL ) {
		return (G_raster_map_type (map_answer,""));
	}
	else return (-1);
}
Example #2
0
int G_write_quant(const char *name, const char *mapset,
		  const struct Quant *quant)
{
    CELL cell_min, cell_max;
    DCELL d_min, d_max;
    char buf[300];

    if (G_raster_map_type(name, mapset) == CELL_TYPE) {
	sprintf(buf, _("Cannot write quant rules: map %s is integer"), name);
	G_warning(buf);
	return -1;
    }

    G_quant_get_limits(quant, &d_min, &d_max, &cell_min, &cell_max);

    /* first actually write the rules */
    if (G__quant_export(name, mapset, quant) < 0) {
	sprintf(buf, _("Cannot write quant rules for map %s"), name);
	G_warning(buf);
	return -1;
    }

    return 1;
}
Example #3
0
int main( int argc, char **argv )
{
  struct GModule *module;
  struct Option *info_opt, *rast_opt, *vect_opt, *coor_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,query";

  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;

  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" );
    }
  }
  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;
      G_get_cellhd( rast_opt->answer, "", &window );
      G_set_window( &window );
      fd = G_open_cell_old( rast_opt->answer, "" );
      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:null\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 );
        }
      }
      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }

  exit( EXIT_SUCCESS );
}
Example #4
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;
}
Example #5
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 );
}
Example #6
0
int main( int argc, char **argv )
{
  char *mapset;
  char *name;
  struct GModule *module;
  struct Option *map;
  struct Option *win;
  struct Option *format;
  struct Cell_head window;
  RASTER_MAP_TYPE raster_type;

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

  module = G_define_module();
  module->keywords = ( "display, raster" );
  module->description = ( "Output raster map layers in a format suitable for display in QGIS" );

  map = G_define_standard_option( G_OPT_R_MAP );
  map->description = ( "Raster map to be displayed" );

  format = G_define_option();
  format->key = "format";
  format->type = TYPE_STRING;
  format->description = "format";
  format->options = "color,value";

  win = G_define_option();
  win->key = "window";
  win->type = TYPE_DOUBLE;
  win->multiple = YES;
  win->description = "xmin,ymin,xmax,ymax,ncols,nrows";

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

  name = map->answer;

  /* Make sure map is available */
  mapset = G_find_cell2( name, "" );
  if ( mapset == NULL )
    G_fatal_error(( "Raster map <%s> not found" ), name );

  /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and
   * cellhd, and G_open_cell_old fails, so it is better to read window from map */
  /* G_get_window( &window ); */
  G_get_cellhd( name, mapset, &window );
  window.west = atof( win->answers[0] );
  window.south = atof( win->answers[1] );
  window.east = atof( win->answers[2] );
  window.north = atof( win->answers[3] );
  window.cols = atoi( win->answers[4] );
  window.rows = atoi( win->answers[5] );
  G_adjust_Cell_head( &window, 1, 1 );
  G_set_window( &window );

  raster_type = G_raster_map_type( name, "" );

  display( name, mapset, raster_type, format->answer );

  exit( EXIT_SUCCESS );
}
Example #7
0
void cell_clip_drv(int col0, int row0, int ncols, int nrows, double **value,
		   int index, int cntwhole, float radius)
{

    register int i, j;
    int cnt = 0, p;
    double *rich, *richtmp;
    char *name, *mapset;
    DCELL **buf;
    DCELL **null_buf;
    RASTER_MAP_TYPE data_type;

    /*
       col0 = starting column for area to be clipped
       row0 = starting row for area to be clipped
       ncols = number of columns in area to be clipped
       nrows = number of rows in area to be clipped
       value =
       index = number of the region to be clipped, if there's a region map
       buf = pointer to array containing the clipped area, a smaller area
       than the original raster map to be read from finput                            printf("h2\n");

       pat = pointer to array containing the map of patch numbers
       cor = pointer to array containing the map of interior area
     */

    name = choice->fn;
    mapset = G_mapset();
    data_type = G_raster_map_type(name, mapset);

    /* dynamically allocate storage for the
       buffer that will hold the contents of
       the window */

    buf = (DCELL **) G_calloc(nrows + 3, sizeof(DCELL *));
    for (i = 0; i < nrows + 3; i++) {
	buf[i] = (DCELL *) G_calloc(ncols + 3, sizeof(DCELL));
    }

    /* dynamically allocate storage for the
       buffer that will hold the null values for
       the clipped area */

    null_buf = (DCELL **) G_calloc(nrows + 3, sizeof(DCELL *));
    for (i = 0; i < nrows + 3; i++)
	null_buf[i] = (DCELL *) G_calloc(ncols + 3, sizeof(DCELL));

    /* call the cell_clip routine */

    cell_clip(buf, null_buf, row0, col0, nrows, ncols, index, radius);

    /* dynamically allocate memory for
       the richness array */

    richtmp = (double *)G_calloc(MAX, sizeof(double));

    /* go through the sampling area
       pixel by pixel */

    for (i = 1; i < nrows + 1; i++) {
	for (j = 1; j < ncols + 1; j++) {

	    /* if buf[i][j] is not a null value,
	       call get_rich to tally up the
	       number of different attributes
	       in the sampling area and fill
	       the richness array with those
	       attributes */

	    if ((buf[i][j] || buf[i][j] == 0.0) && null_buf[i][j] == 0.0) {
		/*printf("buf[%d][%d] = %f\n",i,j,buf[i][j]); */

		get_rich(buf[i][j], richtmp, &cnt);
	    }
	}
    }

    if (cnt) {

	rich = (double *)G_calloc(cnt, sizeof(double));
	for (i = 0; i < cnt; i++) {
	    rich[i] = richtmp[i];
	}
	G_free(richtmp);

	/* call ANSI C runtime library
	   function qsort to sort the 
	   richness array into ascending
	   order */

	qsort(rich, cnt, sizeof(double), compar);

	/* moving window */

	if (choice->wrum == 'm') {
	    if (is_not_empty_buffer(buf, null_buf, nrows + 1, ncols + 1)) {
		if (center_is_not_null(buf, null_buf, nrows, ncols))
		    mv_texture(nrows, ncols, buf, null_buf, value, index,
			       rich, cnt, cntwhole);
		else {
		    for (p = 0; p < 17; p++)
			*(*(value + index) + p) = -BIG;
		}
	    }
	}

	/* whole map, units, or regions */

	else if (is_not_empty_buffer(buf, null_buf, nrows + 1, ncols + 1))
	    df_texture(nrows, ncols, buf, null_buf, rich, cnt, cntwhole);

	for (i = 0; i < nrows + 3; i++)
	    G_free(*(buf + i));
	G_free(buf);

	/* free memory allocated for null buffer */

	for (i = 0; i < nrows + 3; i++)
	    G_free(null_buf[i]);
	G_free(null_buf);

	G_free(rich);
    }
    else
	G_free(richtmp);

    return;
}
Example #8
0
void cell_clip(DCELL ** buf, DCELL ** null_buf, int row0, int col0, int nrows,
	       int ncols, int index, float radius)
{
    CELL *tmp, *tmp1;
    FCELL *ftmp;
    DCELL *dtmp;
    char *tmpname, *nulltmp;
    int fr;
    register int i, j;
    double center_row = 0.0, center_col = 0.0;
    double dist;
    RASTER_MAP_TYPE data_type;

    /*
       Variables:
       IN:
       buf        = pointer to array containing only the pixels inside the area 
       that was specified to be clipped, so a smaller array than the
       original raster map
       null_buf   = pointer to array containing the corresponding null values
       row0       = starting row for the area to be clipped out of the raster map
       col0       = starting col for the area to be clipped out of the raster map
       nrows      = total number of rows in the area to be clipped
       ncols      = total number of cols in the area to be clipped
       index      = number of the region to be clipped, if there's a region map
       INTERNAL:
       tmp        = pointer to a temporary array to store a row of the raster map
       tmp1       = pointer to a temporary array to store a row of the region map
       fr         = return value from attempting to open the region map
       i, j       = indices to rows and cols of the arrays
     */

    data_type = G_raster_map_type(choice->fn, G_mapset());

    /* if sampling by region was chosen, check
       for the region map and make sure it is
       an integer (CELL_TYPE) map */

    if (choice->wrum == 'r') {
	if (0 > (fr = G_open_cell_old(choice->reg, G_mapset()))) {
	    fprintf(stderr, "\n");
	    fprintf(stderr,
		    "   *******************************************************\n");
	    fprintf(stderr,
		    "    You specified sam=r to request sampling by region,    \n");
	    fprintf(stderr,
		    "    but the region map specified with the 'reg=' parameter\n");
	    fprintf(stderr,
		    "    cannot be found in the current mapset.                \n");
	    fprintf(stderr,
		    "   *******************************************************\n");
	    exit(1);
	}
	if (G_raster_map_type(choice->reg, G_mapset()) > 0) {
	    fprintf(stderr, "\n");
	    fprintf(stderr,
		    "   *******************************************************\n");
	    fprintf(stderr,
		    "    You specified sam=r to request sampling by region,    \n");
	    fprintf(stderr,
		    "    but the region map specified with the 'reg=' parameter\n");
	    fprintf(stderr,
		    "    must be an integer map, and it is floating point or   \n");
	    fprintf(stderr,
		    "    double instead.                                       \n");
	    fprintf(stderr,
		    "   *******************************************************\n");
	    exit(1);
	}
	tmp1 = G_allocate_raster_buf(CELL_TYPE);
	G_zero_raster_buf(tmp1, CELL_TYPE);
	fprintf(stderr, "Analyzing region number %d...\n", index);
    }

    /* allocate memory to store a row of the
       raster map, depending on the type of
       input raster map; keep track of the
       name of the buffer for each raster type */

    switch (data_type) {
    case CELL_TYPE:
	tmp = G_allocate_raster_buf(CELL_TYPE);
	tmpname = "tmp";
	break;
    case FCELL_TYPE:
	ftmp = G_allocate_raster_buf(FCELL_TYPE);
	tmpname = "ftmp";
	break;
    case DCELL_TYPE:
	dtmp = G_allocate_raster_buf(DCELL_TYPE);
	tmpname = "dtmp";
	break;
    }

    /* allocate memory to store a row of the
       null values corresponding to the raster
       map */

    nulltmp = G_allocate_null_buf();

    /* if circles are used for sampling, then
       calculate the center of the area to be
       clipped, in pixels */

    if ((int)radius) {
	center_row = ((double)row0 + ((double)nrows - 1) / 2);
	center_col = ((double)col0 + ((double)ncols - 1) / 2);
    }

    /* for each row of the area to be clipped */

    for (i = row0; i < row0 + nrows; i++) {

	/* if region, read in the corresponding
	   map row in the region file */

	if (choice->wrum == 'r')
	    G_get_raster_row_nomask(fr, tmp1, i, CELL_TYPE);

	/* initialize each element of the
	   row buffer to 0; this row buffer
	   will hold one row of the clipped
	   raster map.  Then read row i of the
	   map and the corresponding null values
	   into tmp and nulltmp buffers */

	switch (data_type) {
	case CELL_TYPE:
	    G_zero_raster_buf(tmp, data_type);
	    G_get_raster_row(finput, tmp, i, CELL_TYPE);
	    break;
	case FCELL_TYPE:
	    G_zero_raster_buf(ftmp, data_type);
	    G_get_raster_row(finput, ftmp, i, FCELL_TYPE);
	    break;
	case DCELL_TYPE:
	    G_zero_raster_buf(dtmp, data_type);
	    G_get_raster_row(finput, dtmp, i, DCELL_TYPE);
	    break;
	}

	G_get_null_value_row(finput, nulltmp, i);

	/* for all the columns one by one */

	for (j = col0; j < col0 + ncols; j++) {

	    /* if circles are used for sampling */

	    if ((int)radius) {
		dist = sqrt(((double)i - center_row) *
			    ((double)i - center_row) +
			    ((double)j - center_col) *
			    ((double)j - center_col));

		/* copy the contents of tmp into the
		   appropriate cell in buf */

		if (dist < radius) {
		    switch (data_type) {
		    case CELL_TYPE:
			*(*(buf + i + 1 - row0) + j + 1 - col0) = *(tmp + j);
			break;
		    case FCELL_TYPE:
			*(*(buf + i + 1 - row0) + j + 1 - col0) = *(ftmp + j);
			break;
		    case DCELL_TYPE:
			*(*(buf + i + 1 - row0) + j + 1 - col0) = *(dtmp + j);
			break;
		    }
		    *(*(null_buf + i + 1 - row0) + j + 1 - col0) =
			*(nulltmp + j);
		}
	    }

	    /* if circles are not used and
	       if the choice is not "by region" or
	       if this column is in region "index" */

	    else if (choice->wrum != 'r' || *(tmp1 + j) == index) {

		/* copy the contents of the correct tmp
		   into the appropriate cell in the buf
		   and the corresponding null values into
		   the appropriate cell in null_buf */

		switch (data_type) {
		case CELL_TYPE:
		    *(*(buf + i + 1 - row0) + j + 1 - col0) = *(tmp + j);
		    break;
		case FCELL_TYPE:
		    *(*(buf + i + 1 - row0) + j + 1 - col0) = *(ftmp + j);
		    break;
		case DCELL_TYPE:
		    *(*(buf + i + 1 - row0) + j + 1 - col0) = *(dtmp + j);
		    break;
		}
		*(*(null_buf + i + 1 - row0) + j + 1 - col0) = *(nulltmp + j);
	    }
	}
    }

    switch (data_type) {
    case CELL_TYPE:
	G_free(tmp);
	break;
    case FCELL_TYPE:
	G_free(ftmp);
	break;
    case DCELL_TYPE:
	G_free(dtmp);
	break;
    }
    if (choice->wrum == 'r') {
	G_free(tmp1);
	G_close_cell(fr);
    }
    G_free(nulltmp);
    return;
}
Example #9
0
int main(int argc, char *argv[])
{
    char *name, *mapset;
    char rname[GNAME_MAX], rmapset[GMAPSET_MAX];
    char path[GPATH_MAX];
    int row, col, null_fd;
    unsigned char *null_bits;
    RASTER_MAP_TYPE map_type;
    int change_null = 0, create, remove, only_int, only_fp, only_null;
    int is_reclass;

    struct GModule *module;
    struct
    {
	struct Option *map;
	struct Option *setnull;
	struct Option *null;
    } parms;
    struct
    {
	struct Flag *f;
	struct Flag *n;
	struct Flag *i;
	struct Flag *c;
	struct Flag *r;
    } flags;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, null data");
    module->description = _("Manages NULL-values of given raster map.");

    parms.map = G_define_standard_option(G_OPT_R_MAP);
    parms.map->description = _("Name of raster map for which to edit null file");

    parms.setnull = G_define_option();
    parms.setnull->key = "setnull";
    parms.setnull->key_desc = "val[-val]";
    parms.setnull->type = TYPE_STRING;
    parms.setnull->required = NO;
    parms.setnull->multiple = YES;
    parms.setnull->description = _("List of cell values to be set to NULL");
    parms.setnull->guisection = _("Modify");
 
    parms.null = G_define_option();
    parms.null->key = "null";
    parms.null->type = TYPE_DOUBLE;
    parms.null->required = NO;
    parms.null->multiple = NO;
    parms.null->description = _("The value to replace the null value by");
    parms.null->guisection = _("Modify");

    flags.f = G_define_flag();
    flags.f->key = 'f';
    flags.f->description = _("Only do the work if the map is floating-point");
    flags.f->guisection = _("Check");

    flags.i = G_define_flag();
    flags.i->key = 'i';
    flags.i->description = _("Only do the work if the map is integer");
    flags.i->guisection = _("Check");

    flags.n = G_define_flag();
    flags.n->key = 'n';
    flags.n->description =
	_("Only do the work if the map doesn't have a NULL-value bitmap file");
    flags.n->guisection = _("Check");

    flags.c = G_define_flag();
    flags.c->key = 'c';
    flags.c->description =
	_("Create NULL-value bitmap file validating all data cells");

    flags.r = G_define_flag();
    flags.r->key = 'r';
    flags.r->description = _("Remove NULL-value bitmap file");
    flags.r->guisection = _("Remove");

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

    only_int = flags.i->answer;
    only_fp = flags.f->answer;
    only_null = flags.n->answer;
    create = flags.c->answer;
    remove = flags.r->answer;

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

    is_reclass = (G_is_reclass(name, mapset, rname, rmapset) > 0);
    if (is_reclass)
	G_fatal_error(_("Raster map <%s> is a reclass of map <%s@%s>. "
			"Consider to generate a copy with r.mapcalc. Exiting."),
		      name, rname, rmapset);


    if (strcmp(mapset, G_mapset()) != 0)
	G_fatal_error(_("Raster map <%s> is not in your mapset <%s>"),
		      name, G_mapset());
    
    if (parms.null->answer) {
	if (sscanf(parms.null->answer, "%lf", &new_null) == 1)
	    change_null = 1;
	else
	    G_fatal_error(_("%s is illegal entry for null"),
			  parms.null->answer);
    }

    map_type = G_raster_map_type(name, mapset);

    if (only_null && G_find_file_misc("cell_misc", "null", name, mapset))
	G_fatal_error(_("Raster map <%s> already has a null bitmap file"), name);

    if (map_type == CELL_TYPE) {
	if (only_fp)
	    G_fatal_error(_("<%s> is integer raster map (CELL)"),
			  name);

	if ((double)((int)new_null) != new_null) {
	    G_warning(_("<%s> is integer raster map (CELL). Using null=%d."),
		      name, (int)new_null);
	    new_null = (double)((int)new_null);
	}
    }
    else if (only_int)
	G_fatal_error(_("<%s> is floating pointing raster map"),
		      name);

    parse_vallist(parms.setnull->answers, &d_mask);

    if (G_get_cellhd(name, mapset, &cellhd) < 0)
	G_fatal_error(_("Unable to read header of raster map <%s>"),
		      G_fully_qualified_name(name, mapset));

    if (create) {
	/* write a file of no-nulls */
	null_bits = (unsigned char *)G__allocate_null_bits(cellhd.cols);
	/* init all cells to 0's */
	for (col = 0; col < G__null_bitstream_size(cellhd.cols); col++)
	    null_bits[col] = 0;

	null_fd = G_open_new_misc("cell_misc", "null", name);

	G_verbose_message(_("Writing new null file for raster map <%s>..."),
			  name);

	for (row = 0; row < cellhd.rows; row++) {
	    G_percent(row, cellhd.rows, 1);
	    if (G__write_null_bits(null_fd, null_bits, row, cellhd.cols, 0) <
		0)
		G_fatal_error(_("Error writing null row %d"), row);
	}
	G_percent(row, cellhd.rows, 1);
	close(null_fd);

	G_done_msg(_("Raster map <%s> modified."), name);

	exit(EXIT_SUCCESS);
    }

    if (remove) {
	/* write a file of no-nulls */
	G_verbose_message(_("Removing null file for raster map <%s>..."),
			   name);
	null_fd = G_open_new_misc("cell_misc", "null", name);
	G__file_name_misc(path, "cell_misc", "null", name, mapset);
	unlink(path);

	G_done_msg(_("Raster map <%s> modified."), name);

	exit(EXIT_SUCCESS);
    }

    process(name, mapset, change_null, map_type);

    exit(EXIT_SUCCESS);
}
Example #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 );
    }
}
Example #11
0
void* raster2array(const char* name, struct Cell_head* header, int* rows,
		int* cols, RASTER_MAP_TYPE out_type) {
	// Open the raster map and load the dem
	// for simplicity sake, the dem will be an array of
	// doubles, converted from any possible GRASS CELL type.
	char* mapset = G_find_cell2(name, "");
	if (mapset == NULL)
		G_fatal_error("Raster map <%s> not found", name);

	// Find out the cell type of the DEM
	RASTER_MAP_TYPE type = G_raster_map_type(name, mapset);

	// Get a file descriptor for the DEM raster map
	int infd;
	if ((infd = G_open_cell_old(name, mapset)) < 0)
		G_fatal_error("Unable to open raster map <%s>", name);

	// Get header info for the DEM raster map
	struct Cell_head cellhd;
	if (G_get_cellhd(name, mapset, &cellhd) < 0)
		G_fatal_error("Unable to open raster map <%s>", name);

	// Create a GRASS buffer for the DEM raster
	void* inrast = G_allocate_raster_buf(type);

	// Get the max rows and max cols from the window information, since the 
	// header gives the values for the full raster
	const int maxr = G_window_rows();
	const int maxc = G_window_cols();

	// Read in the raster line by line, copying it into the double array
	// rast for return.
	void* rast;
	switch (out_type) {
	case CELL_TYPE:
		rast = (int*) calloc(maxr * maxc, sizeof(int));
		break;
	case FCELL_TYPE:
		rast = (float*) calloc(maxr * maxc, sizeof(float));
		break;
	case DCELL_TYPE:
		rast = (double*) calloc(maxr * maxc, sizeof(double));
		break;

	}

	if (rast == NULL) {
		G_fatal_error("Unable to allocate memory for raster map <%s>", name);
	}

	int row, col;
	for (row = 0; row < maxr; ++row) {
		if (G_get_raster_row(infd, inrast, row, type) < 0)
			G_fatal_error("Unable to read raster map <%s> row %d", name, row);

		for (col = 0; col < maxc; ++col) {
			int index = col + row * maxc;

			if (out_type == CELL_TYPE) {
				switch (type) {
				case CELL_TYPE:
					((int*) rast)[index] = ((int *) inrast)[col];
					break;
				case FCELL_TYPE:
					((int*) rast)[index] = (int) ((float *) inrast)[col];
					break;
				case DCELL_TYPE:
					((int*) rast)[index] = (int) ((double *) inrast)[col];
					break;
				default:
					G_fatal_error("Unknown cell type");
					break;
				}
			}

			if (out_type == FCELL_TYPE) {
				switch (type) {
				case CELL_TYPE:
					((float*) rast)[index] = (float) ((int *) inrast)[col];
					break;
				case FCELL_TYPE:
					((float*) rast)[index] = ((float *) inrast)[col];
					break;
				case DCELL_TYPE:
					((float*) rast)[index] = (float) ((double *) inrast)[col];
					break;
				default:
					G_fatal_error("Unknown cell type");
					break;
				}
			}

			if (out_type == DCELL_TYPE) {
				switch (type) {
				case CELL_TYPE:
					((double*) rast)[index] = (double) ((int *) inrast)[col];
					break;
				case FCELL_TYPE:
					((double*) rast)[index] = (double) ((float *) inrast)[col];
					break;
				case DCELL_TYPE:
					((double*) rast)[index] = ((double *) inrast)[col];
					break;
				default:
					G_fatal_error("Unknown cell type");
					break;
				}
			}
		}
	}

	// Return cellhd, maxr, and maxc by pointer
	if (header != NULL)
		*header = cellhd;
	if (rows != NULL)
		*rows = maxr;
	if (cols != NULL)
		*cols = maxc;

	return rast;
}
Example #12
0
int main(int argc, char *argv[])
{
	struct Cell_head cellhd; 
        struct Range range;
        char *name;                     /* input raster name */
	char *result;                   /* output raster name */
        char *mapset;                   /* mapset name */
	DCELL *inrast;                  /* input buffer */
	DCELL *outrast;                 /* output buffer */
	int row,col;
	int infd, outfd;                /* file descriptor */
	int verbose;
        double *weights;                /* array of weights */
        DCELL **D_rows;
        DCELL *tmp;
        int nrows;                      
        int ncols;
        double min, max;                /* raster map range */
        
	RASTER_MAP_TYPE data_type;      /* type of the map */
        void *values;                   /* neighborhood values */
        int n,i;                        /* number of neighborhood cells */
        int size;                       /* matrix size */
        double ssigma;                  /* sigma of the spatial part */
        double csigma;                  /* sigma of the color part */
        char title[1024];               /* map title */


	struct GModule *module;         /* GRASS module for parsing arguments */
	struct
	    {
		struct Option *input, *output;
		struct Option *sigma_s, *sigma_c, *size;
		struct Option *title;
	} parm;
	struct
	    {
		struct Flag *quiet;
		struct Flag *print_sigmas;
	} flag;

        /* initialize GIS environment */
	G_gisinit(argv[0]);     /* reads grass env, 
                                   stores program name to 
                                   G_program_name
                                   */

        /* initialize module */
	module = G_define_module();
	module->description = ("Gaussian filter for raster maps.");
					        
	/* Define the different options */
	parm.input = G_define_option() ;
	parm.input->key        = "input";
	parm.input->type       = TYPE_STRING;
	parm.input->required   = YES;
	parm.input->description= ("Name of an input layer" );

	parm.output = G_define_option() ;
	parm.output->key        = "output";
	parm.output->type       = TYPE_STRING;
	parm.output->required   = YES;
	parm.output->description= ("Name of an output layer");

	parm.sigma_s = G_define_option() ;
	parm.sigma_s->key        = "ssigma";
	parm.sigma_s->type       = TYPE_DOUBLE;
	parm.sigma_s->required   = NO;
	parm.sigma_s->description= ("Sigma for space part of the filter\n\t(default: 0.465*((size-1)/2)");

	parm.sigma_c = G_define_option() ;
	parm.sigma_c->key        = "csigma";
	parm.sigma_c->type       = TYPE_DOUBLE;
	parm.sigma_c->required   = NO;
	parm.sigma_c->description= ("Sigma for color part of the filter\n(default: 0.465*((color_range)/2)");

        parm.size = G_define_option() ;
	parm.size->key        = "size";
	parm.size->type       = TYPE_INTEGER;
	parm.size->required   = YES;
	parm.size->description= ("Size of the matrix (odd number)");

        flag.print_sigmas = G_define_flag() ;
	flag.print_sigmas->key         = 's' ;
	flag.print_sigmas->description = "Print calculated values for sigmas" ;
        
        flag.quiet = G_define_flag() ;
	flag.quiet->key         = 'q' ;
	flag.quiet->description = "Quiet" ;
        
        /* options and flags pareser */
	if (G_parser(argc, argv))
		exit (-1);
		
        /* stores options and flags to variables */
	name    = parm.input->answer;
	result  = parm.output->answer;
	verbose = (! flag.quiet->answer);
        sscanf(parm.size->answer, "%d", &size);
        if (!parm.sigma_s->answer)
            ssigma = 0.465*((size-1)/2);
        else 
            sscanf(parm.sigma_s->answer, "%lf", &ssigma);
      
        

        /* controlling the input values */
        if (size%2 == 0) 
            G_fatal_error("Size <%d> is not odd number", size);

	/* returs NULL if the map was not found in any mapset, 
         * mapset name otherwise*/
	mapset = G_find_cell2 (name, ""); 
        if (mapset == NULL)
                G_fatal_error ("cell file [%s] not found", name);

       /* color sigma next */
        if (!parm.sigma_c->answer) {
            if (G_read_range(name, mapset, &range) < 0) 
                G_fatal_error("Could not read the raster map range");
                
            /* for raster maps with range from 0-255 the result
             * should be around 60 
             */
            min = (double)range.min;
            max = (double)range.max;
            csigma = 0.456*(max - min)/2;
        }
        else
            sscanf(parm.sigma_c->answer, "%lf", &csigma);
        
        /* print if appropriate */
        if (flag.print_sigmas->answer)
            printf("Space sigma: %f\nColor sigma: %f\n", ssigma, csigma);

 
        if (G_legal_filename (result) < 0)
                G_fatal_error ("[%s] is an illegal name", result);

        /* count weights */
        weights = (double *)malloc(size * size * sizeof(double));
        /* stores values of gauss. bell into 'weigts'*/
        count_weights(weights, size, ssigma);
        
	/* determine the inputmap type (CELL/FCELL/DCELL) */
	data_type = G_raster_map_type(name, mapset);

        /* G_open_cell_old - returns file destriptor (>0) */
	if ( (infd = G_open_cell_old (name, mapset)) < 0)
		G_fatal_error ("Cannot open cell file [%s]", name);

        /* controlling, if we can open input raster */
	if (G_get_cellhd (name, mapset, &cellhd) < 0)
		G_fatal_error ("Cannot read file header of [%s]", name);

	/* Allocate input buffer */
	inrast = G_allocate_raster_buf(data_type);
	
	/* Allocate output buffer, use input map data_type */
	nrows = G_window_rows();
	ncols = G_window_cols();
	outrast = G_allocate_d_raster_buf();


        /* Allocate values buffers */
        values = (DCELL *) malloc(size * size * sizeof(DCELL));
        
        /* allocating memory for rows */
        D_rows = (DCELL **)malloc(size * sizeof(DCELL));
        for (i = 0; i < size; i++) {
            D_rows[i] = G_allocate_raster_buf(DCELL_TYPE);
        }
        
        if (values == NULL) 
            G_fatal_error("Cannot allocate memory");

        /* controlling, if we can write the raster */
	if ( (outfd = G_open_raster_new (result, data_type)) < 0)
		G_fatal_error ("Could not open <%s>",result);

        /* write first rows as NULL values */
        for (row = 0; row < size/2; row++) {
            G_set_d_null_value(outrast, ncols);
            if (G_put_d_raster_row (outfd, outrast) < 0)
                G_fatal_error ("Cannot write to <%s>",result);
        }

        /* allocate first size/2 rows */
        for (row = 0; row < size; row++) 
            if (G_get_d_raster_row(infd, D_rows[row], row) < 0)
		G_fatal_error ("Could not open <%s>",result);
            
        /****************************************************************/
        /* for each row inside the region */
	for ( row = size/2; row < nrows - size/2; row++) {
            

		if (verbose)
		    G_percent (row, nrows, 2);
                
                /* allocate new last row */
               G_get_d_raster_row(infd, D_rows[size-1], row+(size/2));

                /*process the data */
		for (col=0; col < ncols; col++){

                    /* skip the outside columns */
                    if ( (col - size/2) < 0 || ncols <= (col + size/2)) {
                        G_set_d_null_value(outrast, 1);
                    }
                    /* work only with columns, which are inside */
                    else {

                        /* store values of the matrix into arry 'values', 'n' is
                         * number of elements of the matrix */
                        n = D_gather(infd, values, D_rows, col, row,size);
                        ((DCELL *)outrast)[col] = D_bilateral(values, ssigma, csigma, size, weights);
		    }
                } /* for each column */

                /* write raster row to output raster file */
		G_put_d_raster_row (outfd, outrast);

                /* switch rows */
		tmp = D_rows[0];
                for (i = 0; i < size; i++){
                   D_rows[i] = D_rows[i + 1];
                }
		D_rows[size-1] = tmp;

	} /* for each row */
        
        /* write last rows as NULL values */
        for (i = 0; i < size/2; i++) {
            G_set_d_null_value(outrast, ncols);
            G_put_d_raster_row (outfd, outrast);
        }
 
        /* memory cleaning */
	G_free(outrast);
	G_free(inrast);
        G_free(values);

        for (i = 0; i < size; i++) {
            G_free(D_rows[i]);
        }
        free((void *) D_rows);


        /* closing rastr files */
	G_close_cell (infd);
	G_close_cell (outfd);

        /* set the map title */
        sprintf(title, "Bilateral filter of %s with %dx%d matrix: ssigma %.3f, csigma %.3f", name, size, size, ssigma, csigma ); 
        G_put_cell_title (result, title ); 

	return 0;
}