[GRASS-SVN] r57634 - sandbox/turek/scatter_plot

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Sep 11 00:17:16 PDT 2013


Author: turek
Date: 2013-09-11 00:17:16 -0700 (Wed, 11 Sep 2013)
New Revision: 57634

Modified:
   sandbox/turek/scatter_plot/README.txt
   sandbox/turek/scatter_plot/testing_patch.diff
Log:
scatter plot: bugs fixing, optimization

Modified: sandbox/turek/scatter_plot/README.txt
===================================================================
--- sandbox/turek/scatter_plot/README.txt	2013-09-11 02:30:24 UTC (rev 57633)
+++ sandbox/turek/scatter_plot/README.txt	2013-09-11 07:17:16 UTC (rev 57634)
@@ -17,11 +17,12 @@
 NEEDS TO BE DONE:
 
 - change layers order #DONE
-- ellipses managment
+- ellipses managment #DONE
 - flip of digitized area on scatter plot
-- synch whith digitizer
-- statusbar showing information about computations and coordinates
-- scatter plot settings
+- synch whith digitizer #DONE
+- statusbar showing information about computations and coordinates #DONE
+- scatter plot settings 
+- export raster map #DONE
 - check for range of data, if big show warning
 - better temp files clean up
 - comment code
@@ -45,7 +46,7 @@
 - Scatter plot window
   - zoom icon: also allow for zoom box #DONE
   - mouse wheel: 0.1 zoom step (not 0.5)#DONE
-  - add values to axis # it is possible but  IDEA show values in statusbar
+  - add values to axis # it is possible but  IDEA show values in statusbar #DONE implemented statusbar
   - plot legend: strip @mapset off #DONE
   - second plot is falling out of the main window to the left
 
@@ -53,8 +54,8 @@
   - rerendering zooms out, it should not #DONE
 
 - confidence ellipse
-  - connect to "xx std dev" selection in toolbar
-  - show center of ellipse as little cross
+  - connect to "xx std dev" selection in toolbar #DONE
+  - show center of ellipse as little cross #DONE
 
 Wish:
  - optionally link map displays for zoom/pan etc. (icon?)

Modified: sandbox/turek/scatter_plot/testing_patch.diff
===================================================================
--- sandbox/turek/scatter_plot/testing_patch.diff	2013-09-11 02:30:24 UTC (rev 57633)
+++ sandbox/turek/scatter_plot/testing_patch.diff	2013-09-11 07:17:16 UTC (rev 57634)
@@ -1,6 +1,1235 @@
+Index: lib/vector/Vlib/open.c
+===================================================================
+--- lib/vector/Vlib/open.c	(revision 57633)
++++ lib/vector/Vlib/open.c	(working copy)
+@@ -240,7 +240,9 @@
+         }
+         else {
+             char file_path[GPATH_MAX];
+-            
++            /* reduce to current mapset if search path was set */
++            if(strcmp(Map->mapset, "") == 0)
++                Map->mapset = G_store(G_mapset());
+             /* temporary map: reduce to current mapset if search path
+              * was set */
+             if (strcmp(Map->mapset, "") == 0)
+Index: lib/imagery/scatt.c
+===================================================================
+--- lib/imagery/scatt.c	(revision 0)
++++ lib/imagery/scatt.c	(working copy)
+@@ -0,0 +1,799 @@
++/*!
++   \file lib/imagery/scatt.c
++
++   \brief Imagery library - functions for wx Scatter Plot Tool.
++
++   Low level functions used by wx Scatter Plot Tool.
++
++   Copyright (C) 2013 by the GRASS Development Team
++
++   This program is free software under the GNU General Public License
++   (>=v2).  Read the file COPYING that comes with GRASS for details.
++
++   \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
++ */
++
++#include <grass/raster.h>
++#include <grass/imagery.h>
++#include <grass/gis.h>
++#include <grass/glocale.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <string.h>
++
++
++struct rast_row
++{
++    CELL * row;
++    char * null_row;
++    struct Range rast_range; /*Range of whole raster.*/
++};
++
++/*!
++   \brief Create pgm header.
++
++   Scatter plot internally generates pgm files. These pgms have header in format created by this function.
++    
++   \param region region to be pgm header generated for 
++   \param [out] header header of pgm file
++ */
++static int get_cat_rast_header(struct Cell_head * region, char * header){
++    return sprintf(header, "P5\n%d\n%d\n1\n", region->cols, region->rows);
++}
++
++/*!
++   \brief Create category raster conditions file.
++    
++   \param cat_rast_region region to be file generated for
++   \param cat_rast path of generated category raster file
++ */
++int I_create_cat_rast(struct Cell_head * cat_rast_region,  const char * cat_rast)
++{
++    FILE * f_cat_rast;
++    char cat_rast_header[1024];//TODO magic number 
++    int i_row, i_col;
++    int head_nchars;
++
++    unsigned char * row_data;
++
++    f_cat_rast = fopen(cat_rast, "wb");
++    if(!f_cat_rast) {
++        G_warning("Unable to create category raster condition file <%s>.", cat_rast);
++        return -1;
++    }
++
++    head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
++
++    fwrite(cat_rast_header, sizeof(char), head_nchars/sizeof(char), f_cat_rast);
++    if (ferror(f_cat_rast)){
++        fclose(f_cat_rast);
++        G_warning(_("Unable to write header into category raster condition file <%s>."), cat_rast);
++        return -1;
++    }
++
++    row_data = (unsigned char *) G_malloc(cat_rast_region->cols * sizeof(unsigned char));
++    for(i_col = 0; i_col < cat_rast_region->cols; i_col++)
++        row_data[i_col] = 0 & 255;
++
++    for(i_row = 0; i_row < cat_rast_region->rows; i_row++) {
++        fwrite(row_data, sizeof(unsigned char), (cat_rast_region->cols)/sizeof(unsigned char), f_cat_rast);
++        if (ferror(f_cat_rast))
++        {
++            fclose(f_cat_rast);
++            G_warning(_("Unable to write into category raster condition file <%s>."), cat_rast);
++            return -1;
++        }
++    }
++
++    fclose(f_cat_rast);
++    return 0;
++}
++
++static int print_reg(struct Cell_head * intersec, const char * pref, int dbg_level)
++{
++    G_debug(dbg_level, "%s:\n n:%f\ns:%f\ne:%f\nw:%f\nns_res:%f\new_res:%f", pref, intersec->north, intersec->south, 
++               intersec->east, intersec->west, intersec->ns_res, intersec->ew_res);
++}
++
++/*!
++   \brief Find intersection region of two regions.
++
++   \param A pointer to intersected region
++   \param B pointer to intersected region
++   \param [out] intersec pointer to intersection region of regions A B (relevant params of the region are: south, north, east, west)
++
++   \return  0 if interection exists
++   \return -1 if regions does not intersect
++ */
++static int regions_intersecion(struct Cell_head * A, struct Cell_head * B, struct Cell_head * intersec)
++{
++
++    if(B->north < A->south) return -1;
++    else if(B->north > A->north) intersec->north = A->north;
++    else intersec->north = B->north;
++
++    if(B->south > A->north) return -1;
++    else if(B->south < A->south) intersec->south = A->south;
++    else intersec->south = B->south;
++
++    if(B->east < A->west) return -1;
++    else if(B->east > A->east) intersec->east = A->east;
++    else intersec->east = B->east;
++
++    if(B->west > A->east) return -1;
++    else if(B->west < A->west) intersec->west = A->west;
++    else intersec->west = B->west;
++
++    if(intersec->north == intersec->south) return -1;
++
++    if(intersec->east == intersec->west) return -1;
++
++    return 0;
++
++}
++
++/*!
++   \brief Get rows and cols numbers, which defines intersection of the regions.
++  
++   \param A pointer to intersected region
++   \param B pointer to intersected region (A and B must have same resolution)
++   \param [out] A_bounds rows and cols numbers of A stored in south, north, east, west, which defines intersection of A and B
++   \param [out] B_bounds rows and cols numbers of B stored in south, north, east, west, which defines intersection of A and B
++
++   \return  0 if interection exists
++   \return -1 if regions do not intersect
++   \return -2 resolution of regions is not same 
++*/
++static int get_rows_and_cols_bounds(struct Cell_head * A,  struct Cell_head * B, struct Cell_head * A_bounds,  struct Cell_head * B_bounds)
++{
++    float ns_res, ew_res;
++
++    struct Cell_head intersec;
++
++    /* TODO is it right check? */
++    if(abs(A->ns_res - B->ns_res) > GRASS_EPSILON) {
++        G_debug(0, "'get_rows_and_cols_bounds' ns_res does not fit, A->ns_res: %f B->ns_res: %f", A->ns_res, B->ns_res);
++        return -2;
++    }
++
++    if(abs(A->ew_res - B->ew_res) > GRASS_EPSILON) {
++        G_debug(0, "'get_rows_and_cols_bounds' ew_res does not fit, A->ew_res: %f B->ew_res: %f", A->ew_res, B->ew_res);
++        return -2;
++    }
++
++    ns_res = A->ns_res;
++    ew_res = A->ew_res;
++
++    if(regions_intersecion(A, B, &intersec) == -1)
++        return -1;
++
++    A_bounds->north = ceil((A->north - intersec.north - ns_res * 0.5) / ns_res);
++    A_bounds->south = ceil((A->north - intersec.south - ns_res * 0.5) / ns_res);
++
++    A_bounds->east = ceil((intersec.east - A->west - ew_res * 0.5) / ew_res);
++    A_bounds->west = ceil((intersec.west - A->west - ew_res * 0.5) / ew_res);
++
++    B_bounds->north = ceil((B->north - intersec.north - ns_res * 0.5) / ns_res);
++    B_bounds->south = ceil((B->north - intersec.south - ns_res * 0.5) / ns_res);
++
++    B_bounds->east = ceil((intersec.east - B->west - ew_res * 0.5) / ew_res);
++    B_bounds->west = ceil((intersec.west - B->west - ew_res * 0.5) / ew_res);
++
++    return 0;
++}
++
++/*!
++   \brief Insert raster map patch into pgm file.
++  
++   \param patch_rast name of raster map
++   \param cat_rast_region region of category raster file
++   \param cat_rast path to category raster file
++
++   \return  0 on success
++   \return -1 on failure
++*/
++int I_insert_patch_to_cat_rast(const char * patch_rast, struct Cell_head * cat_rast_region,  const char * cat_rast)
++{
++
++    FILE * f_cat_rast;
++    struct Cell_head patch_region, patch_bounds, cat_rast_bounds;
++    char cat_rast_header[1024];//TODO magic number 
++    int i_row, i_col, ncols, nrows, cat_rast_col, patch_col, val;
++    int head_nchars, ret;
++    int fd_patch_rast, init_shift, step_shift;
++    unsigned char * patch_data;
++
++    char * null_chunk_row;
++
++    const char *mapset;
++
++    struct Cell_head patch_lines, cat_rast_lines;
++
++    unsigned char * row_data;
++
++    f_cat_rast = fopen(cat_rast, "rb+");
++    if(!f_cat_rast) {
++        G_warning(_("Unable to open category raster condtions file <%s>."), cat_rast);
++        return -1;
++    }
++
++    head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
++    if ((mapset = G_find_raster(patch_rast,"")) == NULL) {
++        fclose(f_cat_rast);
++        G_warning(_("Unable to find patch raster <%s>."), patch_rast);
++        return -1;
++    }
++
++    Rast_get_cellhd(patch_rast, mapset, &patch_region);
++    Rast_set_window(&patch_region);
++            
++    if ((fd_patch_rast = Rast_open_old(patch_rast, mapset)) < 0) {
++        fclose(f_cat_rast);
++        return -1;
++    }
++
++    ret = get_rows_and_cols_bounds(cat_rast_region, &patch_region, &cat_rast_bounds, &patch_bounds);
++    if(ret == -2) { 
++        G_warning(_("Resolutions of patch <%s> and patched file <%s> are not same."), patch_rast, cat_rast);
++
++        Rast_close(fd_patch_rast);
++        fclose(f_cat_rast);
++
++        return -1;
++    }
++    else if (ret == -1){
++
++        Rast_close(fd_patch_rast);
++        fclose(f_cat_rast);
++
++        return 0;
++    }
++
++    ncols = cat_rast_bounds.east - cat_rast_bounds.west;
++    nrows = cat_rast_bounds.south - cat_rast_bounds.north;
++
++    patch_data = (unsigned char *) G_malloc(ncols * sizeof(unsigned char));
++
++    init_shift = head_nchars + cat_rast_region->cols * cat_rast_bounds.north + cat_rast_bounds.west;
++
++    if(fseek(f_cat_rast, init_shift, SEEK_SET) != 0) {
++        G_warning(_("Corrupted  category raster conditions file <%s> (fseek failed)"), cat_rast);
++
++        Rast_close(fd_patch_rast);
++        G_free(null_chunk_row);
++        fclose(f_cat_rast);
++
++        return -1;
++    }
++
++    step_shift = cat_rast_region->cols - ncols;
++
++    null_chunk_row =  Rast_allocate_null_buf();
++    
++    for(i_row = 0; i_row < nrows; i_row++) {
++        Rast_get_null_value_row (fd_patch_rast, null_chunk_row, i_row + patch_bounds.north);
++
++        for(i_col = 0; i_col < ncols; i_col++) {
++            patch_col = patch_bounds.west + i_col;
++
++            if(null_chunk_row[patch_col] != 1) 
++                patch_data[i_col] = 1 & 255;
++            else {
++                patch_data[i_col] = 0 & 255;
++            }
++        }
++
++        fwrite(patch_data, sizeof(unsigned char), (ncols)/sizeof(unsigned char), f_cat_rast);
++        if (ferror(f_cat_rast))
++        {
++            G_warning(_("Unable to write into category raster conditions file <%s>"), cat_rast);
++            
++            Rast_close(fd_patch_rast);
++            G_free(null_chunk_row);
++            fclose(f_cat_rast);
++
++            return -1;
++        }
++        if(fseek(f_cat_rast, step_shift, SEEK_CUR) != 0) {
++            G_warning(_("Corrupted  category raster conditions file <%s> (fseek failed)"), cat_rast);
++            
++            Rast_close(fd_patch_rast);
++            G_free(null_chunk_row);
++            fclose(f_cat_rast);
++            
++            return -1;
++        }
++    }
++
++    Rast_close(fd_patch_rast);
++    G_free(null_chunk_row);
++    fclose(f_cat_rast);
++    return 0;
++}
++
++/*!
++   \brief Updates scatter plots data in category by pixels which meets category conditions.
++  
++   \param bands_rows data represents data describig one row from raster band
++   \param belongs_pix array which defines which pixels belongs to category (1 value) and which not (0 value)
++   \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, which are modified according to values in belongs_pix
++*/
++static inline void update_cat_scatt_plts(struct rast_row * bands_rows, unsigned short * belongs_pix, struct scScatts * scatts)
++{
++    int band_axis_1, band_axis_2, i_scatt, array_idx, cat_idx, i_chunk_rows_pix, max_arr_idx;
++
++    CELL * b_1_row;
++    CELL * b_2_row;
++    char * b_1_null_row,* b_2_null_row;
++    struct rast_row b_1_rast_row, b_2_rast_row;
++
++    struct Range b_1_range, b_2_range;
++    int b_1_range_size;
++
++    int row_size = Rast_window_cols();
++
++    int * scatts_bands = scatts->scatts_bands;
++
++    for(i_scatt = 0; i_scatt < scatts->n_a_scatts; i_scatt++)
++    {   
++        b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
++        b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
++
++        b_1_row = b_1_rast_row.row;
++        b_2_row = b_2_rast_row.row;
++
++        b_1_null_row =  b_1_rast_row.null_row;
++        b_2_null_row =  b_2_rast_row.null_row;
++
++        b_1_range = b_1_rast_row.rast_range;
++        b_2_range = b_2_rast_row.rast_range;
++        
++        b_1_range_size = b_1_range.max - b_1_range.min + 1;
++        max_arr_idx = (b_1_range.max -  b_1_range.min + 1) * (b_2_range.max -  b_2_range.min + 1);
++
++        for(i_chunk_rows_pix = 0; i_chunk_rows_pix < row_size; i_chunk_rows_pix++)
++        {
++            /* pixel does not belongs to scatter plot or has null value in one of the bands */
++            if(!belongs_pix[i_chunk_rows_pix] || 
++                b_1_null_row[i_chunk_rows_pix] == 1 || 
++                b_2_null_row[i_chunk_rows_pix] == 1)                
++                continue;
++
++            /* index in scatter plot array */
++            array_idx = b_1_row[i_chunk_rows_pix] - b_1_range.min + (b_2_row[i_chunk_rows_pix] - b_2_range.min) * b_1_range_size;
++
++            if(array_idx < 0 || array_idx >= max_arr_idx) {
++                        G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
++                continue;
++            }
++
++            /* increment scatter plot value */
++            ++scatts->scatts_arr[i_scatt]->scatt_vals_arr[array_idx];
++        }
++    }
++}
++
++/*!
++   \brief Computes scatter plots data from chunk_rows.
++
++   \param scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
++   \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are selected areas (condtitions)stored
++
++   \param chunk_rows data arrays of chunk_rows from analyzed raster bands (all data in chunk_rows, null_chunk_rows and belongs_pix arrays represents same region)
++   \param null_chunk_rows null data arrays of chunk_rows from analyzed raster bands
++   \param row_size size of data in chunk_rows, null_chunk_rows and belongs_pix arrays
++   \param f_cats_rasts_conds file which stores selected areas (conditions) from mapwindow see I_create_cat_rast() and I_pa
++   \param fd_cats_rasts array of openedraster maps which represents all selected pixels for category
++   \param region analysis region
++
++   \return  0 on success
++   \return -1 on failure
++*/
++static inline int compute_scatts_from_chunk_row(struct Cell_head *region, struct scCats * scatt_conds, 
++                                                FILE ** f_cats_rasts_conds, struct rast_row * bands_rows, 
++                                                struct scCats * scatts, int * fd_cats_rasts)
++{
++
++    int i_rows_pix, i_cat, i_scatt, n_a_scatts, n_pixs;
++    int cat_id, scatt_plts_cat_idx, array_idx, max_arr_idx;
++    char * b_1_null_row,* b_2_null_row;
++    struct rast_row b_1_rast_row, b_2_rast_row;
++    CELL * cat_rast_row;
++
++    struct scScatts * scatts_conds;
++    struct scScatts * scatts_scatt_plts;
++    struct scdScattData * conds;
++
++    struct Range b_1_range, b_2_range;
++    int b_1_range_size;
++
++    int * scatts_bands;
++    struct scdScattData ** scatts_arr;
++
++    CELL * b_1_row;
++    CELL * b_2_row;
++    unsigned char * i_scatt_conds;
++
++    int row_size = Rast_window_cols();
++
++    unsigned short * belongs_pix = (unsigned short *) G_malloc(row_size * sizeof(unsigned short)); 
++    unsigned char * rast_pixs = (unsigned char *) G_malloc(row_size * sizeof(unsigned char));
++    cat_rast_row =  Rast_allocate_c_buf();
++
++     
++    for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
++    {
++        scatts_conds = scatt_conds->cats_arr[i_cat];
++
++        cat_id = scatt_conds->cats_ids[i_cat];
++
++        scatt_plts_cat_idx = scatts->cats_idxs[cat_id];
++        if(scatt_plts_cat_idx < 0)
++            continue;
++        scatts_scatt_plts = scatts->cats_arr[scatt_plts_cat_idx];
++
++        G_zero(belongs_pix, row_size * sizeof(unsigned short));
++
++        /* if category has no conditions defined, scatter plots without any constraint are computed (default scatter plots) */
++        if(!scatts_conds->n_a_scatts && !f_cats_rasts_conds[i_cat]) {
++            for(i_scatt = 0; i_scatt < scatts_scatt_plts->n_a_scatts; i_scatt++)
++            {       
++                /* all pixels belongs */
++                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)                
++                    belongs_pix[i_rows_pix] = 1;
++            }
++        }
++        /* compute belonging pixels for defined conditions */
++        else
++        {
++            scatts_bands = scatts_conds->scatts_bands;
++
++            /* check conditions from category raster condtitions file */
++            if(f_cats_rasts_conds[i_cat]) {
++                n_pixs = fread(rast_pixs, sizeof(unsigned char), (row_size)/sizeof(unsigned char), f_cats_rasts_conds[i_cat]);
++
++                if (ferror(f_cats_rasts_conds[i_cat]))
++                {
++                    G_free(rast_pixs);
++                    G_free(belongs_pix);
++                    G_warning(_("Unable to read from category raster condtition file."));
++                    return -1;
++                }
++                if (n_pixs != n_pixs) {
++                    G_free(rast_pixs);
++                    G_free(belongs_pix);
++                    G_warning(_("Invalid size of category raster conditions file."));
++                    return -1;
++
++                }
++
++                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++                {
++                    if(rast_pixs[i_rows_pix] != 0 & 255)
++                        belongs_pix[i_rows_pix] = 1;
++                }
++            }
++
++            /* check condtions defined in scatter plots*/
++            for(i_scatt = 0; i_scatt < scatts_conds->n_a_scatts; i_scatt++)
++            {   
++                b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
++                b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
++
++                b_1_row = b_1_rast_row.row;
++                b_2_row = b_2_rast_row.row;
++
++                b_1_null_row =  b_1_rast_row.null_row;
++                b_2_null_row =  b_2_rast_row.null_row;
++
++                b_1_range = b_1_rast_row.rast_range;
++                b_2_range = b_2_rast_row.rast_range;
++
++                b_1_range_size = b_1_range.max - b_1_range.min + 1;
++                max_arr_idx = (b_1_range.max -  b_1_range.min + 1) * (b_2_range.max -  b_2_range.min + 1);
++
++                i_scatt_conds = scatts_conds->scatts_arr[i_scatt]->b_conds_arr;
++
++                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++                {
++                    /* pixels already belongs to category from category raster conditions file or contains null value in one of the bands */
++                    if(belongs_pix[i_rows_pix] || 
++                       b_1_null_row[i_rows_pix] == 1 || 
++                       b_2_null_row[i_rows_pix] == 1)
++                        continue;
++
++                    array_idx = b_1_row[i_rows_pix] - b_1_range.min + (b_2_row[i_rows_pix] - b_2_range.min) * b_1_range_size;
++                    if(array_idx < 0 || array_idx >= max_arr_idx) {
++                        G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
++                        continue;
++                    }
++                    /* pixels meets condtion defined in scatter plot */
++                    if(i_scatt_conds[array_idx])
++                        belongs_pix[i_rows_pix] = 1;
++                }                
++            }
++        }
++
++        /* update category raster with belonging pixels */
++        if(fd_cats_rasts[i_cat] >= 0) {
++            Rast_set_null_value(cat_rast_row, Rast_window_cols(), CELL_TYPE); 
++
++            for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++                if(belongs_pix[i_rows_pix])
++                    cat_rast_row[i_rows_pix] = belongs_pix[i_rows_pix];
++
++            Rast_put_c_row (fd_cats_rasts[i_cat], cat_rast_row); 
++        }
++
++        /* update scatter plots with belonging pixels */
++        update_cat_scatt_plts(bands_rows, belongs_pix, scatts_scatt_plts);
++    }
++
++    G_free(cat_rast_row);
++    G_free(rast_pixs);
++    G_free(belongs_pix);
++
++    return 0;
++}
++
++/*!
++   \brief Get list if bands needed to be opened for analysis from scCats struct.
++*/
++static void get_needed_bands(struct scCats * cats, int * b_needed_bands)
++{
++    // results in b_needed_bands - array of bools - if item has value 1, band (defined by item index) is needed to be opened
++    int i_cat, i_scatt, cat_id;
++
++    for(i_cat = 0;  i_cat < cats->n_a_cats; i_cat++)
++    {   
++        for(i_scatt = 0;  i_scatt < cats->cats_arr[i_cat]->n_a_scatts; i_scatt++)
++        {   
++            G_debug(3, "Active scatt %d in catt %d", i_scatt, i_cat);
++
++            b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2]] = 1;
++            b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2 + 1]] = 1;
++        }
++    }
++    return;
++}
++
++/*!
++   \brief Helper function for clean up.
++*/
++static void free_compute_scatts_data(int * fd_bands, struct rast_row * bands_rows, int n_a_bands, int * bands_ids, 
++                                     int * fd_cats_rasts, FILE ** f_cats_rasts_conds, int n_a_cats)
++{
++    int i, band_id;
++
++    for(i = 0; i < n_a_bands; i++)
++    {   
++        band_id = bands_ids[i];
++        if(band_id >= 0) {
++            Rast_close(fd_bands[i]);
++            G_free(bands_rows[band_id].row);
++            G_free(bands_rows[band_id].null_row);
++        }
++    }
++     
++    if(f_cats_rasts_conds)
++        for(i = 0; i < n_a_cats; i++)
++            if(f_cats_rasts_conds[i])
++                fclose(f_cats_rasts_conds[i]);
++
++    if(fd_cats_rasts)
++        for(i = 0; i < n_a_cats; i++)
++            if(fd_cats_rasts[i] >= 0)
++                Rast_close(fd_cats_rasts[i]);
++
++}
++
++/*!
++   \brief Compute scatter plots data.
++
++    If category has not defined no category raster condition file and no scatter plot with consdtion,
++    default scatter plot is computed.
++
++   \param region analysis region, beaware that all input data must be prepared for this region (bands (their ranges), cats_rasts_conds rasters...)
++   \param region function calls Rast_set_window for this region
++   \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are stored selected areas (conditions) in scatter plots
++   \param cats_rasts_conds paths to category raster conditions files representing selected areas (conditions) in rasters for every category 
++   \param cats_rasts_conds index in array represents corresponding category id
++   \param cats_rasts_conds for manupulation with category raster conditions file see also I_id_scatt_to_bands() and I_insert_patch_to_cat_rast()
++   \param bands names of analyzed bands, order of bands is defined by their id
++   \param n_bands number of bands
++   \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
++   \param [out] cats_rasts array of raster maps names where will be stored all selected pixels for every category
++
++   \return  0 on success
++   \return -1 on failure
++*/
++int I_compute_scatts(struct Cell_head *region, struct scCats * scatt_conds, const char ** cats_rasts_conds,
++                     const char ** bands, int n_bands, struct scCats * scatts, const char ** cats_rasts) 
++{
++    const char *mapset;
++    char header[1024];
++
++    int fd_cats_rasts[scatt_conds->n_a_cats];
++    FILE * f_cats_rasts_conds[scatt_conds->n_a_cats];
++
++    struct rast_row bands_rows[n_bands];
++
++    RASTER_MAP_TYPE data_type;
++
++    int nrows, i_band, n_a_bands, band_id, 
++        i, i_row, head_nchars, i_cat, id_cat;
++   
++    int fd_bands[n_bands];
++    int bands_ids[n_bands];
++    int b_needed_bands[n_bands];  
++
++    Rast_set_window(region);
++
++    for(i_band = 0; i_band < n_bands; i_band++)
++        fd_bands[i_band] = -1;
++    
++    for(i_band = 0; i_band < n_bands; i_band++)
++        bands_ids[i_band] = -1;
++
++    if (n_bands != scatts->n_bands ||
++        n_bands != scatt_conds->n_bands)
++        return -1;
++
++    memset(b_needed_bands, 0, (size_t)n_bands * sizeof(int));
++
++    get_needed_bands(scatt_conds, &b_needed_bands[0]);
++    get_needed_bands(scatts, &b_needed_bands[0]);
++
++    n_a_bands = 0;
++
++    /* open band rasters, which are needed for computation */
++    for(band_id = 0; band_id < n_bands; band_id++)
++    {
++        if(b_needed_bands[band_id])
++        {
++            G_debug(3, "Opening raster no. %d with name: %s", band_id, bands[band_id]);
++
++            if ((mapset = G_find_raster2(bands[band_id],"")) == NULL) {
++                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
++                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++                G_warning(_("Unbale to read find raster <%s>"), bands[band_id]);
++                return -1;
++            }
++            
++            if ((fd_bands[n_a_bands] = Rast_open_old(bands[band_id], mapset)) < 0) {
++                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
++                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++                G_warning(_("Unbale to open raster <%s>"), bands[band_id]);
++                return -1;
++            }
++
++            data_type = Rast_get_map_type(fd_bands[n_a_bands]);
++            if(data_type != CELL_TYPE) {
++                G_warning(_("Raster <%s> type is not <%s>"), bands[band_id], "CELL");
++                return -1;
++            }
++
++            bands_rows[band_id].row =  Rast_allocate_c_buf();
++            bands_rows[band_id].null_row =  Rast_allocate_null_buf();
++
++            if(Rast_read_range(bands[band_id], mapset, &bands_rows[band_id].rast_range) != 1){
++                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
++                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++                G_warning(_("Unable to read range of raster <%s>"), bands[band_id]);
++                return -1;
++            }      
++
++            bands_ids[n_a_bands] = band_id;
++            ++n_a_bands;
++        }
++    }
++
++    /* open category rasters condition files and category rasters */
++    for(i_cat = 0; i_cat < scatts->n_a_cats; i_cat++)
++    {
++        id_cat = scatts->cats_ids[i_cat];
++        if(cats_rasts[id_cat]) {
++            fd_cats_rasts[i_cat] = Rast_open_new(cats_rasts[id_cat], CELL_TYPE);   
++        }
++        else
++            fd_cats_rasts[i_cat] = -1;
++
++        if(cats_rasts_conds[id_cat]) {
++            f_cats_rasts_conds[i_cat] = fopen(cats_rasts_conds[id_cat], "r");
++            if(!f_cats_rasts_conds[i_cat]) {
++                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, 
++                                         f_cats_rasts_conds, f_cats_rasts_conds, scatt_conds->n_a_cats);
++                G_warning(_("Unable to open category raster condtition file <%s>"), bands[band_id]);
++                return -1;
++            }
++        }
++        else
++            f_cats_rasts_conds[i_cat] = NULL;
++    }
++
++    head_nchars =  get_cat_rast_header(region, header);
++    for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
++        if(f_cats_rasts_conds[i_cat])
++            if( fseek(f_cats_rasts_conds[i_cat] , head_nchars, SEEK_SET) != 0) {
++                G_warning(_("Corrupted category raster conditions file (fseek failed)"));
++                return -1;
++            }
++
++    nrows = Rast_window_rows();
++
++    /* analyze bands by rows */
++    for (i_row = 0; i_row < nrows; i_row++)
++    {
++        for(i_band = 0; i_band < n_a_bands; i_band++)
++        {   
++            band_id = bands_ids[i_band];
++            Rast_get_c_row(fd_bands[i_band], bands_rows[band_id].row, i_row);
++            Rast_get_null_value_row (fd_bands[i_band], bands_rows[band_id].null_row, i_row);
++        }
++        if(compute_scatts_from_chunk_row(region, scatt_conds, f_cats_rasts_conds, bands_rows, scatts, fd_cats_rasts) == -1) 
++        {
++            free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, fd_cats_rasts, 
++                                     f_cats_rasts_conds, scatt_conds->n_a_cats);
++            return -1;
++        }
++ 
++    }
++    free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, 
++                             fd_cats_rasts, f_cats_rasts_conds, scatt_conds->n_a_cats); 
++    return 0;    
++}
++
++
++int I_merge_arrays(unsigned char *  merged_arr, unsigned char *  overlay_arr, unsigned rows, unsigned cols, double alpha)
++{
++    unsigned int i_row, i_col, i_b;
++    unsigned int row_idx, col_idx, idx;
++    unsigned int c_a_i, c_a;
++
++    for(i_row = 0; i_row < rows; i_row++)
++    {
++        row_idx = i_row * cols;
++        for(i_col = 0; i_col < cols; i_col++)
++        {
++                col_idx = 4 * (row_idx + i_col);
++                idx = col_idx + 3;
++
++                c_a = overlay_arr[idx] * alpha;
++                c_a_i = 255 - c_a;
++
++                merged_arr[idx] = (c_a_i * (int)merged_arr[idx] + c_a * 255) / 255;
++                
++                for(i_b = 0; i_b < 3; i_b++)
++                {
++                    idx = col_idx + i_b;
++                    merged_arr[idx] = (c_a_i * (int)merged_arr[idx] + c_a * (int)overlay_arr[idx]) / 255;
++                }
++        }
++    }
++    return 0; 
++}
++
++
++int I_apply_colormap(unsigned char * vals, unsigned char * vals_mask, unsigned vals_size, unsigned char * colmap, unsigned char * col_vals){
++    unsigned int i_val;
++    int v, i, i_cm;
++
++    for(i_val = 0; i_val < vals_size; i_val++){
++        i_cm = 4 * i_val;
++
++        v = vals[i_val];
++
++        if(vals_mask[i_val])
++            for(i = 0; i < 4; i++) col_vals[i_cm + i] = colmap[258 * 4 + i];
++        else if(v > 255)
++            for(i = 0; i < 4; i++) col_vals[i_cm + i] = colmap[257 * 4 + i];
++        else if(v < 0)
++            for(i = 0; i < 4; i++) col_vals[i_cm + i] = colmap[256 * 4 + i];
++        else
++            for(i = 0; i < 4; i++){ col_vals[i_cm + i] = colmap[v * 4 + i];
++        }
++    }
++    return 0;
++}
+Index: lib/imagery/scatt_sccats.c
+===================================================================
+--- lib/imagery/scatt_sccats.c	(revision 0)
++++ lib/imagery/scatt_sccats.c	(working copy)
+@@ -0,0 +1,405 @@
++/*!
++   \file lib/imagery/scatt_cat_rast.c
++
++   \brief Imagery library - functions for manipulation with scatter plot structs.
++
++   Copyright (C) 2013 by the GRASS Development Team
++
++   This program is free software under the GNU General Public License
++   (>=v2).  Read the file COPYING that comes with GRASS for details.
++
++   \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
++ */
++
++#include <grass/raster.h>
++#include <grass/imagery.h>
++#include <grass/gis.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <string.h>
++
++/*!
++   \brief Compute band ids from scatter plot id.
++
++    Scatter plot id describes which bands defines the scatter plot.
++
++    Let say we have 3 bands, their ids are 0, 1 and 2.
++    Scatter plot with id 0 consists of band 1 (b_1_id) 0 and  band 2 (b_2_id) 1.
++    All scatter plots:
++    scatt_id b_1_id b_2_id
++    0        0      1
++    1        0      2
++    2        1      2
++
++   \param scatt_id scatter plot id
++   \param n_bands number of bands
++   \param [out] b_1_id id of band1
++   \param[out] b_2_id id of band2
++
++   \return 0
++ */
++int I_id_scatt_to_bands(const int scatt_id, const int n_bands, int * b_1_id, int * b_2_id)
++{   
++    int n_b1 = n_bands - 1;
++
++    * b_1_id = (int) ((2 * n_b1 + 1 - sqrt((double)((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2);
++
++    * b_2_id = scatt_id - ((* b_1_id) * (2 * n_b1 + 1) - (* b_1_id) * (* b_1_id)) / 2 + (* b_1_id) + 1;
++
++    return 0;
++}
++
++
++/*!
++   \brief Compute scatter plot id from band ids.
++
++    See also I_id_scatt_to_bands().
++
++   \param n_bands number of bands
++   \param b_1_id id of band1
++   \param b_1_id id of band2
++   \param [out] scatt_id scatter plot id
++
++   \return 0
++ */
++int I_bands_to_id_scatt(const int b_1_id, const int b_2_id, const int n_bands, int * scatt_id)
++{   
++    int n_b1 = n_bands - 1;
++
++    * scatt_id = (b_1_id * (2 * n_b1 + 1) - b_1_id * b_1_id) / 2 + b_2_id - b_1_id - 1;
++
++    return 0;
++}
++
++/*!
++   \brief Initialize structure for storing scatter plots data.
++
++   \param cats pointer to scCats struct 
++   \param n_bands number of bands
++   \param type SC_SCATT_DATA - stores scatter plots 
++   \param type SC_SCATT_CONDITIONS - stores selected areas in scatter plots
++ */
++void I_sc_init_cats(struct scCats * cats, int n_bands, int type)
++{
++    int i_cat;
++
++    cats->type = type;
++
++    cats->n_cats = 100;
++    cats->n_a_cats = 0;
++
++    cats->n_bands = n_bands;
++    cats->n_scatts = (n_bands - 1) * n_bands / 2;
++
++    cats->cats_arr = (struct scScatts **) G_malloc(cats->n_cats * sizeof(struct scScatts *));
++    memset(cats->cats_arr, 0, cats-> n_cats * sizeof(struct scScatts *));
++
++    cats->cats_ids = (int *)  G_malloc(cats->n_cats * sizeof(int));
++    cats->cats_idxs =(int *)  G_malloc(cats->n_cats * sizeof(int));
++
++    for(i_cat = 0; i_cat < cats->n_cats; i_cat++)
++        cats->cats_idxs[i_cat] = -1;
++
++    return;
++}
++
++/*!
++   \brief Free data of struct scCats, the structure itself remains alocated.
++
++   \param cats pointer to existing scCats struct
++ */
++void I_sc_free_cats(struct scCats * cats)
++{
++    int i_cat;
++
++    for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
++    {        
++        if(cats->cats_arr[i_cat])
++        {   
++            G_free(cats->cats_arr[i_cat]->scatt_idxs);
++            G_free(cats->cats_arr[i_cat]->scatts_bands);
++            G_free(cats->cats_arr[i_cat]->scatts_arr);
++            G_free(cats->cats_arr[i_cat]);
++        }
++    }
++
++    G_free(cats->cats_ids);
++    G_free(cats->cats_idxs);
++    G_free(cats->cats_arr);
++
++    cats->n_cats = 0;
++    cats->n_a_cats = 0;
++    cats->n_bands = 0;
++    cats->n_scatts = 0;
++    cats->type = -1;
++
++    return;
++}
++
++#if 0
++void I_sc_get_active_categories(int * a_cats_ids, int * n_a_cats, struct scCats * cats)
++{
++    a_cats_ids = cats->cats_ids;
++    * n_a_cats = cats->n_a_cats;
++}
++#endif
++
++/*!
++   \brief Add category.
++    
++    Category represents group of scatter plots.
++
++   \param cats pointer to scCats struct
++
++   \return assigned category id (starts with 0)
++   \return -1 if maximum nuber of categories was reached
++ */
++int I_sc_add_cat(struct scCats * cats)
++{
++    int i_scatt, i_cat_id, cat_id;
++    int n_a_cats = cats->n_a_cats;
++
++    if(cats->n_a_cats >= cats->n_cats)
++        return -1;
++
++    for(i_cat_id = 0; i_cat_id < cats->n_cats; i_cat_id++)
++        if(cats->cats_idxs[i_cat_id] < 0) {
++            cat_id = i_cat_id;
++            break;
++        }
++
++    cats->cats_ids[n_a_cats] = cat_id;
++    cats->cats_idxs[cat_id] = n_a_cats;
++    
++    cats->cats_arr[n_a_cats] = (struct scScatts *) G_malloc(sizeof(struct scScatts));
++
++    cats->cats_arr[n_a_cats]->scatts_arr = (struct scdScattData **) G_malloc(cats->n_scatts * sizeof(struct scdScattData *));
++    memset((cats->cats_arr[n_a_cats]->scatts_arr), 0, cats->n_scatts * sizeof(struct scdScattData *));
++    
++    cats->cats_arr[n_a_cats]->n_a_scatts = 0;
++
++    cats->cats_arr[n_a_cats]->scatts_bands = (int *) G_malloc(cats->n_scatts * 2 * sizeof(int));
++     
++    cats->cats_arr[n_a_cats]->scatt_idxs = (int *) G_malloc(cats->n_scatts * sizeof(int));
++    for(i_scatt = 0; i_scatt < cats->n_scatts; i_scatt++)
++        cats->cats_arr[n_a_cats]->scatt_idxs[i_scatt] = -1;
++    
++    ++cats->n_a_cats;
++
++    return cat_id;
++}
++
++#if 0
++int I_sc_delete_cat(struct scCats * cats, int cat_id)
++{
++    int cat_idx, i_cat;
++
++    if(cat_id < 0 || cat_id >= cats->n_cats)
++        return -1;
++
++    cat_idx = cats->cats_idxs[cat_id];
++    if(cat_idx < 0)
++        return -1;
++
++    G_free(cats->cats_arr[cat_idx]->scatt_idxs);
++    G_free(cats->cats_arr[cat_idx]->scatts_bands);
++    G_free(cats->cats_arr[cat_idx]->scatts_arr);
++    G_free(cats->cats_arr[cat_idx]);
++
++    for(i_cat = cat_idx; i_cat < cats->n_a_cats - 1; i_cat++)
++    {
++        cats->cats_arr[i_cat] = cats->cats_arr[i_cat + 1];
++        cats->cats_ids[i_cat] = cats->cats_ids[i_cat + 1];
++    }
++    cats->cats_idxs[cat_id] = -1; 
++
++    --cats->n_a_cats;
++    
++    return 0;
++}
++#endif
++
++/*!
++   \brief Insert scatter plot data .
++    Inserted scatt_data struct must have same type as cats struct (SC_SCATT_DATA or SC_SCATT_CONDITIONS).
++
++   \param cats pointer to scCats struct
++   \param cat_id id number of category.
++   \param scatt_id id number of scatter plot.
++
++   \return  0 on success
++   \return -1 on failure
++ */
++int I_sc_insert_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
++{
++    int band_1, band_2, cat_idx, n_a_scatts;
++    struct scScatts * scatts;
++
++    if(cat_id < 0 || cat_id >= cats->n_cats)
++        return -1;
++
++    cat_idx = cats->cats_idxs[cat_id];
++    if(cat_idx < 0)
++        return -1;
++
++    if(scatt_id < 0 && scatt_id >= cats->n_scatts)
++        return -1;
++
++    scatts = cats->cats_arr[cat_idx];
++    if(scatts->scatt_idxs[scatt_id] >= 0)
++        return -1;
++
++    if(!scatt_data->b_conds_arr && cats->type == SC_SCATT_CONDITIONS)
++        return -1;
++
++    if(!scatt_data->scatt_vals_arr && cats->type == SC_SCATT_DATA)
++        return -1;
++
++    n_a_scatts = scatts->n_a_scatts;
++
++    scatts->scatt_idxs[scatt_id] = n_a_scatts;
++
++    I_id_scatt_to_bands(scatt_id, cats->n_bands, &band_1, &band_2);
++
++    scatts->scatts_bands[n_a_scatts * 2] = band_1;
++    scatts->scatts_bands[n_a_scatts * 2 + 1] = band_2;
++
++    scatts->scatts_arr[n_a_scatts] = scatt_data;
++    ++scatts->n_a_scatts;
++
++    return 0;
++}
++
++#if 0
++int I_sc_remove_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
++{
++    int cat_idx, scatt_idx, n_init_scatts, i_scatt;
++    struct scScatts * scatts;
++
++    if(cat_id < 0 && cat_id >= cats->n_cats)
++        return -1;
++
++    cat_idx = cats->cats_idxs[cat_id];
++    if(cat_idx < 0)
++        return -1;
++
++    if(scatt_id < 0 || scatt_id >= cats->n_scatts)
++        return -1;
++
++    scatts = cats->cats_arr[cat_idx];
++    if(scatts->scatt_idxs[scatt_id] < 0)
++        return -1;
++
++    scatt_data = scatts->scatts_arr[scatt_idx];
++
++    for(i_scatt = scatt_idx; i_scatt < scatts->n_a_scatts - 1; i_scatt++)
++    {
++        scatts->scatts_arr[i_scatt] = scatts->scatts_arr[i_scatt + 1];
++        scatts->scatts_bands[i_scatt * 2] = scatts->scatts_bands[(i_scatt + 1)* 2];
++        scatts->scatts_bands[i_scatt * 2 + 1] = scatts->scatts_bands[(i_scatt + 1) * 2 + 1];
++    }
++    scatts->scatts_arr[scatts->n_a_scatts] = NULL;
++
++    scatts->scatt_idxs[scatt_id] = -1;
++
++    scatt_data = scatts->scatts_arr[scatt_id];
++    scatts->n_a_scatts--;
++
++    return 0;
++}
++
++int I_sc_set_value(struct scCats * cats, int cat_id, int scatt_id, int value_idx, int value)
++{
++    int n_a_scatts = cats->cats_arr[cat_id]->n_a_scatts;
++    int cat_idx, scatt_idx, ret;
++
++    cat_idx = cats->cats_idxs[cat_id];
++    if(cat_idx < 0)
++        return -1;
++    
++    if(cats->cats_arr[cat_idx]->scatt_idxs[scatt_id] < 0)
++        return -1;
++
++    cat_idx = cats->cats_idxs[cat_id];
++    scatt_idx = cats->cats_arr[cat_idx]->scatt_idxs[scatt_id];
++
++    I_scd_set_value(cats->cats_arr[cat_idx]->scatts_arr[scatt_idx], value_idx, value);
++
++    return 0;
++}
++#endif
++
++/*!
++   \brief Insert scatter plot data.
++    
++   \param scatt_data pointer to existing struct scdScattData
++   \param type SC_SCATT_DATA for scatter plots or SC_SCATT_CONDITIONS for selected areas in scatter plot
++   \param n_vals number of data values
++   \param data array of values (unsigned char for SC_SCATT_CONDITIONS, unsigned int for SC_SCATT_DATA)
++ */
++void I_scd_init_scatt_data(struct scdScattData * scatt_data, int type, int n_vals, void * data)
++{
++    scatt_data->n_vals = n_vals;
++
++    if(type == SC_SCATT_DATA)
++    {   
++        if(data)
++            scatt_data->scatt_vals_arr = (unsigned int *) data;
++        else {
++            scatt_data->scatt_vals_arr = (unsigned int *) G_malloc(n_vals * sizeof(unsigned int));
++            memset(scatt_data->scatt_vals_arr, 0, n_vals * sizeof(unsigned int)); 
++        }
++        scatt_data->b_conds_arr = NULL;
++    }
++    else if(type == SC_SCATT_CONDITIONS)
++    {
++        if(data)
++            scatt_data->b_conds_arr = (unsigned char *) data;
++        else {
++            scatt_data->b_conds_arr = (unsigned char *) G_malloc(n_vals * sizeof(unsigned char));
++            memset(scatt_data->b_conds_arr, 0, n_vals * sizeof(unsigned char));
++        }
++        scatt_data->scatt_vals_arr = NULL;
++    }
++
++    return;
++}
++
++
++#if 0
++void I_scd_get_range_min_max(struct scdScattData * scatt_data, CELL * band_1_min, CELL * band_1_max, CELL * band_2_min, CELL * band_2_max)
++{
++
++    Rast_get_range_min_max(&(scatt_data->band_1_range), band_1_min, band_2_min);
++    Rast_get_range_min_max(&(scatt_data->band_2_range), band_2_min, band_2_max);
++
++    return;
++}
++s
++void * I_scd_get_data_ptr(struct scdScattData * scatt_data)
++{
++    if(!scatt_data->b_conds_arr)
++        return scatt_data->b_conds_arr;
++    else if(!scatt_data->scatt_vals_arr)
++        return scatt_data->scatt_vals_arr;
++
++    return NULL;
++}
++
++int I_scd_set_value(struct scdScattData * scatt_data, unsigned int val_idx, unsigned int val)
++{
++    if(val_idx < 0 && val_idx >  scatt_data->n_vals)
++        return -1;
++
++    if(scatt_data->b_conds_arr)
++        scatt_data->b_conds_arr[val_idx] = val;
++    else if(scatt_data->scatt_vals_arr)
++        scatt_data->scatt_vals_arr[val_idx] = val;
++    else
++        return -1;
++
++    return 0;
++}
++#endif
 Index: include/imagery.h
 ===================================================================
---- include/imagery.h	(revision 57601)
+--- include/imagery.h	(revision 57633)
 +++ include/imagery.h	(working copy)
 @@ -135,6 +135,56 @@
      
@@ -61,7 +1290,7 @@
  #define GROUPFILE "CURGROUP"
 Index: include/defs/vedit.h
 ===================================================================
---- include/defs/vedit.h	(revision 57601)
+--- include/defs/vedit.h	(revision 57633)
 +++ include/defs/vedit.h	(working copy)
 @@ -33,6 +33,8 @@
  int Vedit_merge_lines(struct Map_info *, struct ilist *);
@@ -74,13 +1303,13 @@
  
 Index: include/defs/imagery.h
 ===================================================================
---- include/defs/imagery.h	(revision 57601)
+--- include/defs/imagery.h	(revision 57633)
 +++ include/defs/imagery.h	(working copy)
-@@ -110,6 +110,23 @@
+@@ -110,6 +110,26 @@
  FILE *I_fopen_subgroup_ref_new(const char *, const char *);
  FILE *I_fopen_subgroup_ref_old(const char *, const char *);
  
-+/* scatt_plt.c */
++/* scatt_sccats.c */
 +void I_sc_init_cats(struct scCats *, int, int);
 +void I_sc_free_cats(struct scCats *);
 +int I_sc_add_cat(struct scCats *);
@@ -88,6 +1317,7 @@
 +
 +void I_scd_init_scatt_data(struct scdScattData *, int, int, void *);
 +
++/* scatt.c */
 +int I_compute_scatts(struct Cell_head *, struct scCats *, const char **, 
 +	                 const char **, int, struct scCats *, const char **);
 +
@@ -96,30 +1326,2549 @@
 +
 +int I_id_scatt_to_bands(const int, const int, int *, int *);
 +int I_bands_to_id_scatt(const int, const int, const int, int *);
++int I_merge_arrays(unsigned char *, unsigned char *, unsigned, unsigned, double);
++int I_apply_colormap(unsigned char *, unsigned char *, unsigned,  unsigned char *, unsigned char *);
 +
  /* sig.c */
  int I_init_signatures(struct Signature *, int);
  int I_new_signature(struct Signature *);
-Index: gui/icons/grass/polygon.png
+Index: gui/wxpython/mapdisp/toolbars.py
 ===================================================================
-Cannot display: file marked as a binary type.
-svn:mime-type = application/octet-stream
-Index: gui/icons/grass/polygon.png
+--- gui/wxpython/mapdisp/toolbars.py	(revision 57633)
++++ gui/wxpython/mapdisp/toolbars.py	(working copy)
+@@ -239,7 +239,8 @@
+                       (MapIcons["scatter"],     self.parent.OnScatterplot),
+                       (MapIcons["histogram"],   self.parent.OnHistogramPyPlot),
+                       (BaseIcons["histogramD"], self.parent.OnHistogram),
+-                      (MapIcons["vnet"],        self.parent.OnVNet)))
++                      (MapIcons["vnet"],        self.parent.OnVNet),
++                      (MapIcons["scatter"],     self.parent.OnScatterplot2)))
+         
+     def OnDecoration(self, event):
+         """!Decorations overlay menu
+Index: gui/wxpython/mapdisp/frame.py
 ===================================================================
---- gui/icons/grass/polygon.png	(revision 57601)
-+++ gui/icons/grass/polygon.png	(working copy)
-
-Property changes on: gui/icons/grass/polygon.png
-___________________________________________________________________
-Added: svn:mime-type
-## -0,0 +1 ##
-+application/octet-stream
-\ No newline at end of property
+--- gui/wxpython/mapdisp/frame.py	(revision 57633)
++++ gui/wxpython/mapdisp/frame.py	(working copy)
+@@ -225,6 +225,7 @@
+         #
+         self.dialogs = {}
+         self.dialogs['attributes'] = None
++        self.dialogs['scatt_plot'] = None
+         self.dialogs['category'] = None
+         self.dialogs['barscale'] = None
+         self.dialogs['legend'] = None
+@@ -1168,6 +1169,19 @@
+         """!Returns toolbar with zooming tools"""
+         return self.toolbars['map']
+ 
++    def OnScatterplot2(self, event):
++        """!Init interactive scatterplot tools
++        """
++        if self.dialogs['scatt_plot']:
++            self.dialogs['scatt_plot'].Raise()
++            return
++
++        from scatt_plot.dialogs import ScattPlotMainDialog
++        self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface)
++        
++        self.dialogs['scatt_plot'].CenterOnScreen()
++        self.dialogs['scatt_plot'].Show()
++
+     def OnVNet(self, event):
+         """!Dialog for v.net* modules 
+         """
+Index: gui/wxpython/vdigit/wxdigit.py
+===================================================================
+--- gui/wxpython/vdigit/wxdigit.py	(revision 57633)
++++ gui/wxpython/vdigit/wxdigit.py	(working copy)
+@@ -17,7 +17,7 @@
+ (and NumPy would be an excellent candidate for acceleration via
+ e.g. OpenCL or CUDA; I'm surprised it hasn't happened already).
+ 
+-(C) 2007-2011 by the GRASS Development Team
++(C) 2007-2011, 2013 by the GRASS Development Team
+ 
+ This program is free software under the GNU General Public License
+ (>=v2). Read the file COPYING that comes with GRASS for details.
+@@ -27,6 +27,8 @@
+ 
+ import grass.script.core as grass
+ 
++from grass.pydispatch.signal import Signal
++
+ from core.gcmd        import GError
+ from core.debug       import Debug
+ from core.settings    import UserSettings
+@@ -176,7 +178,21 @@
+         
+         if self.poMapInfo:
+             self.InitCats()
+-        
++
++        self.emit_signals = False
++
++        # signals which describes features changes during digitization, 
++        # activate them using EmitSignals method 
++        #TODO signal for errors?
++        self.featureAdded = Signal('IVDigit.featureAdded')
++        self.areasDeleted = Signal('IVDigit.areasDeleted')
++        self.vertexMoved = Signal('IVDigit.vertexMoved')
++        self.vertexAdded = Signal('IVDigit.vertexAdded')
++        self.vertexRemoved = Signal('IVDigit.vertexRemoved')
++        self.featuresDeleted = Signal('IVDigit.featuresDeleted')
++        self.featuresMoved = Signal('IVDigit.featuresMoved')
++        self.lineEdited = Signal('IVDigit.lineEdited')
++
+     def __del__(self):
+         Debug.msg(1, "IVDigit.__del__()")
+         Vect_destroy_line_struct(self.poPoints)
+@@ -188,7 +204,12 @@
+             Vect_close(self.poBgMapInfo)
+             self.poBgMapInfo = self.popoBgMapInfo = None
+             del self.bgMapInfo
+-        
++     
++    def EmitSignals(self, emit):
++        """!Activate/deactivate signals which describes features changes during digitization.
++        """
++        self.emit_signals = emit
++
+     def CloseBackgroundMap(self):
+         """!Close background vector map"""
+         if not self.poBgMapInfo:
+@@ -394,7 +415,6 @@
+         
+         @return tuple (number of added features, feature ids)
+         """
+-        
+         layer = self._getNewFeaturesLayer()
+         cat = self._getNewFeaturesCat()
+         
+@@ -419,10 +439,14 @@
+             return (-1, None)
+         
+         self.toolbar.EnableUndo()
+-        
+-        return self._addFeature(vtype, points, layer, cat,
+-                                self._getSnapMode(), self._display.GetThreshold())
+-    
++
++        ret = self._addFeature(vtype, points, layer, cat,
++                               self._getSnapMode(), self._display.GetThreshold())
++        if ret[0] > -1 and self.emit_signals:
++            self.featureAdded.emit(new_bboxs = [self._createBbox(points)], new_areas_cats = [[{layer : [cat]}, None]])
++
++        return ret
++
+     def DeleteSelectedLines(self):
+         """!Delete selected features
+ 
+@@ -434,16 +458,27 @@
+         # collect categories for deleting if requested
+         deleteRec = UserSettings.Get(group = 'vdigit', key = 'delRecord', subkey = 'enabled')
+         catDict = dict()
++
++        old_bboxs = []
++        old_areas_cats = []
+         if deleteRec:
+             for i in self._display.selected['ids']:
++                
+                 if Vect_read_line(self.poMapInfo, None, self.poCats, i) < 0:
+                     self._error.ReadLine(i)
+                 
+-                cats = self.poCats.contents
+-                for j in range(cats.n_cats):
+-                    if cats.field[j] not in catDict.keys():
+-                        catDict[cats.field[j]] = list()
+-                    catDict[cats.field[j]].append(cats.cat[j])
++                if self.emit_signals:
++                    ret = self._getLineAreaBboxCats(i)
++                    if ret:
++                        old_bboxs += ret[0]
++                        old_areas_cats += ret[1]
++                
++                # catDict was not used -> put into comment
++                #cats = self.poCats.contents
++                #for j in range(cats.n_cats):
++                #    if cats.field[j] not in catDict.keys():
++                #        catDict[cats.field[j]] = list()
++                #    catDict[cats.field[j]].append(cats.cat[j])
+         
+         poList = self._display.GetSelectedIList()
+         nlines = Vedit_delete_lines(self.poMapInfo, poList)
+@@ -456,7 +491,10 @@
+                 self._deleteRecords(catDict)
+             self._addChangeset()
+             self.toolbar.EnableUndo()
+-        
++
++            if self.emit_signals:
++                self.featuresDeleted.emit(old_bboxs = old_bboxs, old_areas_cats = old_areas_cats)
++
+         return nlines
+             
+     def _deleteRecords(self, cats):
+@@ -512,22 +550,173 @@
+ 
+         @return number of deleted 
+         """
++        if len(self._display.selected['ids']) < 1:
++            return 0
++        
+         poList = self._display.GetSelectedIList()
+         cList  = poList.contents
+         
+         nareas = 0
++        old_bboxs = []
++        old_areas_cats = []
++
+         for i in range(cList.n_values):
++
+             if Vect_get_line_type(self.poMapInfo, cList.value[i]) != GV_CENTROID:
+                 continue
+-            
++
++            if self.emit_signals:
++                area = Vect_get_centroid_area(self.poMapInfo, cList.value[i]);
++                if area > 0: 
++                    bbox, cats = self._getaAreaBboxCats(area)
++                    old_bboxs += bbox
++                    old_areas_cats += cats
++
+             nareas += Vedit_delete_area_centroid(self.poMapInfo, cList.value[i])
+         
+         if nareas > 0:
+             self._addChangeset()
+             self.toolbar.EnableUndo()
++            if self.emit_signals:
++                self.areasDeleted.emit(old_bboxs = old_bboxs, old_areas_cats = old_areas_cats)        
++
++        return nareas
++   
++    def _getLineAreaBboxCats(self, ln_id):
++        ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
++
++        if ltype == GV_CENTROID:
++            #TODO centroid opttimization, can be adited also its area -> it will appear two times in new_ lists
++            return self._getCentroidAreaBboxCats(ln_id)
++        else: 
++            return [self._getBbox(ln_id)], [self._getLineAreasCategories(ln_id)]
++
++
++    def _getCentroidAreaBboxCats(self, centroid):
++        if not Vect_line_alive(self.poMapInfo, centroid):
++            return None
++
++        area = Vect_get_centroid_area(self.poMapInfo, centroid)  
++        if area > 0:
++            return self._getaAreaBboxCats(area)
++        else:
++            return None
++
++    def _getaAreaBboxCats(self, area):
++
++        po_b_list = Vect_new_list()
++        Vect_get_area_boundaries(self.poMapInfo, area, po_b_list);
++        b_list = po_b_list.contents
++
++        geoms = []
++        areas_cats = []
++
++        if b_list.n_values > 0:
++            for i_line in range(b_list.n_values):
++
++                line = b_list.value[i_line];
++
++                geoms.append(self._getBbox(abs(line)))
++                areas_cats.append(self._getLineAreasCategories(abs(line)))
+         
+-        return nareas
++        Vect_destroy_list(po_b_list);
++
++        return geoms, areas_cats
++
++    def _getLineAreasCategories(self, ln_id):
++        if not Vect_line_alive (self.poMapInfo, ln_id):
++            return []
++
++        ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
++        if ltype != GV_BOUNDARY:
++            return []
++
++        cats = [None, None]
++
++        left = c_int()
++        right = c_int()
++
++        if Vect_get_line_areas(self.poMapInfo, ln_id, pointer(left), pointer(right)) == 1:
++            areas = [left.value, right.value]
++
++            for i, a in enumerate(areas):
++                if a > 0: 
++                    centroid = Vect_get_area_centroid(self.poMapInfo, a)
++                    if centroid <= 0:
++                        continue
++                    c = self._getCategories(centroid)
++                    if c:
++                        cats[i] = c
++
++        return cats
++
++    def _getCategories(self, ln_id):
++        if not Vect_line_alive (self.poMapInfo, ln_id):
++            return none
++
++        poCats = Vect_new_cats_struct()
++        if Vect_read_line(self.poMapInfo, None, poCats, ln_id) < 0:
++            Vect_destroy_cats_struct(poCats)
++            return None
++
++        cCats = poCats.contents
++
++        cats = {}
++        for j in range(cCats.n_cats):
++            if cats.has_key(cCats.field[j]):
++                cats[cCats.field[j]].append(cCats.cat[j])
++            else:
++                cats[cCats.field[j]] = [cCats.cat[j]]
+     
++        Vect_destroy_cats_struct(poCats)
++        return cats
++
++    def _getBbox(self, ln_id):
++        if not Vect_line_alive (self.poMapInfo, ln_id):
++            return None
++
++        poPoints = Vect_new_line_struct()
++        if Vect_read_line(self.poMapInfo, poPoints, None, ln_id) < 0:
++            Vect_destroy_line_struct(poPoints)
++            return []
++
++        geom = self._convertGeom(poPoints)
++        bbox = self._createBbox(geom)
++        Vect_destroy_line_struct(poPoints)
++        return bbox
++
++    def _createBbox(self, points):
++
++        bbox = {}
++        for pt in points:
++            if not bbox.has_key('maxy'):
++                bbox['maxy'] = pt[1]
++                bbox['miny'] = pt[1]
++                bbox['maxx'] = pt[0]
++                bbox['minx'] = pt[0]
++                continue
++                
++            if   bbox['maxy'] < pt[1]:
++                bbox['maxy'] = pt[1]
++            elif bbox['miny'] > pt[1]:
++                bbox['miny'] = pt[1]
++                
++            if   bbox['maxx'] < pt[0]:
++                bbox['maxx'] = pt[0]
++            elif bbox['minx'] > pt[0]:
++                bbox['minx'] = pt[0]
++        return bbox
++
++    def _convertGeom(self, poPoints):
++
++        Points = poPoints.contents
++
++        pts_geom = []
++        for j in range(Points.n_points):
++            pts_geom.append((Points.x[j], Points.y[j]))
++
++        return pts_geom
++
+     def MoveSelectedLines(self, move):
+         """!Move selected features
+ 
+@@ -536,16 +725,45 @@
+         if not self._checkMap():
+             return -1
+         
++        nsel = len(self._display.selected['ids'])
++        if nsel < 1:
++            return -1   
++        
+         thresh = self._display.GetThreshold()
+         snap   = self._getSnapMode()
+         
+         poList = self._display.GetSelectedIList()
++
++        if self.emit_signals:
++            old_bboxs = []
++            old_areas_cats = []
++            for sel_id in self._display.selected['ids']:
++                ret = self._getLineAreaBboxCats(sel_id)
++                if ret:
++                    old_bboxs += ret[0]
++                    old_areas_cats += ret[1]
++        
++            Vect_set_updated(self.poMapInfo, 1)
++            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
++        
+         nlines = Vedit_move_lines(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
+                                   poList,
+                                   move[0], move[1], 0,
+                                   snap, thresh)
++
+         Vect_destroy_list(poList)
+-        
++
++        if nlines > 0 and self.emit_signals:
++            new_bboxs = []
++            new_areas_cats = []
++            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
++            for i in range(n_up_lines_old, n_up_lines):
++                new_id = Vect_get_updated_line(self.poMapInfo, i)
++                ret = self._getLineAreaBboxCats(new_id)
++                if ret:
++                    new_bboxs += ret[0]
++                    new_areas_cats += ret[1]
++
+         if nlines > 0 and self._settings['breakLines']:
+             for i in range(1, nlines):
+                 self._breakLineAtIntersection(nlines + i, None, changeset)
+@@ -553,7 +771,13 @@
+         if nlines > 0:
+             self._addChangeset()
+             self.toolbar.EnableUndo()
+-        
++            
++            if self.emit_signals:
++                self.featuresMoved.emit(new_bboxs = new_bboxs,
++                                        old_bboxs = old_bboxs, 
++                                        old_areas_cats = old_areas_cats, 
++                                        new_areas_cats = new_areas_cats)
++
+         return nlines
+ 
+     def MoveSelectedVertex(self, point, move):
+@@ -571,12 +795,21 @@
+         
+         if len(self._display.selected['ids']) != 1:
+             return -1
+-        
++
++        # move only first found vertex in bbox 
++        poList = self._display.GetSelectedIList()
++
++        if self.emit_signals:
++            cList = poList.contents
++            old_bboxs = [self._getBbox(cList.value[0])]
++            old_areas_cats = [self._getLineAreasCategories(cList.value[0])]
++
++            Vect_set_updated(self.poMapInfo, 1)
++            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
++
+         Vect_reset_line(self.poPoints)
+         Vect_append_point(self.poPoints, point[0], point[1], 0.0)
+-        
+-        # move only first found vertex in bbox 
+-        poList = self._display.GetSelectedIList()
++
+         moved = Vedit_move_vertex(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
+                                   poList, self.poPoints,
+                                   self._display.GetThreshold(type = 'selectThresh'),
+@@ -584,7 +817,17 @@
+                                   move[0], move[1], 0.0,
+                                   1, self._getSnapMode())
+         Vect_destroy_list(poList)
+-        
++
++        if moved > 0 and self.emit_signals:
++            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
++
++            new_bboxs = []
++            new_areas_cats = []
++            for i in range(n_up_lines_old, n_up_lines):
++                new_id = Vect_get_updated_line(self.poMapInfo, i)
++                new_bboxs.append(self._getBbox(new_id))
++                new_areas_cats.append(self._getLineAreasCategories(new_id))
++
+         if moved > 0 and self._settings['breakLines']:
+             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
+                                           None)
+@@ -592,7 +835,13 @@
+         if moved > 0:
+             self._addChangeset()
+             self.toolbar.EnableUndo()
+-        
++
++            if self.emit_signals:
++                self.vertexMoved.emit(new_bboxs = new_bboxs,  
++                                      new_areas_cats = new_areas_cats, 
++                                      old_areas_cats = old_areas_cats, 
++                                      old_bboxs = old_bboxs)
++
+         return moved
+ 
+     def AddVertex(self, coords):
+@@ -681,6 +930,10 @@
+             self._error.ReadLine(line)
+             return -1
+         
++        if self.emit_signals:
++            old_bboxs = [self._getBbox(line)]
++            old_areas_cats = [self._getLineAreasCategories(line)]
++
+         # build feature geometry
+         Vect_reset_line(self.poPoints)
+         for p in coords:
+@@ -696,6 +949,9 @@
+         
+         newline = Vect_rewrite_line(self.poMapInfo, line, ltype,
+                                     self.poPoints, self.poCats)
++        if newline > 0 and self.emit_signals:
++            new_geom = [self._getBbox(newline)]
++            new_areas_cats = [self._getLineAreasCategories(newline)]
+         
+         if newline > 0 and self._settings['breakLines']:
+             self._breakLineAtIntersection(newline, None)
+@@ -703,7 +959,13 @@
+         if newline > 0:
+             self._addChangeset()
+             self.toolbar.EnableUndo()
+-        
++    
++            if self.emit_signals:
++                self.lineEdited.emit(old_bboxs = old_bboxs, 
++                                     old_areas_cats = old_areas_cats, 
++                                     new_bboxs = new_bboxs, 
++                                     new_areas_cats = new_areas_cats)
++
+         return newline
+ 
+     def FlipLine(self):
+@@ -1514,6 +1776,16 @@
+             return 0
+         
+         poList  = self._display.GetSelectedIList()
++
++        if self.emit_signals:
++            cList = poList.contents
++            
++            old_bboxs = [self._getBbox(cList.value[0])]
++            old_areas_cats = [self._getLineAreasCategories(cList.value[0])]
++
++            Vect_set_updated(self.poMapInfo, 1)
++            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
++
+         Vect_reset_line(self.poPoints)
+         Vect_append_point(self.poPoints, coords[0], coords[1], 0.0)
+         
+@@ -1525,15 +1797,35 @@
+         else:
+             ret = Vedit_remove_vertex(self.poMapInfo, poList,
+                                       self.poPoints, thresh)
++
+         Vect_destroy_list(poList)
++
++        if ret > 0 and self.emit_signals:
++            new_bboxs = []
++            new_areas_cats = []
++
++            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
++            for i in range(n_up_lines_old, n_up_lines):
++                new_id = Vect_get_updated_line(self.poMapInfo, i)
++                new_areas_cats.append(self._getLineAreasCategories(new_id))
++                new_bboxs.append(self._getBbox(new_id))
+         
+         if not add and ret > 0 and self._settings['breakLines']:
+             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
+                                           None)
+-        
++
+         if ret > 0:
+             self._addChangeset()
+-                
++
++        if ret > 0 and self.emit_signals:
++            if add:
++                self.vertexAdded.emit(old_bboxs = old_bboxs, new_bboxs = new_bboxs)
++            else:
++                self.vertexRemoved.emit(old_bboxs = old_bboxs, 
++                                        new_bboxs = new_bboxs,
++                                        old_areas_cats = old_areas_cats,
++                                        new_areas_cats = new_areas_cats)
++
+         return 1
+     
+     def GetLineCats(self, line):
+Index: gui/wxpython/vdigit/toolbars.py
+===================================================================
+--- gui/wxpython/vdigit/toolbars.py	(revision 57633)
++++ gui/wxpython/vdigit/toolbars.py	(working copy)
+@@ -17,6 +17,7 @@
+ import wx
+ 
+ from grass.script import core as grass
++from grass.pydispatch.signal import Signal
+ 
+ from gui_core.toolbars  import BaseToolbar, BaseIcons
+ from gui_core.dialogs   import CreateNewVector
+@@ -42,6 +43,8 @@
+         self.digit         = None
+         self._giface       = giface
+         
++        self.editingStarted = Signal("VDigitToolbar.editingStarted")
++
+         # currently selected map layer for editing (reference to MapLayer instance)
+         self.mapLayer = None
+         # list of vector layers from Layer Manager (only in the current mapset)
+@@ -860,6 +863,7 @@
+             alpha = int(opacity * 255)
+             self.digit.GetDisplay().UpdateSettings(alpha = alpha)
+         
++        self.editingStarted.emit(vectMap = mapLayer.GetName(), digit = self.digit)
+         return True
+ 
+     def StopEditing(self):
+Index: gui/wxpython/vnet/toolbars.py
+===================================================================
+--- gui/wxpython/vnet/toolbars.py	(revision 57633)
++++ gui/wxpython/vnet/toolbars.py	(working copy)
+@@ -19,9 +19,9 @@
+ 
+ import wx
+ 
+-from icon              import MetaIcon
++from icons.icon import MetaIcon
+ from gui_core.toolbars import BaseToolbar, BaseIcons
+-from core.gcmd         import RunCommand
++from core.gcmd import RunCommand
+ from core.utils import _
+ 
+ class PointListToolbar(BaseToolbar):
+Index: gui/wxpython/Makefile
+===================================================================
+--- gui/wxpython/Makefile	(revision 57633)
++++ gui/wxpython/Makefile	(working copy)
+@@ -13,7 +13,7 @@
+ 	$(wildcard animation/* core/*.py dbmgr/* gcp/*.py gmodeler/* \
+ 	gui_core/*.py iclass/* lmgr/*.py location_wizard/*.py mapwin/*.py mapdisp/*.py \
+ 	mapswipe/* modules/*.py nviz/*.py psmap/* rlisetup/* timeline/* vdigit/* \
+-	vnet/*.py web_services/*.py wxplot/*.py) \
++	vnet/*.py web_services/*.py wxplot/*.py scatt_plot/*.py) \
+ 	gis_set.py gis_set_error.py wxgui.py README
+ 
+ DSTFILES := $(patsubst %,$(ETCDIR)/%,$(SRCFILES)) \
+@@ -21,8 +21,9 @@
+ 
+ PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,animation core dbmgr gcp gmodeler \
+ 	gui_core iclass lmgr location_wizard mapwin mapdisp modules nviz psmap \
+-	mapswipe vdigit wxplot web_services rlisetup vnet timeline)
++	mapswipe vdigit wxplot web_services rlisetup vnet timeline scatt_plot)
+ 
++
+ DSTDIRS := $(patsubst %,$(ETCDIR)/%,icons scripts xml)
+ 
+ default: $(DSTFILES)
+Index: gui/wxpython/iclass/dialogs.py
+===================================================================
+--- gui/wxpython/iclass/dialogs.py	(revision 57633)
++++ gui/wxpython/iclass/dialogs.py	(working copy)
+@@ -333,13 +333,19 @@
+         toolbar.SetCategories(catNames = catNames, catIdx = cats)
+         if name in catNames:
+             toolbar.choice.SetStringSelection(name)
++            cat = toolbar.GetSelectedCategoryIdx()
+         elif catNames:
+             toolbar.choice.SetSelection(0)
+-            
++            cat = toolbar.GetSelectedCategoryIdx()
++        else:
++            cat = None
++
+         if toolbar.choice.IsEmpty():
+             toolbar.EnableControls(False)
+         else:
+             toolbar.EnableControls(True)
++
++        self.mapWindow.CategoryChanged(cat)
+         # don't forget to update maps, histo, ...
+         
+     def GetSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
+Index: gui/wxpython/iclass/toolbars.py
+===================================================================
+--- gui/wxpython/iclass/toolbars.py	(revision 57633)
++++ gui/wxpython/iclass/toolbars.py	(working copy)
+@@ -46,9 +46,7 @@
+         'importAreas' : MetaIcon(img = 'layer-import',
+                             label = _('Import training areas from vector map')),
+         'addRgb' : MetaIcon(img = 'layer-rgb-add',
+-                            label = _('Add RGB map layer')),
+-        'scatt_plot'    : MetaIcon(img = 'layer-raster-analyze',
+-                                   label = _('Open Scatter Plot Tool (EXPERIMENTAL GSoC 2013)')),
++                            label = _('Add RGB map layer'))
+         }
+         
+ class IClassMapToolbar(BaseToolbar):
+@@ -117,10 +115,7 @@
+                                      ("zoomBack", icons["zoomBack"],
+                                       self.parent.OnZoomBack),
+                                      ("zoomToMap", icons["zoomExtent"],
+-                                      self.parent.OnZoomToMap),
+-                                     (None, ),
+-                                     ("scatt_plot", iClassIcons["scatt_plot"],
+-                                      self.parent.OnScatterplot)
++                                      self.parent.OnZoomToMap)
+                                     ))
+ class IClassToolbar(BaseToolbar):
+     """!IClass toolbar
+@@ -156,7 +151,7 @@
+         """!Toolbar data"""
+         icons = iClassIcons
+         return self._getToolbarData((("selectGroup", icons['selectGroup'],
+-                                      self.parent.OnAddBands),
++                                      lambda event : self.parent.AddBands()),
+                                       (None, ),
+                                       ("classManager", icons['classManager'],
+                                       self.parent.OnCategoryManager),
+Index: gui/wxpython/iclass/frame.py
+===================================================================
+--- gui/wxpython/iclass/frame.py	(revision 57633)
++++ gui/wxpython/iclass/frame.py	(working copy)
+@@ -64,6 +64,8 @@
+                                IClassExportAreasDialog, IClassMapDialog
+ from iclass.plots       import PlotPanel
+ 
++from grass.pydispatch.signal import Signal
++
+ class IClassMapFrame(DoubleMapFrame):
+     """! wxIClass main frame
+     
+@@ -114,6 +116,10 @@
+             lambda:
+             self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
+         self.SetSize(size)
++
++        self.groupSet = Signal("IClassMapFrame.groupSet")
++        self.categoryChanged = Signal('IClassMapFrame.categoryChanged')
++
+         #
+         # Add toolbars
+         #
+@@ -177,7 +183,7 @@
+         self.dialogs['category']   = None
+         
+         # PyPlot init
+-        self.plotPanel = PlotPanel(self, stats_data = self.stats_data)
++        self.plotPanel = PlotPanel(self, giface = self._giface, stats_data = self.stats_data)
+                                    
+         self._addPanes()
+         self._mgr.Update()
+@@ -237,7 +243,7 @@
+             return False
+         
+         return vectorName
+-        
++    
+     def RemoveTempVector(self):
+         """!Removes temporary vector map with training areas"""
+         ret = RunCommand(prog = 'g.remove',
+@@ -334,11 +340,12 @@
+             self._addPaneMapWindow(name = 'preview')
+             self._addPaneToolbar(name = 'iClassTrainingMapManager')
+             self._addPaneMapWindow(name = 'training')
+-        
++
++        self._mgr.SetDockSizeConstraint(0.5, 0.5) 
+         self._mgr.AddPane(self.plotPanel, wx.aui.AuiPaneInfo().
+                   Name("plots").Caption(_("Plots")).
+                   Dockable(False).Floatable(False).CloseButton(False).
+-                  Left().Layer(1).BestSize((400, -1)))
++                  Left().Layer(1).BestSize((300, -1)))
+         
+     def _addPaneToolbar(self, name):
+         if name == 'iClassPreviewMapManager':
+@@ -477,21 +484,47 @@
+         
+         self.Render(self.GetFirstWindow())
+         
+-    def OnAddBands(self, event):
++    def AddBands(self):
+         """!Add imagery group"""
+         dlg = IClassGroupDialog(self, group = self.group)
+-        if dlg.ShowModal() == wx.ID_OK:
+-            self.SetGroup(dlg.GetGroup())
++        
++        while True:
++            if dlg.ShowModal() == wx.ID_OK:
++                if self.SetGroup(dlg.GetGroup()):
++                    break
++            else: 
++                break
++        
+         dlg.Destroy()
+         
+     def SetGroup(self, name):
+         """!Set imagery group"""
+         group = grass.find_file(name = name, element = 'group')
+         if group['name']:
++            if not self.GroupData(group['name']):
++                GError(_("No data found in group <%s>.\n" \
++                         "Please create subgroup with same name as group and add the data there.") \
++                           % name, parent = self)
++                return False
+             self.group = group['name']
++            self.groupSet.emit(group = group['name'])
+         else:
+             GError(_("Group <%s> not found") % name, parent = self)
+-    
++            return False
++
++        return True
++
++    def GroupData(self, group):
++        res = RunCommand('i.group',
++                         flags = 'g',
++                         group = group, subgroup = group,
++                         read = True).strip()
++        bands = None
++        if res.split('\n')[0]:
++            bands = res.split('\n')
++            
++        return bands
++
+     def OnImportAreas(self, event):
+         """!Import training areas"""
+         # check if we have any changes
+@@ -768,17 +801,20 @@
+         
+         Updates number of stddev, histograms, layer in preview display. 
+         """
+-        stat = self.stats_data.GetStatistics(currentCat)
+-        nstd = stat.nstd
+-        self.toolbars['iClass'].UpdateStddev(nstd)
+-        
+-        self.plotPanel.UpdateCategory(currentCat)
+-        self.plotPanel.OnPlotTypeSelected(None)
++        if currentCat:
++          stat = self.stats_data.GetStatistics(currentCat)
++          nstd = stat.nstd
++          self.toolbars['iClass'].UpdateStddev(nstd)
++          
++          self.plotPanel.UpdateCategory(currentCat)
++          self.plotPanel.OnPlotTypeSelected(None)
+                                    
+-        name = stat.rasterName
+-        name = self.previewMapManager.GetAlias(name)
+-        if name:
+-            self.previewMapManager.SelectLayer(name)
++          name = stat.rasterName
++          name = self.previewMapManager.GetAlias(name)
++          if name:
++              self.previewMapManager.SelectLayer(name)
++
++        self.categoryChanged.emit(cat = currentCat)
+         
+     def DeleteAreas(self, cats):
+         """!Removes all training areas of given categories
+@@ -805,12 +841,12 @@
+     def UpdateRasterName(self, newName, cat):
+         """!Update alias of raster map when category name is changed"""
+         origName = self.stats_data.GetStatistics(cat).rasterName
+-        self.previewMapManager.SetAlias(origName, newName)
++        self.previewMapManager.SetAlias(origName, self._addSuffix(newName))
+         
+     def StddevChanged(self, cat, nstd):
+         """!Standard deviation multiplier changed, rerender map, histograms"""
+         stat = self.stats_data.GetStatistics(cat)
+-        stat.nstd = nstd
++        stat.SetStatistics({"nstd" : nstd})
+         
+         if not stat.IsReady():
+             return
+@@ -923,7 +959,7 @@
+                 
+                 self.ConvertToNull(name = stats.rasterName)
+                 self.previewMapManager.AddLayer(name = stats.rasterName,
+-                                                alias = stats.name, resultsLayer = True)
++                                                alias = self._addSuffix(stats.name), resultsLayer = True)
+                 # write statistics
+                 I_iclass_add_signature(self.signatures, statistics)
+                 
+@@ -936,7 +972,11 @@
+         
+         self.UpdateChangeState(changes = False)
+         return True
+-        
++
++    def _addSuffix(self, name):
++        suffix = _('results')
++        return '_'.join((name, suffix))
++
+     def OnSaveSigFile(self, event):
+         """!Asks for signature file name and saves it."""
+         if not self.group:
+@@ -1105,27 +1145,13 @@
+         self.GetFirstWindow().SetModePointer()
+         self.GetSecondWindow().SetModePointer()
+ 
+-    def OnScatterplot(self, event):
+-        """!Init interactive scatterplot tools
+-        """
+-        if self.dialogs['scatt_plot']:
+-            self.dialogs['scatt_plot'].Raise()
+-            return
++    def GetMapManagers(self):
++      """!Get map managers of wxIClass 
+ 
+-        try:
+-          from scatt_plot.dialogs import ScattPlotMainDialog
+-        except:
+-          GError(parent  = self, message = _("The Scatter Plot Tool is not installed."))
+-          return
++      @return trainingMapManager, previewMapManager 
++      """
++      return self.trainingMapManager, self.previewMapManager
+ 
+-        self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface, iclass_mapwin = self.GetFirstWindow())
+-
+-        scatt_mgr = self.dialogs['scatt_plot'].GetScattMgr()
+-        scatt_mgr.DigitDataChanged(self.toolbars['vdigit'].mapLayer.GetName(), self.GetFirstWindow().GetDigit())
+-
+-        self.dialogs['scatt_plot'].CenterOnScreen()
+-        self.dialogs['scatt_plot'].Show()
+-
+ class MapManager:
+     """! Class for managing map renderer.
+     
+@@ -1168,7 +1194,6 @@
+         self.frame.Render(self.mapWindow)
+         
+         if alias is not None:
+-            alias = self._addSuffix(alias)
+             self.layerName[alias] = name
+             name = alias
+         else:
+@@ -1225,7 +1250,11 @@
+                 self.toolbar.choice.SetSelection(0)
+         
+         self.frame.Render(self.mapWindow)
+-        
++    
++    def Render(self):
++        """@todo giface shoud be used instead of this method"""
++        self.frame.Render(self.mapWindow)
++
+     def RemoveLayer(self, name, idx):
+         """!Removes layer from Map and update toolbar"""
+         name = self.layerName[name]
+@@ -1281,11 +1310,7 @@
+     def _changeOpacity(self, layer, opacity):
+         self.map.ChangeOpacity(layer=layer, opacity=opacity)
+         self.frame.Render(self.mapWindow)
+-        
+-    def _addSuffix(self, name):
+-        suffix = _('results')
+-        return '_'.join((name, suffix))
+-        
++                
+     def GetAlias(self, name):
+         """!Returns alias for layer"""
+         name =  [k for k, v in self.layerName.iteritems() if v == name]
+@@ -1296,11 +1321,11 @@
+     def SetAlias(self, original, alias):
+         name = self.GetAlias(original)
+         if name:
+-            self.layerName[self._addSuffix(alias)] = original
++            self.layerName[alias] = original
+             del self.layerName[name]
+             idx = self.toolbar.choice.FindString(name)
+             if idx != wx.NOT_FOUND:
+-                self.toolbar.choice.SetString(idx, self._addSuffix(alias))
++                self.toolbar.choice.SetString(idx, alias)
+ 
+ def test():
+     import core.render as render
+Index: gui/wxpython/iclass/plots.py
+===================================================================
+--- gui/wxpython/iclass/plots.py	(revision 57633)
++++ gui/wxpython/iclass/plots.py	(working copy)
+@@ -19,6 +19,7 @@
+ import wx.lib.plot as plot
+ import wx.lib.scrolledpanel as scrolled
+ from core.utils import _
++from core.gcmd import GError
+ 
+ class PlotPanel(scrolled.ScrolledPanel):
+     """!Panel for drawing multiple plots.
+@@ -28,7 +29,7 @@
+     for each band and for one category. Coincidence plots show min max range
+     of classes for each band.
+     """
+-    def __init__(self, parent, stats_data):
++    def __init__(self, parent, giface, stats_data):
+         scrolled.ScrolledPanel.__init__(self, parent)
+         
+         self.SetupScrolling(scroll_x = False, scroll_y = True)
+@@ -38,26 +39,71 @@
+         self.stats_data = stats_data
+         self.currentCat = None
+         
++        self._giface = giface
++
+         self.mainSizer = wx.BoxSizer(wx.VERTICAL)
+-        
++
+         self._createControlPanel()
+-        
++        self._createPlotPanel()
++        self._createScatterPlotPanel()
++
+         self.SetSizer(self.mainSizer)
+         self.mainSizer.Fit(self)
+         self.Layout()
+-        
++
++    def _createPlotPanel(self):
++
++        self.canvasPanel = wx.Panel(parent=self)
++        self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
++        self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
++        self.canvasPanel.SetSizer(self.canvasSizer)
++
+     def _createControlPanel(self):
+         self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
+                                      choices = [_("Histograms"),
+-                                                _("Coincident plots")])
++                                                _("Coincident plots"),
++                                                _("Scatter plots")])
+         self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
+         self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
+-        
++    
++    def _createScatterPlotPanel(self):
++        """!Init interactive scatterplot tools
++        """
++        try:
++            from scatt_plot.frame import IClassScatterPlotsPanel
++            self.scatt_plot_panel = IClassScatterPlotsPanel(parent=self, 
++                                                            giface=self._giface, 
++                                                            iclass_mapwin = self.parent.GetFirstWindow())
++            self.mainSizer.Add(self.scatt_plot_panel, proportion = 1, flag = wx.EXPAND, border = 0)
++            self.scatt_plot_panel.Hide()
++        except ImportError as e:#TODO
++            self.scatt_error = _("Scatter plot functionality is disabled. Reason:\n" \
++                                 "Unable to import packages needed for scatter plot.\n%s" % e)
++            GError(self.scatt_error)
++            self.scatt_plot_panel = None
++
+     def OnPlotTypeSelected(self, event):
+         """!Plot type selected"""
++
++        if self.plotSwitch.GetSelection() in [0, 1]:
++            self.SetupScrolling(scroll_x = False, scroll_y = True)
++            if self.scatt_plot_panel:
++                self.scatt_plot_panel.Hide()
++            self.canvasPanel.Show()
++            self.Layout()
++
++        elif self.plotSwitch.GetSelection() == 2:
++            self.SetupScrolling(scroll_x = False, scroll_y = False)
++            if self.scatt_plot_panel:
++                self.scatt_plot_panel.Show()
++            else:
++                GError(self.scatt_error)
++            self.canvasPanel.Hide()
++            self.Layout()
++
+         if self.currentCat is None:
+             return
+-        
++
+         if self.plotSwitch.GetSelection() == 0:
+             stat = self.stats_data.GetStatistics(self.currentCat)
+             if not stat.IsReady():
+@@ -66,7 +112,10 @@
+             self.DrawHistograms(stat)
+         else:
+             self.DrawCoincidencePlots()
+-            
++
++        self.Layout()
++
++
+     def StddevChanged(self):
+         """!Standard deviation multiplier changed, redraw histograms"""
+         if self.plotSwitch.GetSelection() == 0:
+@@ -89,7 +138,7 @@
+             panel.Destroy()
+             
+         self.canvasList = []
+-            
++
+     def ClearPlots(self):
+         """!Clears plot canvases"""
+         for bandIdx in range(len(self.bandList)):
+@@ -104,15 +153,15 @@
+     def CreatePlotCanvases(self):
+         """!Create plot canvases according to the number of bands"""
+         for band in self.bandList:
+-            canvas = plot.PlotCanvas(self)
++            canvas = plot.PlotCanvas(self.canvasPanel)
+             canvas.SetMinSize((-1, 140))
+             canvas.SetFontSizeTitle(10)
+             canvas.SetFontSizeAxis(8)
+             self.canvasList.append(canvas)
+             
+-            self.mainSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
+-
+-        self.SetVirtualSize(self.GetBestVirtualSize()) 
++            self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
++        
++        self.SetVirtualSize(self.GetBestVirtualSize())
+         self.Layout()
+         
+     def UpdatePlots(self, group, currentCat, stats_data):
+@@ -138,7 +187,7 @@
+         
+     def UpdateCategory(self, cat):
+         self.currentCat = cat
+-        
++    
+     def DrawCoincidencePlots(self):
+         """!Draw coincidence plots"""
+         for bandIdx in range(len(self.bandList)):
+Index: gui/wxpython/scatt_plot/gthreading.py
+===================================================================
+--- gui/wxpython/scatt_plot/gthreading.py	(revision 0)
++++ gui/wxpython/scatt_plot/gthreading.py	(working copy)
+@@ -0,0 +1,134 @@
++"""!
++ at package scatt_plot.gthreading
++
++Classes:
++
++(C) 2013 by the GRASS Development Team
++
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
++
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++
++import os
++import sys
++import time
++import threading
++import Queue
++
++import wx
++from core.gconsole import wxCmdRun, wxCmdDone, wxCmdPrepare
++
++class gThread(threading.Thread):
++    """!Thread for GRASS commands"""
++    requestId = 0
++
++    def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
++        """!
++        @param receiver event receiver (used in PostEvent)
++        """
++        threading.Thread.__init__(self, **kwds)
++
++        if requestQ is None:
++            self.requestQ = Queue.Queue()
++        else:
++            self.requestQ = requestQ
++
++        if resultQ is None:
++            self.resultQ = Queue.Queue()
++        else:
++            self.resultQ = resultQ
++
++        self.setDaemon(True)
++
++        self.receiver = receiver
++        self._want_abort_all = False
++
++        self.start()
++
++    def Run(self, *args, **kwds):
++        """!Run command in queue
++
++        @param args unnamed command arguments
++        @param kwds named command arguments
++
++        @return request id in queue
++        """
++        gThread.requestId += 1
++        self.requestQ.put((gThread.requestId, args, kwds))
++
++        return gThread.requestId
++
++    def GetId(self):
++         """!Get id for next command"""
++         return gThread.requestId + 1
++
++    def SetId(self, id):
++        """!Set starting id"""
++        gThread.requestId = id
++
++    def run(self):
++        os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
++        while True:
++            requestId, args, kwds = self.requestQ.get()
++            for key in ('callable', 'onDone', 'onPrepare', 'userdata'):
++                if key in kwds:
++                    vars()[key] = kwds[key]
++                    del kwds[key]
++                else:
++                    vars()[key] = None
++
++            requestTime = time.time()
++
++            #if self._want_abort_all and self.requestCmd is not None:
++            #    self.requestCmd.abort()
++            #    if self.requestQ.empty():
++            #        self._want_abort_all = False
++
++            # prepare
++            if self.receiver:
++                event = wxCmdPrepare(type = 'method',
++                                     time=requestTime,
++                                     pid=requestId)
++
++                wx.PostEvent(self.receiver, event)
++
++                # run command
++                event = wxCmdRun(type = 'method',
++                                 pid=requestId)
++
++                wx.PostEvent(self.receiver, event)
++
++            time.sleep(.1)
++
++            ret = None
++            exception = None
++            
++            #to
++            #try:
++            ret = vars()['callable'](*args, **kwds)
++            #except Exception as e:
++            #    exception  = e;
++
++            self.resultQ.put((requestId, ret))
++
++            time.sleep(.1)
++
++            if self.receiver:
++                event = wxCmdDone(kwds=kwds,
++                                  args=args, #TODO expand args to kwds
++                                  ret=ret,
++                                  exception=exception,
++                                  userdata=vars()['userdata'],
++                                  pid=requestId)
++
++                # send event
++                wx.PostEvent(self.receiver, event)
++
++    def abort(self, abortall=True):
++        """!Abort command(s)"""
++        if abortall:
++            self._want_abort_all = True
++        if self.requestQ.empty():
++            self._want_abort_all = False
+\ No newline at end of file
+Index: gui/wxpython/scatt_plot/dialogs.py
+===================================================================
+--- gui/wxpython/scatt_plot/dialogs.py	(revision 0)
++++ gui/wxpython/scatt_plot/dialogs.py	(working copy)
+@@ -0,0 +1,249 @@
++"""!
++ at package scatt_plot.dialogs
++
++ at brief GUI.
++
++Classes:
++
++(C) 2013 by the GRASS Development Team
++
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
++
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++import os
++import sys
++
++import wx
++from scatt_plot.scatt_core import idBandsToidScatt
++from gui_core.gselect import Select
++
++import grass.script as grass
++
++from core import globalvar
++from core.gcmd import GError
++from core.settings import UserSettings
++
++class AddScattPlotDialog(wx.Dialog):
++
++    def __init__(self, parent, bands, id  = wx.ID_ANY):
++        
++        wx.Dialog.__init__(self, parent, title = ("Add scatter plot"), id = id)
++
++        self.bands = bands
++
++        self.x_band = None
++        self.y_band = None
++
++        self._createWidgets()
++
++    def _createWidgets(self):
++
++        self.labels = {}
++        self.params = {}
++
++        self.band_1_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("%s axis:" % "x"))
++
++        self.band_1_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
++                                     choices = self.bands,
++                                     style = wx.CB_READONLY, size = (350, 30))
++
++        self.band_2_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("%s axis:" % "y"))
++
++        self.band_2_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
++                                     choices = self.bands,
++                                     style = wx.CB_READONLY, size = (350, 30))
++
++        # buttons
++        self.btn_close = wx.Button(parent = self, id = wx.ID_CANCEL)
++        
++        self.btn_ok = wx.Button(parent = self, id = wx.ID_OK, label = _("&OK"))
++
++        self._layout()
++
++    def _layout(self):
++
++        border = wx.BoxSizer(wx.VERTICAL) 
++        dialogSizer = wx.BoxSizer(wx.VERTICAL)
++
++        regionSizer = wx.BoxSizer(wx.HORIZONTAL)
++
++        dialogSizer.Add(item = self._addSelectSizer(title = self.band_1_label, 
++                                                    sel = self.band_1_ch))
++
++        dialogSizer.Add(item = self._addSelectSizer(title = self.band_2_label, 
++                                                    sel = self.band_2_ch))
++
++        # buttons
++        self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
++
++        self.btnsizer.Add(item = self.btn_close, proportion = 0,
++                          flag = wx.ALL | wx.ALIGN_CENTER,
++                          border = 10)
++        
++        self.btnsizer.Add(item = self.btn_ok, proportion = 0,
++                          flag = wx.ALL | wx.ALIGN_CENTER,
++                          border = 10)
++
++        dialogSizer.Add(item = self.btnsizer, proportion = 0,
++                        flag = wx.ALIGN_CENTER)
++
++        border.Add(item = dialogSizer, proportion = 0,
++                   flag = wx.ALL, border = 5)
++
++        self.SetSizer(border)
++        self.Layout()
++        self.Fit()
++
++        # bindings
++        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
++        self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
++
++    def _addSelectSizer(self, title, sel): 
++        """!Helper layout function.
++        """
++        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
++
++        selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
++        selTitleSizer.Add(item = title, proportion = 1,
++                          flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
++
++        selSizer.Add(item = selTitleSizer, proportion = 0,
++                     flag = wx.EXPAND)
++
++        selSizer.Add(item = sel, proportion = 1,
++                     flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
++                     border = 5)
++
++        return selSizer
++
++    def OnClose(self, event):
++        """!Close dialog
++        """
++        if not self.IsModal():
++            self.Destroy()
++        event.Skip()
++
++    def OnOk(self, event):
++        """!
++        """
++        b_x = self.band_1_ch.GetSelection()
++        b_y = self.band_2_ch.GetSelection()
++
++        err = True
++
++        if b_x < 0 or b_y < 0:
++            GError(_("Select both x and y bands."))
++        elif b_y == b_x:
++            GError(_("Selected bands must be different."))
++        else:
++            err = False        
++
++        if err:
++            self.band_y = None
++            self.band_x = None
++            return
++
++        self.band_y = b_y
++        self.band_x = b_x
++
++        event.Skip()
++
++    def GetBands(self):
++        return (self.band_x, self.band_y)
++
++class ExportCategoryRaster(wx.Dialog):
++    def __init__(self, parent, title, rasterName = None, id = wx.ID_ANY,
++                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
++                 **kwargs):
++        """!Dialog for export of category raster.
++        
++        @param parent window
++        @param rasterName name of vector layer for export
++        @param title window title
++        """
++        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
++        
++        self.rasterName = rasterName
++        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
++        
++        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
++        self.btnOK     = wx.Button(parent = self.panel, id = wx.ID_OK)
++        self.btnOK.SetDefault()
++        self.btnOK.Enable(False)
++        self.btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
++        
++        self.__layout()
++        
++        self.vectorNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
++        self.OnTextChanged(None)
++        wx.CallAfter(self.vectorNameCtrl.SetFocus)
++
++    def OnTextChanged(self, event):
++        """!Name of new vector map given.
++        
++        Enable/diable OK button.
++        """
++        file = self.vectorNameCtrl.GetValue()
++        if len(file) > 0:
++            self.btnOK.Enable(True)
++        else:
++            self.btnOK.Enable(False)
++        
++    def __layout(self):
++        """!Do layout"""
++        sizer = wx.BoxSizer(wx.VERTICAL)
++        
++        dataSizer = wx.BoxSizer(wx.VERTICAL)
++        
++        dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
++                                           label = _("Enter name of new vector map:")),
++                      proportion = 0, flag = wx.ALL, border = 3)
++        self.vectorNameCtrl = Select(parent = self.panel, type = 'raster',
++                                     mapsets = [grass.gisenv()['MAPSET']],
++                                     size = globalvar.DIALOG_GSELECT_SIZE)
++        if self.rasterName:
++            self.vectorNameCtrl.SetValue(self.rasterName)
++        dataSizer.Add(item = self.vectorNameCtrl,
++                      proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
++        
++                      
++        # buttons
++        btnSizer = wx.StdDialogButtonSizer()
++        btnSizer.AddButton(self.btnCancel)
++        btnSizer.AddButton(self.btnOK)
++        btnSizer.Realize()
++        
++        sizer.Add(item = dataSizer, proportion = 1,
++                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
++        
++        sizer.Add(item = btnSizer, proportion = 0,
++                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
++        
++        self.panel.SetSizer(sizer)
++        sizer.Fit(self)
++        
++        self.SetMinSize(self.GetSize())
++        
++    def GetRasterName(self):
++        """!Returns vector name"""
++        return self.vectorNameCtrl.GetValue()
++
++    def OnOK(self, event):
++        """!Checks if map exists and can be overwritten."""
++        overwrite = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
++        rast_name = self.GetRasterName()
++        res = grass.find_file(rast_name, element = 'cell')
++        if res['fullname'] and overwrite is False:
++            qdlg = wx.MessageDialog(parent = self,
++                                        message = _("Raster map <%s> already exists."
++                                                    " Do you want to overwrite it?" % rast_name) ,
++                                        caption = _("Raster <%s> exists" % rast_name),
++                                        style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
++            if qdlg.ShowModal() == wx.ID_YES:
++                event.Skip()
++            qdlg.Destroy()
++        else:
++            event.Skip()
++            
+\ No newline at end of file
+Index: gui/wxpython/scatt_plot/toolbars.py
+===================================================================
+--- gui/wxpython/scatt_plot/toolbars.py	(revision 0)
++++ gui/wxpython/scatt_plot/toolbars.py	(working copy)
+@@ -0,0 +1,216 @@
++"""!
++ at package scatt_plot.toolbars
++
++ at brief Scatter plot - toolbars
++
++Classes:
++ - toolbars::MainToolbar
++
++(C) 2013 by the GRASS Development Team
++
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
++
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++import wx
++
++from icons.icon import MetaIcon
++from gui_core.toolbars import BaseToolbar, BaseIcons
++from core.gcmd import RunCommand
++from core.gcmd import GException, GError, RunCommand
++from scatt_plot.scatt_core import idBandsToidScatt
++
++
++class MainToolbar(BaseToolbar):
++    """!Main toolbar
++    """
++    def __init__(self, parent, scatt_mgr):
++        BaseToolbar.__init__(self, parent)
++        self.scatt_mgr = scatt_mgr
++
++        self.InitToolbar(self._toolbarData())
++        
++        # realize the toolbar
++        self.Realize()
++        self.scatt_mgr.modeSet.connect(self.ModeSet)
++
++    def _toolbarData(self):
++
++        icons = {
++                'settings'   : BaseIcons['settings'].SetLabel( _('Ssettings')),
++                'help'       : MetaIcon(img = 'help',
++                                         label = _('Show manual')),
++                'add_scatt_pl'  : MetaIcon(img = 'layer-raster-analyze',
++                                            label = _('Add scatter plot')),
++                'selCatPol'  : MetaIcon(img = 'polygon',
++                                      label = _('Select area with polygon')),
++                'pan'        : MetaIcon(img = 'pan',
++                                         label = _('Pan mode for scatter plots')),
++                'zoomIn'     : MetaIcon(img = 'zoom-in',
++                                        label = _('Zoom mode for scatter plots (left mouse button, wheel)')),
++                'zoomExtent' : MetaIcon(img = 'zoom-extent',
++                                       label = _('Zoom to scatter plot data extend mode (click on scatter plot for zooming to extend)')),
++                'cats_mgr' : MetaIcon(img = 'table-manager',
++                                          label = _('Show/hide class manager'))
++                }
++
++        return self._getToolbarData((
++                                     ('add_scatt', icons["add_scatt_pl"],
++                                     lambda event : self.scatt_mgr.AddScattPlot()),
++                                     (None, ),
++                                     ("cats_mgr", icons['cats_mgr'],
++                                     lambda event: self.parent.ShowCategoryPanel(event.Checked()), wx.ITEM_CHECK),
++                                     (None, ),
++                                     ("pan", icons["pan"],
++                                     lambda event: self.SetPloltsMode(event, 'pan'),
++                                      wx.ITEM_CHECK),
++                                     ("zoom", icons["zoomIn"],
++                                     lambda event: self.SetPloltsMode(event, 'zoom'),
++                                      wx.ITEM_CHECK),
++                                     ("zoom_extend", icons["zoomExtent"],
++                                     lambda event: self.SetPloltsMode(event, 'zoom_extend'),
++                                      wx.ITEM_CHECK),
++                                    (None, ),
++                                     ('sel_pol_mode', icons['selCatPol'],
++                                      self.ActivateSelectionPolygonMode,
++                                     wx.ITEM_CHECK)
++                                     #('settings', icon["settings"],
++                                     # self.parent.OnSettings),  
++                                     #('help', icons["help"],
++                                     # self.OnHelp),                    
++                                    ))
++
++    def GetToolId(self, toolName): #TODO can be useful in base
++        return vars(self)[toolName]            
++
++    def SetPloltsMode(self, event, tool_name):
++        self.scatt_mgr.modeSet.disconnect(self.ModeSet)
++        if event.Checked()  == True:
++            for i_tool_data in  self._data:
++                i_tool_name = i_tool_data[0]
++                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
++                    continue
++                if i_tool_name == tool_name:
++                    continue
++                i_tool_id = vars(self)[i_tool_name]
++                self.ToggleTool(i_tool_id, False)
++
++            self.scatt_mgr.SetPlotsMode(mode = tool_name)
++        else:
++            self.scatt_mgr.SetPlotsMode(mode = None)
++        self.scatt_mgr.modeSet.connect(self.ModeSet)
++
++    def ActivateSelectionPolygonMode(self, event):
++
++        activated = self.scatt_mgr.ActivateSelectionPolygonMode(event.Checked())
++        self.parent.ShowPlotEditingToolbar(activated)
++
++        i_tool_id = vars(self)['sel_pol_mode']
++        self.ToggleTool(i_tool_id, activated)
++
++    def ModeSet(self, mode):
++        self.UnsetMode()
++
++    def UnsetMode(self):
++        for i_tool_data in  self._data:
++                i_tool_name = i_tool_data[0]
++                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
++                    continue
++                i_tool_id = vars(self)[i_tool_name]
++                self.ToggleTool(i_tool_id, False)
++
++class EditingToolbar(BaseToolbar):
++    """!Main toolbar
++    """
++    def __init__(self, parent, scatt_mgr):
++        BaseToolbar.__init__(self, parent)
++        self.scatt_mgr = scatt_mgr
++
++        self.InitToolbar(self._toolbarData())
++        
++        # realize the toolbar
++        self.Realize()
++        self.scatt_mgr.modeSet.connect(self.ModeSet)
++
++    def _toolbarData(self):
++        """!Toolbar data
++        """
++        self.icons = {
++            'sel_add'         : MetaIcon(img = 'layer-add',
++                                         label = _('Include selected area to class.'),
++                                         desc = _('Include selected area to class.')),
++            'sel_remove'      : MetaIcon(img = 'layer-remove',
++                                         label = _('Exclude selected area from class.'),
++                                         desc = _('Exclude selected area from class.')),
++            'addVertex'       : MetaIcon(img = 'vertex-create',
++                                         label = _('Add new vertex'),
++                                         desc = _('Add new vertex to polygon boundary scatter plot')),
++            'editLine'        : MetaIcon(img = 'polygon-create',
++                                         label = _('Edit line/boundary'),
++                                         desc = _('Add new vertex between last and first points of the boundary')),
++            'moveVertex'      : MetaIcon(img = 'vertex-move',
++                                         label = _('Move vertex'),
++                                         desc = _('Move boundary vertex')),
++            'removeVertex'    : MetaIcon(img = 'vertex-delete',
++                                         label = _('Remove vertex'),
++                                         desc = _('Remove boundary vertex.')),
++            'delete'        : MetaIcon(img = 'polygon-delete',
++                                         label = _('Edit line/boundary'),
++                                         desc = _('Delete polygon')),
++            }
++
++        return self._getToolbarData((
++                                    ("sel_add", self.icons["sel_add"],
++                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
++                                     ("sel_remove", self.icons['sel_remove'],
++                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
++                                     (None, ),
++                                     ("add_vertex", self.icons["editLine"],
++                                     lambda event: self.SetMode(event, 'add_vertex'),
++                                     wx.ITEM_CHECK),
++                                     ("add_boundary_vertex", self.icons['addVertex'],
++                                     lambda event: self.SetMode(event, 'add_boundary_vertex'),
++                                     wx.ITEM_CHECK),
++                                     ("move_vertex", self.icons["moveVertex"],
++                                     lambda event: self.SetMode(event, 'move_vertex'),
++                                     wx.ITEM_CHECK),
++                                     ('delete_vertex', self.icons['removeVertex'],
++                                     lambda event: self.SetMode(event, 'delete_vertex'),
++                                     wx.ITEM_CHECK),
++                                     ('delete', self.icons['delete'],
++                                     lambda event: self.SetMode(event, 'delete'),
++                                     wx.ITEM_CHECK)
++                                    ))
++
++    def SetMode(self, event, tool_name):
++        self.scatt_mgr.modeSet.disconnect(self.ModeSet)
++        if event.Checked() == True:
++            for i_tool_data in  self._data:
++                i_tool_name = i_tool_data[0]
++                if not i_tool_name:
++                    continue
++                if i_tool_name == tool_name:
++                    continue
++                i_tool_id = vars(self)[i_tool_name]
++                self.ToggleTool(i_tool_id, False)
++            self.scatt_mgr.SetPlotsMode(tool_name)
++        else:
++            self.scatt_mgr.SetPlotsMode(None)
++        self.scatt_mgr.modeSet.connect(self.ModeSet)
++
++    def ModeSet(self, mode):
++
++        if mode in ['zoom', 'pan', 'zoom_extend', None]:
++            self.UnsetMode()
++
++    def UnsetMode(self):
++        for i_tool_data in  self._data:
++                i_tool_name = i_tool_data[0]
++                if not i_tool_name:
++                    continue
++                i_tool_id = vars(self)[i_tool_name]
++                self.ToggleTool(i_tool_id, False)
++
++    def GetToolId(self, toolName):
++        return vars(self)[toolName]            
+Index: gui/wxpython/scatt_plot/scatt_core.py
+===================================================================
+--- gui/wxpython/scatt_plot/scatt_core.py	(revision 0)
++++ gui/wxpython/scatt_plot/scatt_core.py	(working copy)
+@@ -0,0 +1,808 @@
++"""!
++ at package scatt_plot.scatt_plot
++
++ at brief Non GUI functions.
++
++Classes:
++
++(C) 2013 by the GRASS Development Team
++
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
++
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++import os
++import sys
++
++import time
++
++import numpy as np
++#TODO
++from matplotlib.path import Path 
++
++from math import sqrt, ceil, floor
++from copy import deepcopy
++from scipy.signal import convolve2d
++
++from core.gcmd import GException, GError, RunCommand
++
++import grass.script as grass
++
++from core_c import CreateCatRast, ComputeScatts, UpdateCatRast, \
++                   SC_SCATT_DATA, SC_SCATT_CONDITIONS
++
++class Core:
++    def __init__(self):
++        
++        self.an_data = AnalyzedData()
++
++        self.scatts_dt = ScattPlotsData(self.an_data)
++        self.scatt_conds_dt = ScattPlotsCondsData(self.an_data)
++
++        self.cat_rast_updater = CatRastUpdater(self.scatts_dt, self.an_data, self)
++
++    def SetData(self, bands):
++        self.an_data.Create(bands)
++
++        n_bands = len(self.GetBands())
++
++        self.scatts_dt.Create(n_bands)
++        self.scatt_conds_dt.Create(n_bands)
++
++    def AddCategory(self, cat_id):
++        self.scatts_dt.AddCategory(cat_id)
++        return self.scatt_conds_dt.AddCategory(cat_id)
++
++    def DeleteCategory(self, cat_id):
++        self.scatts_dt.DeleteCategory(cat_id)
++        self.scatt_conds_dt.DeleteCategory(cat_id)
++
++    def CleanUp(self):
++        self.scatts_dt.CleanUp()
++        self.scatt_conds_dt.CleanUp()
++
++    def GetBands(self):
++        return self.an_data.GetBands()
++
++    def GetScattsData(self):
++        return self.scatts_dt, self.scatt_conds_dt;
++
++    def GetRegion(self):
++        return self.an_data.GetRegion()
++
++    def GetCatRast(self, cat_id):
++        return self.scatts_dt.GetCatRast(cat_id)
++
++    def AddScattPlot(self, scatt_id):
++    
++        self.scatts_dt.AddScattPlot(scatt_id = scatt_id)
++
++        cats_ids = self.scatts_dt.GetCategories()
++        self.ComputeCatsScatts(cats_ids)
++
++
++    def SetEditCatData(self, cat_id, scatt_id, bbox, value):
++
++        if cat_id not in self.scatts_dt.GetCategories():
++            raise GException(_("Select category for editing."))
++
++        if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0:
++            return None
++
++        arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
++
++        for k, v in bbox.iteritems():
++            bbox[k] = self._validExtend(v)
++
++        arr[bbox['btm_y'] : bbox['up_y'], bbox['btm_x'] : bbox['up_x']] = value
++        #arr.flush()
++        #del arr
++
++        self.ComputeCatsScatts([cat_id])
++        #print "time"
++        #print time.clock() - start_time
++        return cat_id
++
++    def ComputeCatsScatts(self, cats_ids):
++
++        requested_dt = {}
++        requested_dt_conds = {}
++
++        for c in cats_ids:
++            requested_dt_conds[c] = self.scatt_conds_dt.GetCatScatts(c)
++            requested_dt[c] = self.scatts_dt.GetCatScatts(c)
++
++        scatt_conds = self.scatt_conds_dt.GetData(requested_dt_conds)
++        scatts = self.scatts_dt.GetData(requested_dt)
++
++        bands = self.an_data.GetBands()
++
++        cats_rasts = self.scatts_dt.GetCatsRasts()
++        cats_rasts_conds = self.scatts_dt.GetCatsRastsConds()
++
++        returncode, scatts = ComputeScatts(self.an_data.GetRegion(), scatt_conds, bands,
++                                           len(self.GetBands()), scatts, cats_rasts_conds, cats_rasts)
++
++        #print "ComputeScatts"
++        #print returncode
++        if returncode < 0:
++            GException(_("Computing of scatter plots failed."))
++        #self.scatts_dt.SetData(scatts)
++
++    def CatRastUpdater(self):
++        return self.cat_rast_updater
++    
++    def UpdateCategoryWithPolygons(self, cat_id, scatts_pols, value):
++        start_time = time.clock()
++
++        if cat_id not in self.scatts_dt.GetCategories():
++            raise GException(_("Select category for editing."))
++
++        for scatt_id, coords in scatts_pols.iteritems():
++
++            if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0:
++                return False
++
++            b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))
++
++            b1_info = self.an_data.GetBandInfo(b1)
++            b2_info = self.an_data.GetBandInfo(b2)
++
++            raster_pol = RasterizePolygon(coords, b1_info['range'], b2_info['range'])
++
++            raster_ind = np.where(raster_pol > 0) 
++            arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
++
++            arr[raster_ind] = value
++            #arr.flush()
++        
++        self.ComputeCatsScatts([cat_id])
++        return cat_id
++
++    def _validExtend(self, val):
++        #TODO do it general
++        if  val > 255:
++            val = 255
++        elif val < 0:
++            val = 0
++
++        return val
++
++class CatRastUpdater:
++
++    def __init__(self, scatts_dt, an_data, core):
++        self.scatts_dt = scatts_dt
++        self.an_data = an_data # TODO may be confusing
++        self.core = core
++        self.vectMap = None
++
++    def SetVectMap(self, vectMap):
++        self.vectMap = vectMap
++
++    def SynchWithMap(self):
++        #TODO possible optimization - bbox only of vertex and its two neighbours
++
++        region = self.an_data.GetRegion()
++
++        bbox = {}
++        bbox['maxx'] = region['e']
++        bbox['minx'] = region['w']
++        bbox['maxy'] = region['n']
++        bbox['miny'] = region['s']
++
++        updated_cats = []
++
++        for cat_id in self.scatts_dt.GetCategories():
++            if cat_id == 0:
++                continue
++            
++            cat = [{1 : [cat_id]}]
++            self._updateCatRast(bbox, cat, updated_cats)
++
++        return updated_cats
++
++    def EditedFeature(self, new_bboxs, new_areas_cats, old_bboxs, old_areas_cats):
++        #TODO possible optimization - bbox only of vertex and its two neighbours
++
++        bboxs = old_bboxs + new_bboxs
++        areas_cats = old_areas_cats + new_areas_cats 
++
++        updated_cats = []
++
++        for i in range(len(areas_cats)):
++            self._updateCatRast(bboxs[i], areas_cats[i], updated_cats)
++        
++        return updated_cats
++
++    def _updateCatRast(self, bbox, areas_cats, updated_cats):
++
++        rasterized_cats = []
++        for c in range(len(areas_cats)):
++
++            if not areas_cats[c]:
++                continue
++
++            layer = areas_cats[c].keys()[0]
++            cat =  areas_cats[c][layer][0]
++
++            if cat in rasterized_cats:
++                continue
++
++            rasterized_cats.append(cat)
++            updated_cats.append(cat)
++
++            grass_region = self._create_grass_region_env(bbox)
++
++            #TODO hack
++            patch_rast = "temp_scatt_patch"
++            self._rasterize(grass_region, layer, cat, patch_rast)
++
++            region = self.an_data.GetRegion()
++            ret = UpdateCatRast(patch_rast, region, self.scatts_dt.GetCatRastCond(cat))
++            if ret < 0:
++                GException(_("Patching category raster conditions file failed."))            
++            RunCommand("g.remove",
++                      rast = patch_rast)
++
++    def _rasterize(self, grass_region, layer, cat, out_rast):
++
++        #TODO different thread may be problem when user edits map
++        environs = os.environ.copy()
++        environs['GRASS_VECTOR_TEMPORARY'] = '1'
++
++        ret, text, msg = RunCommand("v.category",
++                                    input=self.vectMap,
++                                    getErrorMsg = True,
++                                    option='report',
++                                    read=True,
++                                    env=environs)
++
++        ret, text, msg = RunCommand("v.build",
++                                      map = self.vectMap,
++                                      getErrorMsg = True,
++                                      read = True,
++                                      env = environs)
++
++        if ret != 0:
++            GException(_("v.build failed:\n%s" % msg))
++
++        environs = os.environ.copy()
++        environs["GRASS_REGION"] = grass_region["GRASS_REGION"]
++        environs['GRASS_VECTOR_TEMPORARY'] = '1'
++
++        ret, text, msg = RunCommand("v.to.rast",
++                                    input = self.vectMap,
++                                    use = "cat",
++                                    layer = str(layer),
++                                    cat = str(cat),
++                                    output = out_rast,
++                                    getErrorMsg = True,
++                                    read = True,
++                                    overwrite = True,
++                                    env = environs)
++
++        if ret != 0:
++            GException(_("v.to.rast failed:\n%s" % msg))
++
++    def _create_grass_region_env(self, bbox):
++
++        region = self.an_data.GetRegion()
++        new_region = {}
++
++        if bbox["maxy"] <= region["s"]:
++            return 0
++        elif bbox["maxy"] >= region["n"]:
++            new_region["n"] = bbox["maxy"]
++        else:
++            new_region["n"] = ceil((bbox["maxy"] - region["s"]) / region["nsres"]) * region["nsres"] + region["s"]
++
++        if bbox["miny"] >= region["n"]:
++            return 0
++        elif bbox["miny"] <= region["s"]:
++            new_region["s"] = bbox["miny"]
++        else:
++            new_region["s"] = floor((bbox["miny"] - region["s"]) / region["nsres"]) * region["nsres"] + region["s"]
++
++        if bbox["maxx"] <= region["w"]:
++            return 0
++        elif bbox["maxx"] >= region["e"]:
++            new_region["e"] = bbox["maxx"]
++        else:
++            new_region["e"] = ceil((bbox["maxx"] - region["w"]) / region["ewres"]) * region["ewres"] + region["w"]
++
++        if bbox["minx"] >= region["e"]:
++            return 0
++        elif bbox["minx"] <= region["w"]:
++            new_region["w"] = bbox["minx"]
++        else:
++            new_region["w"] = floor((bbox["minx"] - region["w"]) / region["ewres"]) * region["ewres"] + region["w"]
++
++        #TODO check regions resolutin
++        new_region["nsres"] = region["nsres"]
++        new_region["ewres"] = region["ewres"]
++
++        return {"GRASS_REGION" :  grass.region_env(**new_region)}
++
++class AnalyzedData:
++
++    def __init__(self):
++        
++        self.bands = []
++        self.bands_info = {}
++
++        self.region = None
++
++    def GetRegion(self):
++        return self.region
++
++    def Create(self, bands):
++
++        self.bands = bands
++        self.region = None
++
++        ret, region, msg = RunCommand("g.region",
++                                      flags = "gp",
++                                      getErrorMsg = True,
++                                      read = True)
++
++        if  ret != 0:
++            raise GException("g.region failed:\n%s" % msg)
++
++
++        self.bands_info = {}
++        for b in bands:
++            self.bands_info[b] = self._getRasterInfo(b)
++            if self.bands_info[b]["datatype"] != "CELL":
++                raise GException(_("Raster <%s> is not <CELL> type.") % (b))
++            #TODO size of raster check
++
++        self.region = self._parseRegion(region)
++
++    def _getRasterInfo(self, rast):
++        """
++        """
++        ret, out, msg = RunCommand("r.info",
++                                    map = rast,
++                                    flags = "rg",
++                                    getErrorMsg = True,
++                                    read = True)
++
++        if  ret != 0:
++            raise GException("r.info failed:\n%s" % msg)
++
++        out = out.split("\n")
++        raster_info = {} 
++
++        for b in out:
++            if not b.strip():
++                continue
++            k, v = b.split("=")
++            if k == "datatype":
++                pass
++            elif k in ['rows', 'cols', 'cells', 'min', 'max']:
++                v = int(v)
++            else:
++                v = float(v)
++
++            raster_info[k] = v
++
++        raster_info['range'] = raster_info['max'] - raster_info['min'] + 1
++        return raster_info
++
++    def GetBands(self):
++        return self.bands
++
++    def GetBandInfo(self, band_id):
++        band = self.bands[band_id]
++        return self.bands_info[band]
++
++    def _parseRegion(self, region_str):
++
++        region = {}
++        region_str = region_str.splitlines()
++
++        for param in region_str:
++            k, v = param.split("=")
++            if k in ["rows", "cols", "cells"]:
++                v = int(v)
++            else:
++                v = float(v)
++            region[k] = v
++
++        return region
++
++class ScattPlotsCondsData:
++
++    def __init__(self, an_data):
++
++        self.an_data = an_data
++
++        #TODO
++        self.max_n_cats = 10
++    
++        self.dtype = 'uint8'
++        self.type = 1;
++        self.CleanUp()
++
++    def CleanUp(self):
++    
++        self.cats = {}
++
++        self.n_scatts = -1
++        self.n_bands = -1
++
++        for cat_id in self.cats.keys():
++            self.DeleteCategory(cat_id)
++
++    def Create(self, n_bands):
++
++        self.CleanUp()
++
++        self.n_scatts =  (n_bands - 1) * n_bands / 2;
++        self.n_bands = n_bands
++
++        self.AddCategory(cat_id = 0)
++
++    def AddCategory(self, cat_id):
++
++        if cat_id not in self.cats.keys():
++            self.cats[cat_id] = {}
++            return cat_id
++        return -1
++
++    def DeleteCategory(self, cat_id):
++
++        if cat_id not in self.cats.keys():
++            return False
++
++        for scatt in self.cats[cat_id].itervalues():
++            del scatt['np_vals']
++
++        del self.cats[cat_id]
++
++        return True
++
++    def GetCategories(self):
++        return self.cats.keys()
++
++    def GetCatScatts(self, cat_id):
++
++        if not self.cats.has_key(cat_id):
++            return False
++
++        return self.cats[cat_id].keys()
++
++
++    def AddScattPlot(self, cat_id, scatt_id):
++
++        if not self.cats.has_key(cat_id):
++            return -1
++
++        if self.cats[cat_id].has_key(scatt_id):
++            return 0
++
++        b_i = self.GetBandsInfo(scatt_id)
++
++        shape = (b_i['b2']['max'] - b_i['b2']['min'] + 1, b_i['b1']['max'] - b_i['b1']['min'] + 1)
++
++        np_vals = np.memmap(grass.tempfile(), dtype=self.dtype, mode='w+', shape = shape)
++
++        self.cats[cat_id][scatt_id] = {
++                                        'np_vals' : np_vals,
++                                      }
++
++        return 1
++
++    def GetBandsInfo(self, scatt_id):
++        b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))
++
++        b1_info = self.an_data.GetBandInfo(b1)
++        b2_info = self.an_data.GetBandInfo(b2)
++
++        bands_info = {'b1' : b1_info,
++                      'b2' : b2_info}
++
++        return bands_info
++
++    def DeleScattPlot(self, cat_id, scatt_id):
++
++        if not self.cats.has_key(cat_id):
++            return False
++
++        if not self.cats[cat_id].has_key(scatt_id):
++            return False
++
++        del self.cats[cat_id][scatt_id]
++        return True
++
++    def GetValuesArr(self, cat_id, scatt_id):
++
++        if not self.cats.has_key(cat_id):
++            return None
++
++        if not self.cats[cat_id].has_key(scatt_id):
++            return None
++
++        return self.cats[cat_id][scatt_id]['np_vals']
++
++    def GetData(self, requested_dt):
++        
++        cats = {}
++        for cat_id, scatt_ids in requested_dt.iteritems():
++            if not cats.has_key(cat_id):
++                cats[cat_id] = {}
++            for scatt_id in scatt_ids:
++                # if key is missing condition is always True (full scatter plor is computed)
++                if self.cats[cat_id].has_key(scatt_id):
++                    cats[cat_id][scatt_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
++                                              'bands_info' : self.GetBandsInfo(scatt_id)}
++                        
++        return cats
++
++    def SetData(self, cats):
++        
++        for cat_id, scatt_ids in cats.iteritems():            
++            for scatt_id in scatt_ids:
++                # if key is missing condition is always True (full scatter plor is computed)
++                if self.cats[cat_id].has_key(scatt_id):
++                    self.cats[cat_id][scatt_id]['np_vals'] = cats[cat_id][scatt_id]['np_vals']
++
++    def GetScatt(self, scatt_id, cats_ids = None):
++        scatts = {}
++        for cat_id in self.cats.iterkeys():
++            if cats_ids and cat_id not in cats_ids:
++                continue
++            if not self.cats[cat_id].has_key(scatt_id):
++                continue
++
++            scatts[cat_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
++                              'bands_info' : self.GetBandsInfo(scatt_id)}
++        return scatts
++
++                   
++class ScattPlotsData(ScattPlotsCondsData):
++
++    def __init__(self, an_data):
++
++        self.cats_rasts = {}
++        self.cats_rasts_conds = {}    
++        self.scatts_ids = []    
++
++        ScattPlotsCondsData.__init__(self, an_data)
++
++        self.dtype = 'uint32'
++
++        #TODO
++        self.type = 0
++
++    def AddCategory(self, cat_id):
++        cat_id = ScattPlotsCondsData.AddCategory(self, cat_id)
++        if cat_id < 0:
++            return cat_id
++
++        for scatt_id in self.scatts_ids:
++            ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
++
++        if cat_id == 0:
++            self.cats_rasts_conds[cat_id] = None
++            self.cats_rasts[cat_id] = None
++        else:
++            self.cats_rasts_conds[cat_id] = grass.tempfile()
++            self.cats_rasts[cat_id] = "temp_cat_rast_%d" % cat_id
++            region = self.an_data.GetRegion()
++            CreateCatRast(region, self.cats_rasts_conds[cat_id])
++
++        return cat_id
++
++    def DeleteCategory(self, cat_id):
++
++        ScattPlotsCondsData.DeleteCategory(self, cat_id)
++
++        grass.try_remove(self.cats_rasts_conds[cat_id])
++        del self.cats_rasts_conds[cat_id]
++
++        grass.try_remove(self.cats_rasts[cat_id])
++        del self.cats_rasts[cat_id]
++
++        return True
++
++    def AddScattPlot(self, scatt_id):
++        
++        if scatt_id in self.scatts_ids:
++            return False
++
++        self.scatts_ids.append(scatt_id)
++        for cat_id in self.cats.iterkeys():
++                ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
++                self.cats[cat_id][scatt_id]['ellipse'] = None
++
++        return True
++
++    def DeleteScatterPlot(self, scatt_id):
++        
++        if scatt_id not in self.scatts_ids:
++            return False
++
++        self.scatts_ids.remove(scatt_id)
++
++        for cat_id in self.cats.iterkeys():
++                ScattPlotsCondsData.DeleteScattPlot(self, cat_id, scatt_id)
++
++        return True
++
++    def GetEllipses(self, scatt_id, styles):
++        if scatt_id not in self.scatts_ids:
++            return False
++
++        scatts = {}
++        for cat_id in self.cats.iterkeys():
++            if cat_id == 0:
++                continue
++            nstd = styles[cat_id]['nstd']
++            scatts[cat_id] = self._getEllipse(cat_id, scatt_id, nstd)
++
++        return scatts
++
++    def _getEllipse(self, cat_id, scatt_id, nstd):
++        # Joe Kington
++        # http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals
++
++        data = np.copy(self.cats[cat_id][scatt_id]['np_vals'])
++
++        sel_pts = np.where(data > 0)
++
++        x = sel_pts[1]
++        y = sel_pts[0]
++
++        flatten_data = data.reshape([-1])
++        flatten_sel_pts = np.nonzero(flatten_data)
++        weights = flatten_data[flatten_sel_pts]
++        if len(weights) == 0:
++            return None
++
++        x_avg = np.average(x, weights=weights)
++        y_avg = np.average(y, weights=weights)
++        pos = np.array([x_avg, y_avg])
++
++        x_diff = (x - x_avg)
++        y_diff = (y - y_avg)
++        
++        x_diff = (x - x_avg) 
++        y_diff = (y - y_avg) 
++
++        diffs = x_diff * y_diff.T
++        cov = np.dot(diffs, weights) / (np.sum(weights) - 1)
++
++        diffs = x_diff * x_diff.T
++        var_x = np.dot(diffs, weights) /  (np.sum(weights) - 1)
++        
++        diffs = y_diff * y_diff.T
++        var_y = np.dot(diffs, weights) /  (np.sum(weights) - 1)
++
++        cov = np.array([[var_x, cov],[cov, var_y]])
++
++        def eigsorted(cov):
++            vals, vecs = np.linalg.eigh(cov)
++            order = vals.argsort()[::-1]
++            return vals[order], vecs[:,order]
++
++        vals, vecs = eigsorted(cov)
++        theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
++
++        # Width and height are "full" widths, not radius
++        width, height = 2 * nstd * np.sqrt(vals)
++
++        ellipse = {'pos' : pos, 
++                   'width' : width,
++                   'height' : height,
++                   'theta' : theta}
++
++        del data
++        del flatten_data
++        del flatten_sel_pts
++        del weights
++        del sel_pts
++        return ellipse
++
++    def CleanUp(self):
++
++        ScattPlotsCondsData.CleanUp(self)        
++        for tmp in self.cats_rasts_conds:
++            grass.try_remove(tmp) 
++        for tmp in self.cats_rasts:
++            grass.try_remove(tmp) 
++
++        self.cats_rasts = {}
++        self.cats_rasts_conds = {}
++
++
++    def GetCatRast(self, cat_id):
++        return self.cats_rasts[cat_id]
++
++    def GetCatRastCond(self, cat_id):
++        return self.cats_rasts_conds[cat_id]
++
++    def GetCatsRastsConds(self):
++        max_cat_id = max(self.cats_rasts_conds.keys())
++
++        cats_rasts_conds = [''] * (max_cat_id + 1)
++        for i_cat_id, i_rast in self.cats_rasts_conds.iteritems():
++            cats_rasts_conds[i_cat_id] = i_rast
++
++        return cats_rasts_conds
++
++    def GetCatsRasts(self):
++        max_cat_id = max(self.cats_rasts.keys())
++
++        cats_rasts = [''] * (max_cat_id + 1)
++        for i_cat_id, i_rast in self.cats_rasts.iteritems():
++            cats_rasts[i_cat_id] = i_rast
++
++        return cats_rasts
++
++
++def RasterizePolygon(pol, height, width):
++
++    # Joe Kington
++    # http://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask
++
++    #poly_verts = [(1,1), (1,4), (4,4),(4,1), (1,1)]
++
++    nx = width + 1
++    ny = height + 1
++
++    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
++    x, y = x.flatten(), y.flatten()
++
++    points = np.vstack((x,y)).T
++
++    p = Path(pol)
++    grid = p.contains_points(points)
++    grid = grid.reshape((ny,nx))
++
++    raster = np.zeros((height, width), dtype=np.uint8)#TODO bool
++
++    #TODO shift by 0.5
++    B = np.ones((2,2))/4
++    raster = convolve2d(grid, B, 'valid')
++
++
++    #TODO this part is very inefficient, replace it with better solution
++    #for (y, x), value in np.ndenumerate(grid):
++
++    #    if x >= width - 1: continue 
++    #    if y >= height - 1: continue
++
++    #    if grid[y, x]:
++    #        raster[y, x] = 1
++    #        raster[y + 1, x] = 1
++    #        raster[y, x + 1] = 1
++    #        raster[y + 1, x + 1] = 1
++
++    return raster
++
++#TODO move to utils?
++def idScattToidBands(scatt_id, n_bands):
++ 
++    n_b1 = n_bands - 1
++
++    band_1 = (int) ((2 * n_b1 + 1 - sqrt(((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2)
++
++    band_2 = scatt_id - (band_1 * (2 * n_b1 + 1) - band_1 * band_1) / 2 + band_1 + 1
++
++    return band_1, band_2
++
++def idBandsToidScatt(band_1_id, band_2_id, n_bands):
++
++    if band_2_id <  band_1_id:
++        tmp = band_1
++        band_1_id = band_2_id
++        band_2_id = tmp
++
++    n_b1 = n_bands - 1
++
++    scatt_id = (band_1_id * (2 * n_b1 + 1) - band_1_id * band_1_id) / 2 + band_2_id - band_1_id - 1
++
++    return scatt_id
++
 Index: gui/wxpython/scatt_plot/core_c.py
 ===================================================================
 --- gui/wxpython/scatt_plot/core_c.py	(revision 0)
 +++ gui/wxpython/scatt_plot/core_c.py	(working copy)
-@@ -0,0 +1,170 @@
+@@ -0,0 +1,203 @@
 +"""!
 + at package scatt_plot.scatt_plot
 +
@@ -150,7 +3899,40 @@
 +
 +from core.gcmd import GException
 +
++def ApplyColormap(vals, vals_mask, colmap, out_vals):
++    
++    c_uint8_p = POINTER(c_uint8)
++    c_double_p = POINTER(c_double)
 +
++
++    vals_p = vals.ctypes.data_as(c_uint8_p)
++    vals_mask_p = vals_mask.ctypes.data_as(c_uint8_p)
++    colmap_p = colmap.ctypes.data_as(c_uint8_p)
++    out_vals_p = out_vals.ctypes.data_as(c_uint8_p)
++
++    vals_size = vals.reshape((-1)).shape[0]
++    I_apply_colormap(vals_p, vals_mask_p, vals_size, colmap_p, out_vals_p)
++
++def MergeArrays(merged_arr, overlay_arr, alpha):
++    if merged_arr.shape != overlay_arr.shape:
++        GException("MergeArrays: merged_arr.shape != overlay_arr.shape")
++
++    c_uint8_p = POINTER(c_uint8)
++    merged_p = merged_arr.ctypes.data_as(c_uint8_p)
++    overlay_p = overlay_arr.ctypes.data_as(c_uint8_p)
++
++    I_merge_arrays(merged_p, overlay_p, merged_arr.shape[0], merged_arr.shape[1], alpha)
++
++def MergeArrays(merged_arr, overlay_arr, alpha):
++    if merged_arr.shape != overlay_arr.shape:
++        GException("MergeArrays: merged_arr.shape != overlay_arr.shape")
++
++    c_uint8_p = POINTER(c_uint8)
++    merged_p = merged_arr.ctypes.data_as(c_uint8_p)
++    overlay_p = overlay_arr.ctypes.data_as(c_uint8_p)
++
++    I_merge_arrays(merged_p, overlay_p, merged_arr.shape[0], merged_arr.shape[1], alpha)
++
 +def ComputeScatts(region, scatt_conds, bands, n_bands, scatts, cats_rasts_conds, cats_rasts):
 +
 +    q = Queue()
@@ -294,7 +4076,7 @@
 ===================================================================
 --- gui/wxpython/scatt_plot/frame.py	(revision 0)
 +++ gui/wxpython/scatt_plot/frame.py	(working copy)
-@@ -0,0 +1,582 @@
+@@ -0,0 +1,624 @@
 +"""!
 + at package scatt_plot.dialogs
 +
@@ -326,6 +4108,7 @@
 +from scatt_plot.toolbars import MainToolbar, EditingToolbar
 +from scatt_plot.scatt_core import idScattToidBands
 +from scatt_plot.plots import ScatterPlotWidget
++from vnet.dialogs import VnetStatusbar
 +
 +try:
 +    from agw import aui
@@ -352,21 +4135,46 @@
 +
 +        self.plot_panel = IClassPlotPanel(self, self.scatt_mgr)
 +
++        # statusbar
++        self.stPriors = {'high' : 5, 'info' : 1}
++        self.stBar = VnetStatusbar(parent = self, style = 0)
++        self.stBar.SetFieldsCount(number = 1)
++
 +        mainsizer = wx.BoxSizer(wx.VERTICAL)
 +        mainsizer.Add(item = self.toolbars['mainToolbar'], proportion = 0, flag = wx.EXPAND)
 +        mainsizer.Add(item = self.toolbars['editingToolbar'], proportion = 0, flag = wx.EXPAND)
 +        mainsizer.Add(item = self.catsPanel, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT , border = 5)
 +        mainsizer.Add(item = self.plot_panel, proportion = 1, flag = wx.EXPAND)
++        mainsizer.Add(item = self.stBar, proportion = 0)
 +
 +        self.catsPanel.Hide()
 +        self.toolbars['editingToolbar'].Hide()
 +
 +        self.SetSizer(mainsizer)
 +        
++        self.scatt_mgr.cursorPlotMove.connect(self.CursorPlotMove)
++        self.scatt_mgr.renderingStarted.connect(lambda : self.stBar.AddStatusItem(text=_("Rendering..."), 
++                                                                                 key='comp', 
++                                                                                 priority=self.stPriors['high']))
++        self.scatt_mgr.renderingFinished.connect(lambda : self.stBar.RemoveStatusItem(key='comp'))
++
++        self.scatt_mgr.computingStarted.connect(lambda : self.stBar.AddStatusItem(text=_("Computing data..."), 
++                                                                                 key='comp', 
++                                                                                 priority=self.stPriors['high']))
++
 +        #self.SetSashGravity(0.5)
 +        #self.SplitHorizontally(self.head_panel, self.plot_panel, -50)
 +        self.Layout()
 +
++    def CursorPlotMove(self, x, y):
++
++        x = int(round(x))
++        y = int(round(y))
++        self.stBar.AddStatusItem(text="%d; %d" % (x, y), 
++                                 key='coords', 
++                                 priority=self.stPriors['info'])
++
++
 +    def NewScatterPlot(self, scatt_id, transpose):
 +        return self.plot_panel.NewScatterPlot(scatt_id, transpose)
 +
@@ -714,9 +4522,25 @@
 +        menu.Append(item_id, text=_("Change opacity level"))
 +        self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, id=item_id)
 +
++        item_id = wx.NewId()
++        menu.Append(item_id, text=_("Export raster"))
++        self.Bind(wx.EVT_MENU, self.OnExportCatRast, id=item_id)
++
++
 +        self.PopupMenu(menu)
 +        menu.Destroy()
 +
++    def OnExportCatRast(self, event):
++        """!Export training areas"""
++        #TODO
++        #   GMessage(parent=self, message=_("No class raster to export."))
++        #    return
++
++        cat_idx = self.rightClickedItemIdx
++        cat_id = self.cats_mgr.GetCategories()[cat_idx]
++
++        self.cats_mgr.ExportCatRast(cat_id)
++
 +    def OnMoveUp(self, event):
 +        cat_idx = self.rightClickedItemIdx
 +        cat_id = self.cats_mgr.GetCategories()[cat_idx]
@@ -897,7 +4721,7 @@
 ===================================================================
 --- gui/wxpython/scatt_plot/plots.py	(revision 0)
 +++ gui/wxpython/scatt_plot/plots.py	(working copy)
-@@ -0,0 +1,851 @@
+@@ -0,0 +1,906 @@
 +"""!
 + at package scatt_plot.dialogs
 +
@@ -922,6 +4746,7 @@
 +#TODO
 +#from numpy.lib.stride_tricks import as_strided
 +from copy import deepcopy
++from scatt_plot.core_c import MergeArrays, ApplyColormap
 +
 +try:
 +    import matplotlib
@@ -971,6 +4796,7 @@
 +        self.Bind(wx.EVT_CLOSE,lambda event : self.CleanUp())
 +
 +        self.plotClosed = Signal("ScatterPlotWidget.plotClosed")
++        self.cursorMove = Signal("ScatterPlotWidget.cursorMove")
 +
 +        self.contex_menu = ScatterPlotContextMenu(plot = self)
 +
@@ -1097,7 +4923,6 @@
 +
 +        callafter_list = []
 +
-+
 +        if self.full_extend:
 +            cx = self.axes.get_xlim()
 +            cy = self.axes.get_ylim()
@@ -1105,15 +4930,20 @@
 +        else:
 +            c = None
 +
-+        q = Queue()
-+        p = Process(target=MergeImg, args=(cats_order, scatts, styles, self.transpose, q))
-+        p.start()
-+        merged_img, self.full_extend = q.get()
-+        p.join()
-+
++        
++        #q = Queue()
++        #p = Process(target=MergeImg, args=(cats_order, scatts, styles, self.transpose, q))
++        #p.start()
++        #merged_img, self.full_extend = q.get()
++        #p.join()
++        
++        merged_img, self.full_extend = MergeImg(cats_order, scatts, styles, None)
 +        self.axes.clear()
 +        self.axes.axis('equal')
 +
++        if self.transpose:
++            merged_img = np.transpose(merged_img, (1, 0, 2))
++
 +        img = imshow(self.axes, merged_img,
 +                     origin = 'lower',
 +                     interpolation='nearest',
@@ -1134,28 +4964,44 @@
 +
 +            colors = styles[cat_id]['color'].split(":")
 +            if self.transpose:
-+                angle = 360 - e['theta'] + 90
-+                if angle >= 360:
-+                    angle = abs(360 - angle) 
++                e['theta'] = 360 - e['theta'] + 90
++                if e['theta'] >= 360:
++                    e['theta'] = abs(360 - e['theta']) 
 +                
-+                xy = [e['pos'][1], e['pos'][0]]
-+                ellip = Ellipse(xy=xy, 
-+                                width=e['width'], 
-+                                height=e['height'], 
-+                                angle=angle, 
-+                                edgecolor="r", 
-+                                facecolor = 'None')
-+            else:
-+                ellip = Ellipse(xy=e['pos'], 
-+                                width=e['width'], 
-+                                height=e['height'], 
-+                                angle=e['theta'], 
-+                                edgecolor="r", 
-+                                facecolor = 'None')
++                e['pos'] = [e['pos'][1], e['pos'][0]]
 +
++            ellip = Ellipse(xy=e['pos'], 
++                            width=e['width'], 
++                            height=e['height'], 
++                            angle=e['theta'], 
++                            edgecolor="w",
++                            linewidth=1.5, 
++                            facecolor = 'None')
 +            self.axes.add_artist(ellip)
 +            callafter_list.append([self.axes.draw_artist, [ellip]])
 +
++            color = map(lambda v : int(v)/255.0, styles[cat_id]['color'].split(":"))
++
++
++            ellip = Ellipse(xy=e['pos'], 
++                            width=e['width'], 
++                            height=e['height'], 
++                            angle=e['theta'], 
++                            edgecolor=color,
++                            linewidth=1, 
++                            facecolor = 'None')
++
++            self.axes.add_artist(ellip)
++            callafter_list.append([self.axes.draw_artist, [ellip]])
++            
++            center = Line2D([e['pos'][0]], [e['pos'][1]], 
++                            marker='x',
++                            markeredgecolor='w',
++                            #markerfacecolor=color,
++                            markersize=2)
++            self.axes.add_artist(center)
++            callafter_list.append([self.axes.draw_artist, [center]])
++
 +        callafter_list.append([self.fig.canvas.blit, []])
 +
 +        if c:
@@ -1224,12 +5070,20 @@
 +    def Motion(self, event):
 +        self.PanMotion(event)
 +        self.ZoomRectMotion(event)
++        
++        if event.inaxes is None: 
++            return
++        
++        self.cursorMove.emit(x=event.xdata, y=event.ydata)
 +
 +    def PanMotion(self, event):
 +        'on mouse movement'
-+        if not self.mode == "pan": return
-+        if event.inaxes is None: return
-+        if event.button != 1: return
++        if not self.mode == "pan": 
++            return
++        if event.inaxes is None: 
++            return
++        if event.button != 1: 
++            return
 +
 +        cur_xlim = self.axes.get_xlim()
 +        cur_ylim = self.axes.get_ylim()
@@ -1538,9 +5392,8 @@
 +    Author: Chris Beaumont <beaumont at hawaii.edu>
 +    """
 +    def __init__(self, *args, **kwargs):
-+        #why???
-+        #if 'extent' in kwargs and kwargs['extent'] is not None:
-+        #    raise NotImplementedError("ModestImage does not support extents")
++        if 'extent' in kwargs and kwargs['extent'] is not None:
++            raise NotImplementedError("ModestImage does not support extents")
 +
 +        self._full_res = None
 +        self._sx, self._sy = None, None
@@ -1613,7 +5466,6 @@
 +        self._scale_to_res()
 +        super(ModestImage, self).draw(renderer, *args, **kwargs)
 +
-+
 +def imshow(axes, X, cmap=None, norm=None, aspect=None,
 +           interpolation=None, alpha=None, vmin=None, vmax=None,
 +           origin=None, extent=None, shape=None, filternorm=1,
@@ -1660,15 +5512,15 @@
 +
 +    return im
 +
-+def MergeImg(cats_order, scatts, styles, transpose, output_queue):
++def MergeImg(cats_order, scatts, styles, output_queue):
 +
 +        start_time = time.clock()
++        cmap_time = 0
++        merge_time = 0
++        mask_time = 0
++        norm_time = 0
++        max_time = 0
 +
-+
-+        start_time = time.clock()
-+        #cmap_time = 0
-+
-+
 +        init = True
 +        merge_tmp = grass.tempfile()
 +        for cat_id in cats_order:
@@ -1681,13 +5533,10 @@
 +               not styles[cat_id]['show']):
 +                continue
 +            if init:
-+                if transpose:
-+                    b1_i = scatt['bands_info']['b1']
-+                    b2_i = scatt['bands_info']['b2']
-+                else:
-+                    b2_i = scatt['bands_info']['b1']
-+                    b1_i = scatt['bands_info']['b2']
 +
++                b2_i = scatt['bands_info']['b1']
++                b1_i = scatt['bands_info']['b2']
++
 +                full_extend = (b1_i['min'] - 0.5, b1_i['max'] + 0.5, b2_i['min'] - 0.5, b2_i['max'] + 0.5) 
 +            
 +            if cat_id == 0:
@@ -1706,55 +5555,85 @@
 +                cmap._lut[:, 1] = int(colors[1])/255.0
 +                cmap._lut[:, 2] = int(colors[2])/255.0
 +
++
 +            #if init:
-+            if transpose:
-+                masked_cat = np.ma.masked_less_equal(scatt['np_vals'].T, 0)
-+            else:
-+                masked_cat = np.ma.masked_less_equal(scatt['np_vals'], 0)
++            tmp = time.clock()
 +
++            masked_cat = np.ma.masked_less_equal(scatt['np_vals'], 0)
++            mask_time += time.clock() - tmp
++
++            tmp = time.clock()
 +            vmax = np.amax(masked_cat)
-+            masked_cat = masked_cat / float(vmax)
++            max_time += time.clock() - tmp
 +
-+            #tmp = time.clock()
-+            colored_cat = np.uint8(cmap(masked_cat) * 255)
-+            #cmap_time += time.clock() + tmp
++            tmp = time.clock()
++            masked_cat = np.uint8(masked_cat * (255.0 / float(vmax)))
++            norm_time += time.clock() - tmp
 +
++            #print "ahoj"
++            #print masked_cat
++            #print masked_cat.shape
++            #print masked_cat.mask.dtype
++            #
++            #print "colored_cat.shape"
++            #print colored_cat.shape
++            #merged_img = np.memmap(merge_tmp, dtype='uint8',, shape=colored_cat.shape)
++            tmp = time.clock()
++            cmap = np.uint8(cmap._lut * 255)
++            sh =masked_cat.shape
++
++            colored_cat = np.zeros(dtype='uint8', shape=(sh[0], sh[1], 4))
++            ApplyColormap(masked_cat, masked_cat.mask, cmap, colored_cat)
++
++            #colored_cat = np.uint8(cmap(masked_cat) * 255)
++            cmap_time += time.clock() - tmp
++
 +            del masked_cat
 +            del cmap
 +            
 +            #colored_cat[...,3] = np.choose(masked_cat.mask, (255, 0))
-+            
++
++            tmp = time.clock()
 +            if init:
 +                merged_img = np.memmap(merge_tmp, dtype='uint8', mode='w+', shape=colored_cat.shape)
 +                merged_img[:] = colored_cat[:]
 +                init = False
 +            else:
++                MergeArrays(merged_img, colored_cat, styles[cat_id]['opacity'])
++
++            """
 +                #c_img_a = np.memmap(grass.tempfile(), dtype="uint16", mode='w+', shape = shape) 
 +                c_img_a = colored_cat.astype('uint16')[:,:,3] * styles[cat_id]['opacity']
 +
 +                #TODO apply strides and there will be no need for loop
 +                #b = as_strided(a, strides=(0, a.strides[3], a.strides[3], a.strides[3]), shape=(3, a.shape[0], a.shape[1]))
-+
++                
 +                for i in range(3):
 +                    merged_img[:,:,i] = (merged_img[:,:,i] * (255 - c_img_a) + colored_cat[:,:,i] * c_img_a) / 255;
 +                merged_img[:,:,3] = (merged_img[:,:,3] * (255 - c_img_a) + 255 * c_img_a) / 255;
 +                
 +                del c_img_a
-+            
++            """
++            merge_time += time.clock() - tmp
++
 +            del colored_cat
 +
-+        #end_time =  time.clock() - start_time
++        end_time =  time.clock() - start_time
 +        #print "all time:%f" % (end_time)
-+        #print "cmap_time:%f" % (end_time / cmap_time * 100.0 )
-+
-+        output_queue.put((merged_img, full_extend))
-+        #return merged_img, full_extend 
++        #print "cmap_time:%f" % (cmap_time / end_time * 100.0 )
++        #print "merge_time:%f" % (merge_time / end_time * 100.0 )
++        #print "mask_time:%f" % (mask_time / end_time * 100.0 )
++        #print "nax_time:%f" % (max_time / end_time * 100.0 )
++        #print "norm_time:%f" % (norm_time / end_time * 100.0 )
++        
++        #output_queue.put((merged_img, full_extend))
++        return merged_img, full_extend 
 \ No newline at end of file
 Index: gui/wxpython/scatt_plot/controllers.py
 ===================================================================
 --- gui/wxpython/scatt_plot/controllers.py	(revision 0)
 +++ gui/wxpython/scatt_plot/controllers.py	(working copy)
-@@ -0,0 +1,708 @@
+@@ -0,0 +1,773 @@
 +"""!
 + at package scatt_plot.controllers
 +
@@ -1782,11 +5661,15 @@
 +
 +from scatt_plot.scatt_core import Core, idBandsToidScatt
 +
-+from scatt_plot.dialogs import AddScattPlotDialog
++from scatt_plot.dialogs import AddScattPlotDialog, ExportCategoryRaster
 +from scatt_plot.gthreading import gThread
 +from core.gconsole import EVT_CMD_DONE
 +from grass.pydispatch.signal import Signal
++import grass.script as grass
 +
++from grass.pydispatch.signal import Signal
++
++
 +class ScattsManager(wx.EvtHandler):
 +    def __init__(self, guiparent, giface, iclass_mapwin):
 +        #TODO remove iclass parameter
@@ -1812,7 +5695,7 @@
 +        self.thread = gThread(self);
 +        
 +        self.plots = {}
-+        self.added_cats_rasts = {}
++        self.added_cats_rasts = []
 +
 +        self.cats_to_update = []
 +
@@ -1821,6 +5704,13 @@
 +
 +        self.data_set = False
 +
++        self.cursorPlotMove = Signal("ScattsManager.cursorPlotMove")
++
++        self.renderingStarted = Signal("ScattsManager.renderingStarted")
++        self.renderingFinished = Signal("ScattsManager.renderingFinished")
++
++        self.computingStarted = Signal("ScattsManager.computingStarted")
++
 +        if iclass_mapwin: 
 +            self.mapWin_conn = MapWinConnection(self, self.mapWin, self.core.CatRastUpdater())
 +            self.iclass_conn = IClassConnection(self, iclass_mapwin.parent, self.cats_mgr)
@@ -1835,7 +5725,8 @@
 +                            'set_edit_cat_data' : -1,
 +                            'mapwin_conn' : [],
 +                            'render_plots' : -1,
-+                            'render' : []
++                            'render' : [],
++                            'export_cat_rast' : []
 +                           }
 +
 +        self.Bind(EVT_CMD_DONE, self.OnThreadDone)
@@ -1844,7 +5735,9 @@
 +
 +    def CleanUp(self):
 +        self.core.CleanUp()
++        self.added_cats_rasts = []
 +
++        self.cats_mgr.CleanUp()
 +        for scatt_id, scatt in self.plots.items():
 +            scatt.CleanUp()
 +
@@ -1876,6 +5769,8 @@
 +
 +        if event.pid in self.tasks_pids['render']:
 +            self.tasks_pids['render'].remove(event.pid)
++            if not self.tasks_pids['render']:
++                self.renderingFinished.emit()
 +            return
 +            
 +        if event.pid in self.tasks_pids['add_scatt']:
@@ -1896,23 +5791,27 @@
 +            self.SetEditCatDataDone(event)
 +            return
 +
++        if event.pid in self.tasks_pids['export_cat_rast']:
++            self.cats_mgr.OnExportCatRastDone(event)
++            return
++
 +    def SetData(self, bands):
-+
++        "setting datas"
 +        self.CleanUp()
 +
 +        self.data_set = False
 +
 +        if self.show_add_scatt_plot:
 +            self.tasks_pids['set_data_add'] = self.thread.GetId()
++            print 'set_data_add'
 +        else:
 +            self.tasks_pids['set_data'] = self.thread.GetId()
++            print 'set_data'
++        self.thread.Run(callable=self.core.SetData, bands=bands)
 +
-+        self.thread.Run(callable = self.core.SetData, bands = bands)
-+
 +    def SetDataDone(self, event):
-+
 +        self.data_set = True
-+        self.cats_mgr.InitCoreCats()
++        self.iclass_conn.SyncCats()
 +
 +    def OnOutput(self, event):
 +        """!Print thread output according to debug level.
@@ -1932,6 +5831,8 @@
 +            GError(_('No data set.'))
 +            return
 +
++        self.computingStarted.emit()
++
 +        bands = self.core.GetBands()
 +        dlg = AddScattPlotDialog(parent = self.guiparent, bands = bands)
 +        if dlg.ShowModal() == wx.ID_OK:
@@ -1951,25 +5852,8 @@
 +        
 +        dlg.Destroy()
 +
-+        return 
-+
-+        #for testing
-+        jj = len(self.core.GetBands()) - 1
-+
-+        max_k = 20
-+        k = 0
-+        for i in range(jj):
-+            for j in range(i, jj):
-+                print i * (len(self.core.GetBands()) - 1) + j
-+                self._addScattPlot(i * (len(self.core.GetBands()) - 1) + j)
-+                k += 1
-+                if k == max_k:
-+                    break
-+            if k == max_k:
-+                break
-+            jj -= 1
-+
-+
++        self.mapWin_conn.Update()
++         
 +    def _addScattPlot(self, scatt_id, transpose):
 +        if self.plots.has_key(scatt_id):
 +            GMessage(_("Scatter plot has been already added."))
@@ -1979,11 +5863,11 @@
 +        
 +        self.thread.Run(callable = self.core.AddScattPlot, scatt_id = scatt_id, userdata = {'transpose' : transpose})
 +
-+
 +    def RenderScattPlts(self, scatt_ids = None):
 +        if len(self.tasks_pids['render']) > 1:
 +            return 
-+
++        
++        self.renderingStarted.emit()
 +        self.tasks_pids['render'].append(self.thread.GetId())
 +        self.thread.Run(callable = self._renderscattplts, scatt_ids = scatt_ids)
 +
@@ -1997,7 +5881,7 @@
 +                continue
 +
 +            scatt_dt = self.scatts_dt.GetScatt(i_scatt_id)
-+            ellipses_dt = self.scatts_dt.GetEllipses(i_scatt_id)
++            ellipses_dt = self.scatts_dt.GetEllipses(i_scatt_id, cats_attrs)
 +
 +            if self.pol_sel_mode[0]:
 +                self._getSelectedAreas(cats, i_scatt_id, scatt_dt, cats_attrs)
@@ -2032,6 +5916,7 @@
 +        self.plots[scatt_id] = self.guiparent.NewScatterPlot(scatt_id = scatt_id, transpose = transpose)
 +
 +        self.plots[scatt_id].plotClosed.connect(self.PlotClosed)
++        self.plots[scatt_id].cursorMove.connect(lambda x, y: self.cursorPlotMove.emit(x = x, y = y))
 +
 +        if self.plot_mode:
 +            self.plots[scatt_id].SetMode(self.plot_mode)
@@ -2093,6 +5978,8 @@
 +        for scatt in self.plots.itervalues():
 +            scatt.SetEmpty()
 +
++        self.computingStarted.emit()
++
 +        self.tasks_pids['set_edit_cat_data'] = self.thread.GetId()
 +        self.thread.Run(callable = self.core.UpdateCategoryWithPolygons, 
 +                        cat_id = sel_cat_id,
@@ -2100,7 +5987,6 @@
 +                        value = value)
 +
 +    def SetEditCatDataDone(self, event):
-+
 +        if event.exception:
 +            GError(_("Error occured during computation of scatter plot category:\n%s"), 
 +                      parent = self.guiparent, showTraceback = False)
@@ -2110,44 +5996,46 @@
 +        self.RenderScattPlts()
 +
 +        cat_id = event.kwds["cat_id"]
++        train_mgr, preview_mgr = self.iclass_conn.iclass_frame.GetMapManagers()
++        
++        if not cat_id in self.added_cats_rasts:
++            cat_rast = self.core.GetCatRast(cat_id)
 +
-+        cat_rast = self.core.GetCatRast(cat_id)
++            cat_name = self.cats_mgr.GetCategoryAttrs(cat_id)['name']
++            self.UpdateCategoryRaster(cat_id, ['color'], render = False)
++            train_mgr.AddLayer(cat_rast, alias = cat_name)
 +
-+        if cat_rast not in self.added_cats_rasts.values():
++            self.added_cats_rasts.append(cat_id)
++        else: #TODO settings
++            train_mgr.Render()
++            
++    def UpdateCategoryRaster(self, cat_id, attrs, render = True):
 +
-+            cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
++        cat_rast = self.core.GetCatRast(cat_id)
++        if not grass.find_file(cat_rast, element = 'cell', mapset = '.')['file']:
++            return
++        cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
++        train_mgr, preview_mgr = self.iclass_conn.iclass_frame.GetMapManagers()
 +
-+    
-+            region = self.core.GetRegion()
-+            ret, err_msg = RunCommand('r.region',
-+                                      map = cat_rast,
-+                                      getErrorMsg = True,
-+                                      n = "%f" % region['n'],
-+                                      s = "%f" % region['s'],
-+                                      e = "%f" % region['e'],
-+                                      w = "%f" % region['w'],
-+                                      )
-+
++        if "color" in attrs:
 +            ret, err_msg = RunCommand('r.colors',
-+                                      map = cat_rast,
-+                                      rules = "-",
-+                                      stdin = "1 %s" % cats_attrs["color"],
-+                                      getErrorMsg = True)
++                                      map=cat_rast,
++                                      rules="-",
++                                      stdin="1 %s" % cats_attrs["color"],
++                                      getErrorMsg=True)
 +
 +            if ret != 0:
-+                GError(_("r.region failed\n%s" % err_msg))
++                GError("r.colors failed\n%s" % err_msg)
++            if render:
++                train_mgr.Render()
 +
-+            self.mapWin.Map.AddLayer(ltype = "raster", name =  "cat_%d" % cat_id, render = True,
-+                                     command = ["d.rast", "map=%s" % cat_rast, "values=1"])                
++        if "name" in attrs:
++            cat_rast = self.core.GetCatRast(cat_id)
 +
++            train_mgr.SetAlias(original=cat_rast, alias=cats_attrs['name'])
++            cats_attrs["name"]
 +
-+            if ret != 0:
-+                GError(_("r.region failed\n%s" % err_msg))
 +
-+            self.added_cats_rasts[cat_id] = cat_rast
-+
-+        self.giface.updateMap.emit()
-+
 +    def DigitDataChanged(self, vectMap, digit):
 +        
 +        if self.mapWin_conn:
@@ -2159,7 +6047,6 @@
 +    def GetCategoriesManager(self):
 +        return self.cats_mgr
 +
-+
 +class CategoriesManager:
 +
 +    def __init__(self, scatt_mgr, core):
@@ -2172,23 +6059,27 @@
 +
 +        self.sel_cat_id = None
 +
++        self.exportRaster = None
++
 +        self.initialized = Signal('CategoriesManager.initialized')
 +        self.setCategoryAttrs = Signal('CategoriesManager.setCategoryAttrs')
 +        self.deletedCategory = Signal('CategoriesManager.deletedCategory')
 +        self.addedCategory = Signal('CategoriesManager.addedCategory')
 +
-+    def Clear(self):
-+
++    def CleanUp(self):
++        
 +        self.cats.clear()
 +        del self.cats_ids[:]
 +
 +        self.sel_cat_id = None  
-+
++    """
 +    def InitCoreCats(self):
 +        if self.scatt_mgr.data_set:
 +            for cat_id in self.cats_ids:
-+                self.core.AddCategory(cat_id)
++                self._addCategory(cat_id)
 +
++        self.scatt_mgr.mapWin_conn.Update()
++    """
 +    def ChangePosition(self, cat_id, new_pos):
 +        if new_pos >= len(self.cats_ids):
 +            return False
@@ -2208,8 +6099,12 @@
 +        self.scatt_mgr.RenderScattPlts()
 +        return True
 +
-+    def AddCategory(self, cat_id = None, name = None, color = None):
++    def _addCategory(self, cat_id):
++        self.scatt_mgr.thread.Run(callable = self.core.AddCategory, 
++                                  cat_id = cat_id)
 +
++    def AddCategory(self, cat_id = None, name = None, color = None, nstd = None):
++
 +        if cat_id is None:
 +            if self.cats_ids:
 +                cat_id = max(self.cats_ids) + 1
@@ -2227,7 +6122,8 @@
 +                                'name' : _('Category %s' % cat_id ),
 +                                'color' : "0:0:0",
 +                                'opacity' : 1.0,
-+                                'show' : True
++                                'show' : True,
++                                'nstd' : 1.0,
 +                            }
 +
 +        self.cats_ids.insert(0, cat_id)
@@ -2238,6 +6134,9 @@
 +        if color is not None:
 +            self.cats[cat_id]["color"] = color
 +
++        if nstd is not None:
++            self.cats[cat_id]["nstd"] = nstd
++
 +        self.addedCategory.emit(cat_id = cat_id,
 +                                name = self.cats[cat_id]["name"], 
 +                                color = self.cats[cat_id]["color"] )
@@ -2245,15 +6144,21 @@
 +
 +    def SetCategoryAttrs(self, cat_id, attrs_dict):
 +        render = False
++        update_cat_rast = []
++
 +        for k, v in attrs_dict.iteritems():
-+            if not render and k in ['name', 'color', 'opacity', 'show']:
++            if not render and k in ['color', 'opacity', 'show', 'nstd']:
 +                render = True
++            if k in ['color', 'name']:
++                update_cat_rast.append(k)
 +
 +            self.cats[cat_id][k] = v
 +
-+        #TODO optimization 
 +        if render:
 +            self.scatt_mgr.RenderScattPlts()
++        
++        if update_cat_rast:
++            self.scatt_mgr.UpdateCategoryRaster(cat_id, update_cat_rast)
 +
 +        self.setCategoryAttrs.emit(cat_id = cat_id, attrs_dict = attrs_dict)
 +
@@ -2293,6 +6198,35 @@
 +        
 +        self.cats_ids.insert(newindex, self.cats_ids.pop(oldindex))
 +
++    def ExportCatRast(self, cat_id):
++
++        cat_attrs = self.GetCategoryAttrs(cat_id)
++
++        dlg = ExportCategoryRaster(parent=self.scatt_mgr.guiparent, 
++                                   rasterName=self.exportRaster, 
++                                   title=_("Export scatter plot raster of class <%s>") % cat_attrs['name'])
++        
++        if dlg.ShowModal() == wx.ID_OK:
++            self.exportCatRast = dlg.GetRasterName()
++            dlg.Destroy()
++
++            self.scatt_mgr.tasks_pids['export_cat_rast'].append(self.scatt_mgr.thread.GetId())
++            self.scatt_mgr.thread.Run(callable=self.core.ExportCatRast,
++                                      userdata={'name' : cat_attrs['name']},
++                                      cat_id=cat_id,
++                                      rast_name=self.exportCatRast)
++
++    def OnExportCatRastDone(self, event):
++        ret, err = event.ret
++        if ret == 0:
++            cat_attrs = self.GetCategoryAttrs(event.kwds['cat_id'])
++            GMessage(_("Scatter plot raster of class <%s> exported to raster map <%s>.") % 
++                      (event.userdata['name'], event.kwds['rast_name']))
++        else:
++            GMessage(_("Export of scatter plot raster of class <%s> to map <%s> failed.\n%s") % 
++                      (event.userdata['name'], event.kwds['rast_name'], err))
++
++
 +class MapWinConnection:
 +    def __init__(self, scatt_mgr, mapWin, scatt_rast_updater):
 +        self.mapWin = mapWin
@@ -2315,6 +6249,9 @@
 +        #                              getErrorMsg = True,
 +        #                              read = True)
 +
++    def Update(self):
++        self.thread.Run(callable=self.scatt_rast_updater.SynchWithMap)
++
 +    def _connectSignals(self):
 +        self.digit.featureAdded.connect(self.AddFeature)
 +        self.digit.areasDeleted.connect(self.DeleteAreas)
@@ -2327,6 +6264,7 @@
 +    def AddFeature(self, new_bboxs, new_areas_cats):
 +        if not self.scatt_mgr.data_set:
 +            return
++        self.scatt_mgr.computingStarted.emit()
 +
 +        self.scatt_mgr.tasks_pids['mapwin_conn'].append(self.thread.GetId())
 +        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
@@ -2338,6 +6276,7 @@
 +    def DeleteAreas(self, old_bboxs, old_areas_cats):
 +        if not self.scatt_mgr.data_set:
 +            return
++        self.scatt_mgr.computingStarted.emit()
 +
 +        self.scatt_mgr.tasks_pids['mapwin_conn'].append(self.thread.GetId())
 +        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
@@ -2350,6 +6289,7 @@
 +    def EditedFeature(self, new_bboxs, new_areas_cats, old_bboxs, old_areas_cats):
 +        if not self.scatt_mgr.data_set:
 +            return
++        self.scatt_mgr.computingStarted.emit()
 +
 +        self.scatt_mgr.tasks_pids['mapwin_conn'].append(self.thread.GetId())
 +        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
@@ -2373,9 +6313,9 @@
 +class IClassConnection:
 +    def __init__(self, scatt_mgr, iclass_frame, cats_mgr):
 +        self.iclass_frame = iclass_frame
-+        self.stats_data   = self.iclass_frame.stats_data
-+        self.cats_mgr     = cats_mgr
-+        self.scatt_mgr    = scatt_mgr
++        self.stats_data = self.iclass_frame.stats_data
++        self.cats_mgr = cats_mgr
++        self.scatt_mgr= scatt_mgr
 +
 +        self.stats_data.statisticsAdded.connect(self.AddCategory)
 +        self.stats_data.statisticsDeleted.connect(self.DeleteCategory)
@@ -2398,12 +6338,14 @@
 +    def EmptyCategories(self):
 +        self.iclass_frame.OnCategoryManager(None)
 +
-+    def SyncCats(self):
++    def SyncCats(self, cats_ids = None):
 +        self.cats_mgr.addedCategory.disconnect(self.AddStatistics)
 +        cats = self.stats_data.GetCategories()
 +        for c in cats:
++            if cats_ids and c not in cats_ids:
++                continue
 +            stats = self.stats_data.GetStatistics(c)
-+            self.cats_mgr.AddCategory(c, stats.name, stats.color)
++            self.cats_mgr.AddCategory(c, stats.name, stats.color, stats.nstd)
 +        self.cats_mgr.addedCategory.connect(self.AddStatistics)
 +
 +    def CategoryChanged(self, cat):
@@ -2411,7 +6353,8 @@
 +
 +    def AddCategory(self, cat, name, color):
 +        self.cats_mgr.addedCategory.disconnect(self.AddStatistics)
-+        self.cats_mgr.AddCategory(cat_id = cat, name = name, color = color)
++        stats = self.stats_data.GetStatistics(cat)
++        self.cats_mgr.AddCategory(cat_id = cat, name = name, color = color, nstd = stats.nstd)
 +        self.cats_mgr.addedCategory.connect(self.AddStatistics)
 +
 +    def DeleteCategory(self, cat):
@@ -2431,7 +6374,8 @@
 +
 +        self.cats_mgr.setCategoryAttrs.disconnect(self.SetStatistics)
 +        cats_attr = {}
-+        for attr in ['name', 'color']:
++
++        for attr in ['name', 'color', 'nstd']:
 +            if stats.has_key(attr):
 +                cats_attr[attr] = stats[attr]
 +
@@ -2464,3461 +6408,18 @@
 +            bands = res.split('\n')
 +            self.scatt_mgr.SetData(bands)
 \ No newline at end of file
-Index: gui/wxpython/scatt_plot/gthreading.py
+Index: gui/icons/grass/polygon.png
 ===================================================================
---- gui/wxpython/scatt_plot/gthreading.py	(revision 0)
-+++ gui/wxpython/scatt_plot/gthreading.py	(working copy)
-@@ -0,0 +1,134 @@
-+"""!
-+ at package scatt_plot.gthreading
-+
-+Classes:
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+
-+import os
-+import sys
-+import time
-+import threading
-+import Queue
-+
-+import wx
-+from core.gconsole import wxCmdRun, wxCmdDone, wxCmdPrepare
-+
-+class gThread(threading.Thread):
-+    """!Thread for GRASS commands"""
-+    requestId = 0
-+
-+    def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
-+        """!
-+        @param receiver event receiver (used in PostEvent)
-+        """
-+        threading.Thread.__init__(self, **kwds)
-+
-+        if requestQ is None:
-+            self.requestQ = Queue.Queue()
-+        else:
-+            self.requestQ = requestQ
-+
-+        if resultQ is None:
-+            self.resultQ = Queue.Queue()
-+        else:
-+            self.resultQ = resultQ
-+
-+        self.setDaemon(True)
-+
-+        self.receiver = receiver
-+        self._want_abort_all = False
-+
-+        self.start()
-+
-+    def Run(self, *args, **kwds):
-+        """!Run command in queue
-+
-+        @param args unnamed command arguments
-+        @param kwds named command arguments
-+
-+        @return request id in queue
-+        """
-+        gThread.requestId += 1
-+        self.requestQ.put((gThread.requestId, args, kwds))
-+
-+        return gThread.requestId
-+
-+    def GetId(self):
-+         """!Get id for next command"""
-+         return gThread.requestId + 1
-+
-+    def SetId(self, id):
-+        """!Set starting id"""
-+        gThread.requestId = id
-+
-+    def run(self):
-+        os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
-+        while True:
-+            requestId, args, kwds = self.requestQ.get()
-+            for key in ('callable', 'onDone', 'onPrepare', 'userdata'):
-+                if key in kwds:
-+                    vars()[key] = kwds[key]
-+                    del kwds[key]
-+                else:
-+                    vars()[key] = None
-+
-+            requestTime = time.time()
-+
-+            #if self._want_abort_all and self.requestCmd is not None:
-+            #    self.requestCmd.abort()
-+            #    if self.requestQ.empty():
-+            #        self._want_abort_all = False
-+
-+            # prepare
-+            if self.receiver:
-+                event = wxCmdPrepare(type = 'method',
-+                                     time=requestTime,
-+                                     pid=requestId)
-+
-+                wx.PostEvent(self.receiver, event)
-+
-+                # run command
-+                event = wxCmdRun(type = 'method',
-+                                 pid=requestId)
-+
-+                wx.PostEvent(self.receiver, event)
-+
-+            time.sleep(.1)
-+
-+            ret = None
-+            exception = None
-+            
-+            #to
-+            #try:
-+            ret = vars()['callable'](*args, **kwds)
-+            #except Exception as e:
-+            #    exception  = e;
-+
-+            self.resultQ.put((requestId, ret))
-+
-+            time.sleep(.1)
-+
-+            if self.receiver:
-+                event = wxCmdDone(kwds=kwds,
-+                                  args=args, #TODO expand args to kwds
-+                                  ret=ret,
-+                                  exception=exception,
-+                                  userdata=vars()['userdata'],
-+                                  pid=requestId)
-+
-+                # send event
-+                wx.PostEvent(self.receiver, event)
-+
-+    def abort(self, abortall=True):
-+        """!Abort command(s)"""
-+        if abortall:
-+            self._want_abort_all = True
-+        if self.requestQ.empty():
-+            self._want_abort_all = False
-\ No newline at end of file
-Index: gui/wxpython/scatt_plot/dialogs.py
+Cannot display: file marked as a binary type.
+svn:mime-type = application/octet-stream
+Index: gui/icons/grass/polygon.png
 ===================================================================
---- gui/wxpython/scatt_plot/dialogs.py	(revision 0)
-+++ gui/wxpython/scatt_plot/dialogs.py	(working copy)
-@@ -0,0 +1,149 @@
-+"""!
-+ at package scatt_plot.dialogs
-+
-+ at brief GUI.
-+
-+Classes:
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+import os
-+import sys
-+
-+import wx
-+from scatt_plot.scatt_core import idBandsToidScatt
-+
-+from core.gcmd import GError
-+
-+class AddScattPlotDialog(wx.Dialog):
-+
-+    def __init__(self, parent, bands, id  = wx.ID_ANY):
-+        
-+        wx.Dialog.__init__(self, parent, title = ("Add scatter plot"), id = id)
-+
-+        self.bands = bands
-+
-+        self.x_band = None
-+        self.y_band = None
-+
-+        self._createWidgets()
-+
-+    def _createWidgets(self):
-+
-+        self.labels = {}
-+        self.params = {}
-+
-+        self.band_1_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("%s axis:" % "x"))
-+
-+        self.band_1_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-+                                     choices = self.bands,
-+                                     style = wx.CB_READONLY, size = (350, 30))
-+
-+        self.band_2_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("%s axis:" % "y"))
-+
-+        self.band_2_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-+                                     choices = self.bands,
-+                                     style = wx.CB_READONLY, size = (350, 30))
-+
-+        # buttons
-+        self.btn_close = wx.Button(parent = self, id = wx.ID_CANCEL)
-+        
-+        self.btn_ok = wx.Button(parent = self, id = wx.ID_OK, label = _("&OK"))
-+
-+        self._layout()
-+
-+    def _layout(self):
-+
-+        border = wx.BoxSizer(wx.VERTICAL) 
-+        dialogSizer = wx.BoxSizer(wx.VERTICAL)
-+
-+        regionSizer = wx.BoxSizer(wx.HORIZONTAL)
-+
-+        dialogSizer.Add(item = self._addSelectSizer(title = self.band_1_label, 
-+                                                    sel = self.band_1_ch))
-+
-+        dialogSizer.Add(item = self._addSelectSizer(title = self.band_2_label, 
-+                                                    sel = self.band_2_ch))
-+
-+        # buttons
-+        self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-+
-+        self.btnsizer.Add(item = self.btn_close, proportion = 0,
-+                          flag = wx.ALL | wx.ALIGN_CENTER,
-+                          border = 10)
-+        
-+        self.btnsizer.Add(item = self.btn_ok, proportion = 0,
-+                          flag = wx.ALL | wx.ALIGN_CENTER,
-+                          border = 10)
-+
-+        dialogSizer.Add(item = self.btnsizer, proportion = 0,
-+                        flag = wx.ALIGN_CENTER)
-+
-+        border.Add(item = dialogSizer, proportion = 0,
-+                   flag = wx.ALL, border = 5)
-+
-+        self.SetSizer(border)
-+        self.Layout()
-+        self.Fit()
-+
-+        # bindings
-+        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
-+        self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
-+
-+    def _addSelectSizer(self, title, sel): 
-+        """!Helper layout function.
-+        """
-+        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
-+
-+        selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-+        selTitleSizer.Add(item = title, proportion = 1,
-+                          flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
-+
-+        selSizer.Add(item = selTitleSizer, proportion = 0,
-+                     flag = wx.EXPAND)
-+
-+        selSizer.Add(item = sel, proportion = 1,
-+                     flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-+                     border = 5)
-+
-+        return selSizer
-+
-+    def OnClose(self, event):
-+        """!Close dialog
-+        """
-+        if not self.IsModal():
-+            self.Destroy()
-+        event.Skip()
-+
-+    def OnOk(self, event):
-+        """!
-+        """
-+        b_x = self.band_1_ch.GetSelection()
-+        b_y = self.band_2_ch.GetSelection()
-+
-+        err = True
-+
-+        if b_x < 0 or b_y < 0:
-+            GError(_("Select both x and y bands."))
-+        elif b_y == b_x:
-+            GError(_("Selected bands must be different."))
-+        else:
-+            err = False        
-+
-+        if err:
-+            self.band_y = None
-+            self.band_x = None
-+            return
-+
-+        self.band_y = b_y
-+        self.band_x = b_x
-+
-+        event.Skip()
-+
-+    def GetBands(self):
-+        return (self.band_x, self.band_y)
-Index: gui/wxpython/scatt_plot/toolbars.py
-===================================================================
---- gui/wxpython/scatt_plot/toolbars.py	(revision 0)
-+++ gui/wxpython/scatt_plot/toolbars.py	(working copy)
-@@ -0,0 +1,216 @@
-+"""!
-+ at package scatt_plot.toolbars
-+
-+ at brief Scatter plot - toolbars
-+
-+Classes:
-+ - toolbars::MainToolbar
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+import wx
-+
-+from icons.icon import MetaIcon
-+from gui_core.toolbars import BaseToolbar, BaseIcons
-+from core.gcmd import RunCommand
-+from core.gcmd import GException, GError, RunCommand
-+from scatt_plot.scatt_core import idBandsToidScatt
-+
-+
-+class MainToolbar(BaseToolbar):
-+    """!Main toolbar
-+    """
-+    def __init__(self, parent, scatt_mgr):
-+        BaseToolbar.__init__(self, parent)
-+        self.scatt_mgr = scatt_mgr
-+
-+        self.InitToolbar(self._toolbarData())
-+        
-+        # realize the toolbar
-+        self.Realize()
-+        self.scatt_mgr.modeSet.connect(self.ModeSet)
-+
-+    def _toolbarData(self):
-+
-+        icons = {
-+                'settings'   : BaseIcons['settings'].SetLabel( _('Ssettings')),
-+                'help'       : MetaIcon(img = 'help',
-+                                         label = _('Show manual')),
-+                'add_scatt_pl'  : MetaIcon(img = 'layer-raster-analyze',
-+                                            label = _('Add scatter plot')),
-+                'selCatPol'  : MetaIcon(img = 'polygon',
-+                                      label = _('Select area with polygon')),
-+                'pan'        : MetaIcon(img = 'pan',
-+                                         label = _('Pan mode for scatter plots')),
-+                'zoomIn'     : MetaIcon(img = 'zoom-in',
-+                                        label = _('Zoom mode for scatter plots (left mouse button, wheel)')),
-+                'zoomExtent' : MetaIcon(img = 'zoom-extent',
-+                                       label = _('Zoom to scatter plot data extend mode (click on scatter plot for zooming to extend)')),
-+                'cats_mgr' : MetaIcon(img = 'table-manager',
-+                                          label = _('Show/hide class manager'))
-+                }
-+
-+        return self._getToolbarData((
-+                                     ('add_scatt', icons["add_scatt_pl"],
-+                                     lambda event : self.scatt_mgr.AddScattPlot()),
-+                                     (None, ),
-+                                     ("cats_mgr", icons['cats_mgr'],
-+                                     lambda event: self.parent.ShowCategoryPanel(event.Checked()), wx.ITEM_CHECK),
-+                                     (None, ),
-+                                     ("pan", icons["pan"],
-+                                     lambda event: self.SetPloltsMode(event, 'pan'),
-+                                      wx.ITEM_CHECK),
-+                                     ("zoom", icons["zoomIn"],
-+                                     lambda event: self.SetPloltsMode(event, 'zoom'),
-+                                      wx.ITEM_CHECK),
-+                                     ("zoom_extend", icons["zoomExtent"],
-+                                     lambda event: self.SetPloltsMode(event, 'zoom_extend'),
-+                                      wx.ITEM_CHECK),
-+                                    (None, ),
-+                                     ('sel_pol_mode', icons['selCatPol'],
-+                                      self.ActivateSelectionPolygonMode,
-+                                     wx.ITEM_CHECK)
-+                                     #('settings', icon["settings"],
-+                                     # self.parent.OnSettings),  
-+                                     #('help', icons["help"],
-+                                     # self.OnHelp),                    
-+                                    ))
-+
-+    def GetToolId(self, toolName): #TODO can be useful in base
-+        return vars(self)[toolName]            
-+
-+    def SetPloltsMode(self, event, tool_name):
-+        self.scatt_mgr.modeSet.disconnect(self.ModeSet)
-+        if event.Checked()  == True:
-+            for i_tool_data in  self._data:
-+                i_tool_name = i_tool_data[0]
-+                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
-+                    continue
-+                if i_tool_name == tool_name:
-+                    continue
-+                i_tool_id = vars(self)[i_tool_name]
-+                self.ToggleTool(i_tool_id, False)
-+
-+            self.scatt_mgr.SetPlotsMode(mode = tool_name)
-+        else:
-+            self.scatt_mgr.SetPlotsMode(mode = None)
-+        self.scatt_mgr.modeSet.connect(self.ModeSet)
-+
-+    def ActivateSelectionPolygonMode(self, event):
-+
-+        activated = self.scatt_mgr.ActivateSelectionPolygonMode(event.Checked())
-+        self.parent.ShowPlotEditingToolbar(activated)
-+
-+        i_tool_id = vars(self)['sel_pol_mode']
-+        self.ToggleTool(i_tool_id, activated)
-+
-+    def ModeSet(self, mode):
-+        self.UnsetMode()
-+
-+    def UnsetMode(self):
-+        for i_tool_data in  self._data:
-+                i_tool_name = i_tool_data[0]
-+                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
-+                    continue
-+                i_tool_id = vars(self)[i_tool_name]
-+                self.ToggleTool(i_tool_id, False)
-+
-+class EditingToolbar(BaseToolbar):
-+    """!Main toolbar
-+    """
-+    def __init__(self, parent, scatt_mgr):
-+        BaseToolbar.__init__(self, parent)
-+        self.scatt_mgr = scatt_mgr
-+
-+        self.InitToolbar(self._toolbarData())
-+        
-+        # realize the toolbar
-+        self.Realize()
-+        self.scatt_mgr.modeSet.connect(self.ModeSet)
-+
-+    def _toolbarData(self):
-+        """!Toolbar data
-+        """
-+        self.icons = {
-+            'sel_add'         : MetaIcon(img = 'layer-add',
-+                                         label = _('Include selected area to class.'),
-+                                         desc = _('Include selected area to class.')),
-+            'sel_remove'      : MetaIcon(img = 'layer-remove',
-+                                         label = _('Exclude selected area from class.'),
-+                                         desc = _('Exclude selected area from class.')),
-+            'addVertex'       : MetaIcon(img = 'vertex-create',
-+                                         label = _('Add new vertex'),
-+                                         desc = _('Add new vertex to polygon boundary scatter plot')),
-+            'editLine'        : MetaIcon(img = 'polygon-create',
-+                                         label = _('Edit line/boundary'),
-+                                         desc = _('Add new vertex between last and first points of the boundary')),
-+            'moveVertex'      : MetaIcon(img = 'vertex-move',
-+                                         label = _('Move vertex'),
-+                                         desc = _('Move boundary vertex')),
-+            'removeVertex'    : MetaIcon(img = 'vertex-delete',
-+                                         label = _('Remove vertex'),
-+                                         desc = _('Remove boundary vertex.')),
-+            'delete'        : MetaIcon(img = 'polygon-delete',
-+                                         label = _('Edit line/boundary'),
-+                                         desc = _('Delete polygon')),
-+            }
-+
-+        return self._getToolbarData((
-+                                    ("sel_add", self.icons["sel_add"],
-+                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
-+                                     ("sel_remove", self.icons['sel_remove'],
-+                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
-+                                     (None, ),
-+                                     ("add_vertex", self.icons["editLine"],
-+                                     lambda event: self.SetMode(event, 'add_vertex'),
-+                                     wx.ITEM_CHECK),
-+                                     ("add_boundary_vertex", self.icons['addVertex'],
-+                                     lambda event: self.SetMode(event, 'add_boundary_vertex'),
-+                                     wx.ITEM_CHECK),
-+                                     ("move_vertex", self.icons["moveVertex"],
-+                                     lambda event: self.SetMode(event, 'move_vertex'),
-+                                     wx.ITEM_CHECK),
-+                                     ('delete_vertex', self.icons['removeVertex'],
-+                                     lambda event: self.SetMode(event, 'delete_vertex'),
-+                                     wx.ITEM_CHECK),
-+                                     ('delete', self.icons['delete'],
-+                                     lambda event: self.SetMode(event, 'delete'),
-+                                     wx.ITEM_CHECK)
-+                                    ))
-+
-+    def SetMode(self, event, tool_name):
-+        self.scatt_mgr.modeSet.disconnect(self.ModeSet)
-+        if event.Checked() == True:
-+            for i_tool_data in  self._data:
-+                i_tool_name = i_tool_data[0]
-+                if not i_tool_name:
-+                    continue
-+                if i_tool_name == tool_name:
-+                    continue
-+                i_tool_id = vars(self)[i_tool_name]
-+                self.ToggleTool(i_tool_id, False)
-+            self.scatt_mgr.SetPlotsMode(tool_name)
-+        else:
-+            self.scatt_mgr.SetPlotsMode(None)
-+        self.scatt_mgr.modeSet.connect(self.ModeSet)
-+
-+    def ModeSet(self, mode):
-+
-+        if mode in ['zoom', 'pan', 'zoom_extend', None]:
-+            self.UnsetMode()
-+
-+    def UnsetMode(self):
-+        for i_tool_data in  self._data:
-+                i_tool_name = i_tool_data[0]
-+                if not i_tool_name:
-+                    continue
-+                i_tool_id = vars(self)[i_tool_name]
-+                self.ToggleTool(i_tool_id, False)
-+
-+    def GetToolId(self, toolName):
-+        return vars(self)[toolName]            
-Index: gui/wxpython/scatt_plot/scatt_core.py
-===================================================================
---- gui/wxpython/scatt_plot/scatt_core.py	(revision 0)
-+++ gui/wxpython/scatt_plot/scatt_core.py	(working copy)
-@@ -0,0 +1,779 @@
-+"""!
-+ at package scatt_plot.scatt_plot
-+
-+ at brief Non GUI functions.
-+
-+Classes:
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+import os
-+import sys
-+
-+import time
-+
-+import numpy as np
-+#TODO
-+from matplotlib.path import Path 
-+
-+from math import sqrt, ceil, floor
-+from copy import deepcopy
-+from scipy.signal import convolve2d
-+
-+from core.gcmd import GException, GError, RunCommand
-+
-+import grass.script as grass
-+
-+from core_c import CreateCatRast, ComputeScatts, UpdateCatRast, \
-+                   SC_SCATT_DATA, SC_SCATT_CONDITIONS
-+
-+class Core:
-+    def __init__(self):
-+        
-+        self.an_data = AnalyzedData()
-+
-+        self.scatts_dt = ScattPlotsData(self.an_data)
-+        self.scatt_conds_dt = ScattPlotsCondsData(self.an_data)
-+
-+        self.cat_rast_updater = CatRastUpdater(self.scatts_dt, self.an_data, self)
-+
-+    def SetData(self, bands):
-+        self.an_data.Create(bands)
-+
-+        n_bands = len(self.GetBands())
-+
-+        self.scatts_dt.Create(n_bands)
-+        self.scatt_conds_dt.Create(n_bands)
-+
-+    def AddCategory(self, cat_id):
-+        self.scatts_dt.AddCategory(cat_id)
-+        return self.scatt_conds_dt.AddCategory(cat_id)
-+
-+    def DeleteCategory(self, cat_id):
-+        self.scatts_dt.DeleteCategory(cat_id)
-+        self.scatt_conds_dt.DeleteCategory(cat_id)
-+
-+    def CleanUp(self):
-+        self.scatts_dt.CleanUp()
-+        self.scatt_conds_dt.CleanUp()
-+
-+    def GetBands(self):
-+        return self.an_data.GetBands()
-+
-+    def GetScattsData(self):
-+        return self.scatts_dt, self.scatt_conds_dt;
-+
-+    def GetRegion(self):
-+        return self.an_data.GetRegion()
-+
-+    def GetCatRast(self, cat_id):
-+        return self.scatts_dt.GetCatRast(cat_id)
-+
-+    def AddScattPlot(self, scatt_id):
-+    
-+        self.scatts_dt.AddScattPlot(scatt_id = scatt_id)
-+
-+        cats_ids = self.scatts_dt.GetCategories()
-+        self.ComputeCatsScatts(cats_ids)
-+
-+
-+    def SetEditCatData(self, cat_id, scatt_id, bbox, value):
-+
-+        if cat_id not in self.scatts_dt.GetCategories():
-+            raise GException(_("Select category for editing."))
-+
-+        if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0:
-+            return None
-+
-+        arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
-+
-+        for k, v in bbox.iteritems():
-+            bbox[k] = self._validExtend(v)
-+
-+        arr[bbox['btm_y'] : bbox['up_y'], bbox['btm_x'] : bbox['up_x']] = value
-+        #arr.flush()
-+        #del arr
-+
-+        self.ComputeCatsScatts([cat_id])
-+        #print "time"
-+        #print time.clock() - start_time
-+        return cat_id
-+
-+    def ComputeCatsScatts(self, cats_ids):
-+
-+        requested_dt = {}
-+        requested_dt_conds = {}
-+
-+        for c in cats_ids:
-+            requested_dt_conds[c] = self.scatt_conds_dt.GetCatScatts(c)
-+            requested_dt[c] = self.scatts_dt.GetCatScatts(c)
-+
-+        scatt_conds = self.scatt_conds_dt.GetData(requested_dt_conds)
-+        scatts = self.scatts_dt.GetData(requested_dt)
-+
-+        bands = self.an_data.GetBands()
-+
-+        cats_rasts = self.scatts_dt.GetCatsRasts()
-+        cats_rasts_conds = self.scatts_dt.GetCatsRastsConds()
-+
-+        returncode, scatts = ComputeScatts(self.an_data.GetRegion(), scatt_conds, bands,
-+                                           len(self.GetBands()), scatts, cats_rasts_conds, cats_rasts)
-+
-+        #print "ComputeScatts"
-+        #print returncode
-+        if returncode < 0:
-+            GException(_("Computing of scatter plots failed."))
-+        #self.scatts_dt.SetData(scatts)
-+
-+    def CatRastUpdater(self):
-+        return self.cat_rast_updater
-+    
-+    def UpdateCategoryWithPolygons(self, cat_id, scatts_pols, value):
-+        start_time = time.clock()
-+
-+        if cat_id not in self.scatts_dt.GetCategories():
-+            raise GException(_("Select category for editing."))
-+
-+        for scatt_id, coords in scatts_pols.iteritems():
-+
-+            if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0:
-+                return False
-+
-+            b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))
-+
-+            b1_info = self.an_data.GetBandInfo(b1)
-+            b2_info = self.an_data.GetBandInfo(b2)
-+
-+            raster_pol = RasterizePolygon(coords, b1_info['range'], b2_info['range'])
-+
-+            raster_ind = np.where(raster_pol > 0) 
-+            arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
-+
-+            arr[raster_ind] = value
-+            #arr.flush()
-+        
-+        self.ComputeCatsScatts([cat_id])
-+        return cat_id
-+
-+    def _validExtend(self, val):
-+        #TODO do it general
-+        if  val > 255:
-+            val = 255
-+        elif val < 0:
-+            val = 0
-+
-+        return val
-+
-+class CatRastUpdater:
-+
-+    def __init__(self, scatts_dt, an_data, core):
-+        self.scatts_dt = scatts_dt
-+        self.an_data = an_data # TODO may be confusing
-+        self.core = core
-+        self.vectMap = None
-+
-+    def SetVectMap(self, vectMap):
-+        self.vectMap = vectMap
-+
-+    def EditedFeature(self, new_bboxs, new_areas_cats, old_bboxs, old_areas_cats):
-+        #TODO possible optimization - bbox only of vertex and its two neighbours
-+
-+        bboxs = old_bboxs + new_bboxs
-+        areas_cats = old_areas_cats + new_areas_cats 
-+
-+        updated_cats = []
-+
-+        for i in range(len(areas_cats)):
-+            self._updateCatRast(bboxs[i], areas_cats[i], updated_cats)
-+        
-+        return updated_cats
-+
-+    def _updateCatRast(self, bbox, areas_cats, updated_cats):
-+
-+        rasterized_cats = []
-+        for c in range(len(areas_cats)):
-+
-+            if not areas_cats[c]:
-+                continue
-+
-+            layer = areas_cats[c].keys()[0]
-+            cat =  areas_cats[c][layer][0]
-+
-+            if cat in rasterized_cats:
-+                continue
-+
-+            rasterized_cats.append(cat)
-+            updated_cats.append(cat)
-+
-+            grass_region = self._create_grass_region_env(bbox)
-+
-+            #TODO hack
-+            patch_rast = "temp_scatt_patch"
-+            self._rasterize(grass_region, layer, cat, patch_rast)
-+
-+            region = self.an_data.GetRegion()
-+            ret = UpdateCatRast(patch_rast, region, self.scatts_dt.GetCatRastCond(cat))
-+            if ret < 0:
-+                GException(_("Patching category raster conditions file failed."))            
-+            RunCommand("g.remove",
-+                      rast = patch_rast)
-+
-+    def _rasterize(self, grass_region, layer, cat, out_rast):
-+
-+        #TODO different thread may be problem when user edits map
-+        environs = os.environ.copy()
-+        environs['GRASS_VECTOR_TEMPORARY'] = '1'
-+
-+        ret, text, msg = RunCommand("v.build",
-+                                      map = self.vectMap,
-+                                      getErrorMsg = True,
-+                                      read = True,
-+                                      env = environs)
-+
-+        if ret != 0:
-+            GException(_("v.build failed:\n%s" % msg))
-+
-+        environs = os.environ.copy()
-+        environs["GRASS_REGION"] = grass_region["GRASS_REGION"]
-+        environs['GRASS_VECTOR_TEMPORARY'] = '1'
-+
-+        ret, text, msg = RunCommand("v.to.rast",
-+                                    input = self.vectMap,
-+                                    use = "cat",
-+                                    layer = str(layer),
-+                                    cat = str(cat),
-+                                    output = out_rast,
-+                                    getErrorMsg = True,
-+                                    read = True,
-+                                    overwrite = True,
-+                                    env = environs)
-+
-+        if ret != 0:
-+            GException(_("v.to.rast failed:\n%s" % msg))
-+
-+    def _create_grass_region_env(self, bbox):
-+
-+        region = self.an_data.GetRegion()
-+        new_region = {}
-+
-+        if bbox["maxy"] <= region["s"]:
-+            return 0
-+        elif bbox["maxy"] >= region["n"]:
-+            new_region["n"] = bbox["maxy"]
-+        else:
-+            new_region["n"] = ceil((bbox["maxy"] - region["s"]) / region["nsres"]) * region["nsres"] + region["s"]
-+
-+        if bbox["miny"] >= region["n"]:
-+            return 0
-+        elif bbox["miny"] <= region["s"]:
-+            new_region["s"] = bbox["miny"]
-+        else:
-+            new_region["s"] = floor((bbox["miny"] - region["s"]) / region["nsres"]) * region["nsres"] + region["s"]
-+
-+        if bbox["maxx"] <= region["w"]:
-+            return 0
-+        elif bbox["maxx"] >= region["e"]:
-+            new_region["e"] = bbox["maxx"]
-+        else:
-+            new_region["e"] = ceil((bbox["maxx"] - region["w"]) / region["ewres"]) * region["ewres"] + region["w"]
-+
-+        if bbox["minx"] >= region["e"]:
-+            return 0
-+        elif bbox["minx"] <= region["w"]:
-+            new_region["w"] = bbox["minx"]
-+        else:
-+            new_region["w"] = floor((bbox["minx"] - region["w"]) / region["ewres"]) * region["ewres"] + region["w"]
-+
-+        #TODO check regions resolutin
-+        new_region["nsres"] = region["nsres"]
-+        new_region["ewres"] = region["ewres"]
-+
-+        return {"GRASS_REGION" :  grass.region_env(**new_region)}
-+
-+class AnalyzedData:
-+
-+    def __init__(self):
-+        
-+        self.bands = []
-+        self.bands_info = {}
-+
-+        self.region = None
-+
-+    def GetRegion(self):
-+        return self.region
-+
-+    def Create(self, bands):
-+
-+        self.bands = bands
-+        self.region = None
-+
-+        ret, region, msg = RunCommand("g.region",
-+                                      flags = "gp",
-+                                      getErrorMsg = True,
-+                                      read = True)
-+
-+        if  ret != 0:
-+            raise GException("g.region failed:\n%s" % msg)
-+
-+
-+        self.bands_info = {}
-+        for b in bands:
-+            self.bands_info[b] = self._getRasterInfo(b)
-+            if self.bands_info[b]["datatype"] != "CELL":
-+                raise GException(_("Raster <%s> is not <CELL> type.") % (b))
-+            #TODO size of raster check
-+
-+        self.region = self._parseRegion(region)
-+
-+    def _getRasterInfo(self, rast):
-+        """
-+        """
-+        ret, out, msg = RunCommand("r.info",
-+                                    map = rast,
-+                                    flags = "rg",
-+                                    getErrorMsg = True,
-+                                    read = True)
-+
-+        if  ret != 0:
-+            raise GException("r.info failed:\n%s" % msg)
-+
-+        out = out.split("\n")
-+        raster_info = {} 
-+
-+        for b in out:
-+            if not b.strip():
-+                continue
-+            k, v = b.split("=")
-+            if k == "datatype":
-+                pass
-+            elif k in ['rows', 'cols', 'cells', 'min', 'max']:
-+                v = int(v)
-+            else:
-+                v = float(v)
-+
-+            raster_info[k] = v
-+
-+        raster_info['range'] = raster_info['max'] - raster_info['min'] + 1
-+        return raster_info
-+
-+    def GetBands(self):
-+        return self.bands
-+
-+    def GetBandInfo(self, band_id):
-+        band = self.bands[band_id]
-+        return self.bands_info[band]
-+
-+    def _parseRegion(self, region_str):
-+
-+        region = {}
-+        region_str = region_str.splitlines()
-+
-+        for param in region_str:
-+            k, v = param.split("=")
-+            if k in ["rows", "cols", "cells"]:
-+                v = int(v)
-+            else:
-+                v = float(v)
-+            region[k] = v
-+
-+        return region
-+
-+class ScattPlotsCondsData:
-+
-+    def __init__(self, an_data):
-+
-+        self.an_data = an_data
-+
-+        #TODO
-+        self.max_n_cats = 10
-+    
-+        self.dtype = 'uint8'
-+        self.type = 1;
-+        self.CleanUp()
-+
-+    def CleanUp(self):
-+    
-+        self.cats = {}
-+
-+        self.n_scatts = -1
-+        self.n_bands = -1
-+
-+        for cat_id in self.cats.keys():
-+            self.DeleteCategory(cat_id)
-+
-+    def Create(self, n_bands):
-+
-+        self.CleanUp()
-+
-+        self.n_scatts =  (n_bands - 1) * n_bands / 2;
-+        self.n_bands = n_bands
-+
-+        self.AddCategory(cat_id = 0)
-+
-+    def AddCategory(self, cat_id):
-+
-+        if cat_id not in self.cats.keys():
-+            self.cats[cat_id] = {}
-+            return cat_id
-+        return -1
-+
-+    def DeleteCategory(self, cat_id):
-+
-+        if cat_id not in self.cats.keys():
-+            return False
-+
-+        for scatt in self.cats[cat_id].itervalues():
-+            del scatt['np_vals']
-+
-+        del self.cats[cat_id]
-+
-+        return True
-+
-+    def GetCategories(self):
-+        return self.cats.keys()
-+
-+    def GetCatScatts(self, cat_id):
-+
-+        if not self.cats.has_key(cat_id):
-+            return False
-+
-+        return self.cats[cat_id].keys()
-+
-+
-+    def AddScattPlot(self, cat_id, scatt_id):
-+
-+        if not self.cats.has_key(cat_id):
-+            return -1
-+
-+        if self.cats[cat_id].has_key(scatt_id):
-+            return 0
-+
-+        b_i = self.GetBandsInfo(scatt_id)
-+
-+        shape = (b_i['b2']['max'] - b_i['b2']['min'] + 1, b_i['b1']['max'] - b_i['b1']['min'] + 1)
-+
-+        np_vals = np.memmap(grass.tempfile(), dtype=self.dtype, mode='w+', shape = shape)
-+
-+        self.cats[cat_id][scatt_id] = {
-+                                        'np_vals' : np_vals,
-+                                      }
-+
-+        return 1
-+
-+    def GetBandsInfo(self, scatt_id):
-+        b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))
-+
-+        b1_info = self.an_data.GetBandInfo(b1)
-+        b2_info = self.an_data.GetBandInfo(b2)
-+
-+        bands_info = {'b1' : b1_info,
-+                      'b2' : b2_info}
-+
-+        return bands_info
-+
-+    def DeleScattPlot(self, cat_id, scatt_id):
-+
-+        if not self.cats.has_key(cat_id):
-+            return False
-+
-+        if not self.cats[cat_id].has_key(scatt_id):
-+            return False
-+
-+        del self.cats[cat_id][scatt_id]
-+        return True
-+
-+    def GetValuesArr(self, cat_id, scatt_id):
-+
-+        if not self.cats.has_key(cat_id):
-+            return None
-+
-+        if not self.cats[cat_id].has_key(scatt_id):
-+            return None
-+
-+        return self.cats[cat_id][scatt_id]['np_vals']
-+
-+    def GetData(self, requested_dt):
-+        
-+        cats = {}
-+        for cat_id, scatt_ids in requested_dt.iteritems():
-+            if not cats.has_key(cat_id):
-+                cats[cat_id] = {}
-+            for scatt_id in scatt_ids:
-+                # if key is missing condition is always True (full scatter plor is computed)
-+                if self.cats[cat_id].has_key(scatt_id):
-+                    cats[cat_id][scatt_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
-+                                              'bands_info' : self.GetBandsInfo(scatt_id)}
-+                        
-+        return cats
-+
-+    def SetData(self, cats):
-+        
-+        for cat_id, scatt_ids in cats.iteritems():            
-+            for scatt_id in scatt_ids:
-+                # if key is missing condition is always True (full scatter plor is computed)
-+                if self.cats[cat_id].has_key(scatt_id):
-+                    self.cats[cat_id][scatt_id]['np_vals'] = cats[cat_id][scatt_id]['np_vals']
-+
-+    def GetScatt(self, scatt_id, cats_ids = None):
-+        scatts = {}
-+        for cat_id in self.cats.iterkeys():
-+            if cats_ids and cat_id not in cats_ids:
-+                continue
-+            if not self.cats[cat_id].has_key(scatt_id):
-+                continue
-+
-+            scatts[cat_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
-+                              'bands_info' : self.GetBandsInfo(scatt_id)}
-+        return scatts
-+
-+                   
-+class ScattPlotsData(ScattPlotsCondsData):
-+
-+    def __init__(self, an_data):
-+
-+        self.cats_rasts = {}
-+        self.cats_rasts_conds = {}    
-+        self.scatts_ids = []    
-+
-+        ScattPlotsCondsData.__init__(self, an_data)
-+
-+        self.dtype = 'uint32'
-+
-+        #TODO
-+        self.type = 0
-+
-+    def AddCategory(self, cat_id):
-+        cat_id = ScattPlotsCondsData.AddCategory(self, cat_id)
-+        if cat_id < 0:
-+            return cat_id
-+
-+        for scatt_id in self.scatts_ids:
-+            ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
-+
-+        if cat_id == 0:
-+            self.cats_rasts_conds[cat_id] = None
-+            self.cats_rasts[cat_id] = None
-+        else:
-+            self.cats_rasts_conds[cat_id] = grass.tempfile()
-+            self.cats_rasts[cat_id] = "temp_cat_rast_%d" % cat_id
-+            region = self.an_data.GetRegion()
-+            CreateCatRast(region, self.cats_rasts_conds[cat_id])
-+
-+        return cat_id
-+
-+    def DeleteCategory(self, cat_id):
-+
-+        ScattPlotsCondsData.DeleteCategory(self, cat_id)
-+
-+        grass.try_remove(self.cats_rasts_conds[cat_id])
-+        del self.cats_rasts_conds[cat_id]
-+
-+        grass.try_remove(self.cats_rasts[cat_id])
-+        del self.cats_rasts[cat_id]
-+
-+        return True
-+
-+    def AddScattPlot(self, scatt_id):
-+        
-+        if scatt_id in self.scatts_ids:
-+            return False
-+
-+        self.scatts_ids.append(scatt_id)
-+        for cat_id in self.cats.iterkeys():
-+                ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
-+                self.cats[cat_id][scatt_id]['ellipse'] = None
-+
-+        return True
-+
-+    def DeleteScatterPlot(self, scatt_id):
-+        
-+        if scatt_id not in self.scatts_ids:
-+            return False
-+
-+        self.scatts_ids.remove(scatt_id)
-+
-+        for cat_id in self.cats.iterkeys():
-+                ScattPlotsCondsData.DeleteScattPlot(self, cat_id, scatt_id)
-+
-+        return True
-+
-+    def GetEllipses(self, scatt_id):
-+        if scatt_id not in self.scatts_ids:
-+            return False
-+
-+        scatts = {}
-+        for cat_id in self.cats.iterkeys():
-+            if cat_id == 0:
-+                continue
-+            scatts[cat_id] = self._getEllipse(cat_id, scatt_id)
-+
-+        return scatts
-+
-+    def _getEllipse(self, cat_id, scatt_id):
-+        # Joe Kington
-+        # http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals
-+
-+        nstd = 2
-+        data = np.copy(self.cats[cat_id][scatt_id]['np_vals'])
-+
-+        sel_pts = np.where(data > 0)
-+
-+        x = sel_pts[1]
-+        y = sel_pts[0]
-+
-+        flatten_data = data.reshape([-1])
-+        flatten_sel_pts = np.nonzero(flatten_data)
-+        weights = flatten_data[flatten_sel_pts]
-+        if len(weights) == 0:
-+            return None
-+
-+        x_avg = np.average(x, weights=weights)
-+        y_avg = np.average(y, weights=weights)
-+        pos = np.array([x_avg, y_avg])
-+
-+        x_diff = (x - x_avg)
-+        y_diff = (y - y_avg)
-+        
-+        x_diff = (x - x_avg) 
-+        y_diff = (y - y_avg) 
-+
-+        diffs = x_diff * y_diff.T
-+        cov = np.dot(diffs, weights) / (np.sum(weights) - 1)
-+
-+        diffs = x_diff * x_diff.T
-+        var_x = np.dot(diffs, weights) /  (np.sum(weights) - 1)
-+        
-+        diffs = y_diff * y_diff.T
-+        var_y = np.dot(diffs, weights) /  (np.sum(weights) - 1)
-+
-+        cov = np.array([[var_x, cov],[cov, var_y]])
-+
-+        def eigsorted(cov):
-+            vals, vecs = np.linalg.eigh(cov)
-+            order = vals.argsort()[::-1]
-+            return vals[order], vecs[:,order]
-+
-+        vals, vecs = eigsorted(cov)
-+        theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
-+
-+        # Width and height are "full" widths, not radius
-+        width, height = 2 * nstd * np.sqrt(vals)
-+
-+        ellipse = {'pos' : pos, 
-+                   'width' : width,
-+                   'height' : height,
-+                   'theta' : theta}
-+
-+        del data
-+        del flatten_data
-+        del flatten_sel_pts
-+        del weights
-+        del sel_pts
-+        return ellipse
-+
-+    def CleanUp(self):
-+
-+        ScattPlotsCondsData.CleanUp(self)        
-+        for tmp in self.cats_rasts_conds:
-+            grass.try_remove(tmp) 
-+        for tmp in self.cats_rasts:
-+            grass.try_remove(tmp) 
-+
-+        self.cats_rasts = {}
-+        self.cats_rasts_conds = {}
-+
-+
-+    def GetCatRast(self, cat_id):
-+        return self.cats_rasts[cat_id]
-+
-+    def GetCatRastCond(self, cat_id):
-+        return self.cats_rasts_conds[cat_id]
-+
-+    def GetCatsRastsConds(self):
-+        max_cat_id = max(self.cats_rasts_conds.keys())
-+
-+        cats_rasts_conds = [''] * (max_cat_id + 1)
-+        for i_cat_id, i_rast in self.cats_rasts_conds.iteritems():
-+            cats_rasts_conds[i_cat_id] = i_rast
-+
-+        return cats_rasts_conds
-+
-+    def GetCatsRasts(self):
-+        max_cat_id = max(self.cats_rasts.keys())
-+
-+        cats_rasts = [''] * (max_cat_id + 1)
-+        for i_cat_id, i_rast in self.cats_rasts.iteritems():
-+            cats_rasts[i_cat_id] = i_rast
-+
-+        return cats_rasts
-+
-+
-+def RasterizePolygon(pol, height, width):
-+
-+    # Joe Kington
-+    # http://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask
-+
-+    #poly_verts = [(1,1), (1,4), (4,4),(4,1), (1,1)]
-+
-+    nx = width + 1
-+    ny = height + 1
-+
-+    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
-+    x, y = x.flatten(), y.flatten()
-+
-+    points = np.vstack((x,y)).T
-+
-+    p = Path(pol)
-+    grid = p.contains_points(points)
-+    grid = grid.reshape((ny,nx))
-+
-+    raster = np.zeros((height, width), dtype=np.uint8)#TODO bool
-+
-+    #TODO shift by 0.5
-+    B = np.ones((2,2))/4
-+    raster = convolve2d(grid, B, 'valid')
-+
-+
-+    #TODO this part is very inefficient, replace it with better solution
-+    #for (y, x), value in np.ndenumerate(grid):
-+
-+    #    if x >= width - 1: continue 
-+    #    if y >= height - 1: continue
-+
-+    #    if grid[y, x]:
-+    #        raster[y, x] = 1
-+    #        raster[y + 1, x] = 1
-+    #        raster[y, x + 1] = 1
-+    #        raster[y + 1, x + 1] = 1
-+
-+    return raster
-+
-+#TODO move to utils?
-+def idScattToidBands(scatt_id, n_bands):
-+ 
-+    n_b1 = n_bands - 1
-+
-+    band_1 = (int) ((2 * n_b1 + 1 - sqrt(((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2)
-+
-+    band_2 = scatt_id - (band_1 * (2 * n_b1 + 1) - band_1 * band_1) / 2 + band_1 + 1
-+
-+    return band_1, band_2
-+
-+def idBandsToidScatt(band_1_id, band_2_id, n_bands):
-+
-+    if band_2_id <  band_1_id:
-+        tmp = band_1
-+        band_1_id = band_2_id
-+        band_2_id = tmp
-+
-+    n_b1 = n_bands - 1
-+
-+    scatt_id = (band_1_id * (2 * n_b1 + 1) - band_1_id * band_1_id) / 2 + band_2_id - band_1_id - 1
-+
-+    return scatt_id
-+
-Index: gui/wxpython/vdigit/wxdigit.py
-===================================================================
---- gui/wxpython/vdigit/wxdigit.py	(revision 57601)
-+++ gui/wxpython/vdigit/wxdigit.py	(working copy)
-@@ -17,7 +17,7 @@
- (and NumPy would be an excellent candidate for acceleration via
- e.g. OpenCL or CUDA; I'm surprised it hasn't happened already).
- 
--(C) 2007-2011 by the GRASS Development Team
-+(C) 2007-2011, 2013 by the GRASS Development Team
- 
- This program is free software under the GNU General Public License
- (>=v2). Read the file COPYING that comes with GRASS for details.
-@@ -27,6 +27,8 @@
- 
- import grass.script.core as grass
- 
-+from grass.pydispatch.signal import Signal
-+
- from core.gcmd        import GError
- from core.debug       import Debug
- from core.settings    import UserSettings
-@@ -176,7 +178,21 @@
-         
-         if self.poMapInfo:
-             self.InitCats()
--        
-+
-+        self.emit_signals = False
-+
-+        # signals which describes features changes during digitization, 
-+        # activate them using EmitSignals method 
-+        #TODO signal for errors?
-+        self.featureAdded = Signal('IVDigit.featureAdded')
-+        self.areasDeleted = Signal('IVDigit.areasDeleted')
-+        self.vertexMoved = Signal('IVDigit.vertexMoved')
-+        self.vertexAdded = Signal('IVDigit.vertexAdded')
-+        self.vertexRemoved = Signal('IVDigit.vertexRemoved')
-+        self.featuresDeleted = Signal('IVDigit.featuresDeleted')
-+        self.featuresMoved = Signal('IVDigit.featuresMoved')
-+        self.lineEdited = Signal('IVDigit.lineEdited')
-+
-     def __del__(self):
-         Debug.msg(1, "IVDigit.__del__()")
-         Vect_destroy_line_struct(self.poPoints)
-@@ -188,7 +204,12 @@
-             Vect_close(self.poBgMapInfo)
-             self.poBgMapInfo = self.popoBgMapInfo = None
-             del self.bgMapInfo
--        
-+     
-+    def EmitSignals(self, emit):
-+        """!Activate/deactivate signals which describes features changes during digitization.
-+        """
-+        self.emit_signals = emit
-+
-     def CloseBackgroundMap(self):
-         """!Close background vector map"""
-         if not self.poBgMapInfo:
-@@ -394,7 +415,6 @@
-         
-         @return tuple (number of added features, feature ids)
-         """
--        
-         layer = self._getNewFeaturesLayer()
-         cat = self._getNewFeaturesCat()
-         
-@@ -419,10 +439,14 @@
-             return (-1, None)
-         
-         self.toolbar.EnableUndo()
--        
--        return self._addFeature(vtype, points, layer, cat,
--                                self._getSnapMode(), self._display.GetThreshold())
--    
-+
-+        ret = self._addFeature(vtype, points, layer, cat,
-+                               self._getSnapMode(), self._display.GetThreshold())
-+        if ret[0] > -1 and self.emit_signals:
-+            self.featureAdded.emit(new_bboxs = [self._createBbox(points)], new_areas_cats = [[{layer : [cat]}, None]])
-+
-+        return ret
-+
-     def DeleteSelectedLines(self):
-         """!Delete selected features
- 
-@@ -434,16 +458,27 @@
-         # collect categories for deleting if requested
-         deleteRec = UserSettings.Get(group = 'vdigit', key = 'delRecord', subkey = 'enabled')
-         catDict = dict()
-+
-+        old_bboxs = []
-+        old_areas_cats = []
-         if deleteRec:
-             for i in self._display.selected['ids']:
-+                
-                 if Vect_read_line(self.poMapInfo, None, self.poCats, i) < 0:
-                     self._error.ReadLine(i)
-                 
--                cats = self.poCats.contents
--                for j in range(cats.n_cats):
--                    if cats.field[j] not in catDict.keys():
--                        catDict[cats.field[j]] = list()
--                    catDict[cats.field[j]].append(cats.cat[j])
-+                if self.emit_signals:
-+                    ret = self._getLineAreaBboxCats(i)
-+                    if ret:
-+                        old_bboxs += ret[0]
-+                        old_areas_cats += ret[1]
-+                
-+                # catDict was not used -> put into comment
-+                #cats = self.poCats.contents
-+                #for j in range(cats.n_cats):
-+                #    if cats.field[j] not in catDict.keys():
-+                #        catDict[cats.field[j]] = list()
-+                #    catDict[cats.field[j]].append(cats.cat[j])
-         
-         poList = self._display.GetSelectedIList()
-         nlines = Vedit_delete_lines(self.poMapInfo, poList)
-@@ -456,7 +491,10 @@
-                 self._deleteRecords(catDict)
-             self._addChangeset()
-             self.toolbar.EnableUndo()
--        
-+
-+            if self.emit_signals:
-+                self.featuresDeleted.emit(old_bboxs = old_bboxs, old_areas_cats = old_areas_cats)
-+
-         return nlines
-             
-     def _deleteRecords(self, cats):
-@@ -512,22 +550,173 @@
- 
-         @return number of deleted 
-         """
-+        if len(self._display.selected['ids']) < 1:
-+            return 0
-+        
-         poList = self._display.GetSelectedIList()
-         cList  = poList.contents
-         
-         nareas = 0
-+        old_bboxs = []
-+        old_areas_cats = []
-+
-         for i in range(cList.n_values):
-+
-             if Vect_get_line_type(self.poMapInfo, cList.value[i]) != GV_CENTROID:
-                 continue
--            
-+
-+            if self.emit_signals:
-+                area = Vect_get_centroid_area(self.poMapInfo, cList.value[i]);
-+                if area > 0: 
-+                    bbox, cats = self._getaAreaBboxCats(area)
-+                    old_bboxs += bbox
-+                    old_areas_cats += cats
-+
-             nareas += Vedit_delete_area_centroid(self.poMapInfo, cList.value[i])
-         
-         if nareas > 0:
-             self._addChangeset()
-             self.toolbar.EnableUndo()
-+            if self.emit_signals:
-+                self.areasDeleted.emit(old_bboxs = old_bboxs, old_areas_cats = old_areas_cats)        
-+
-+        return nareas
-+   
-+    def _getLineAreaBboxCats(self, ln_id):
-+        ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
-+
-+        if ltype == GV_CENTROID:
-+            #TODO centroid opttimization, can be adited also its area -> it will appear two times in new_ lists
-+            return self._getCentroidAreaBboxCats(ln_id)
-+        else: 
-+            return [self._getBbox(ln_id)], [self._getLineAreasCategories(ln_id)]
-+
-+
-+    def _getCentroidAreaBboxCats(self, centroid):
-+        if not Vect_line_alive(self.poMapInfo, centroid):
-+            return None
-+
-+        area = Vect_get_centroid_area(self.poMapInfo, centroid)  
-+        if area > 0:
-+            return self._getaAreaBboxCats(area)
-+        else:
-+            return None
-+
-+    def _getaAreaBboxCats(self, area):
-+
-+        po_b_list = Vect_new_list()
-+        Vect_get_area_boundaries(self.poMapInfo, area, po_b_list);
-+        b_list = po_b_list.contents
-+
-+        geoms = []
-+        areas_cats = []
-+
-+        if b_list.n_values > 0:
-+            for i_line in range(b_list.n_values):
-+
-+                line = b_list.value[i_line];
-+
-+                geoms.append(self._getBbox(abs(line)))
-+                areas_cats.append(self._getLineAreasCategories(abs(line)))
-         
--        return nareas
-+        Vect_destroy_list(po_b_list);
-+
-+        return geoms, areas_cats
-+
-+    def _getLineAreasCategories(self, ln_id):
-+        if not Vect_line_alive (self.poMapInfo, ln_id):
-+            return []
-+
-+        ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
-+        if ltype != GV_BOUNDARY:
-+            return []
-+
-+        cats = [None, None]
-+
-+        left = c_int()
-+        right = c_int()
-+
-+        if Vect_get_line_areas(self.poMapInfo, ln_id, pointer(left), pointer(right)) == 1:
-+            areas = [left.value, right.value]
-+
-+            for i, a in enumerate(areas):
-+                if a > 0: 
-+                    centroid = Vect_get_area_centroid(self.poMapInfo, a)
-+                    if centroid <= 0:
-+                        continue
-+                    c = self._getCategories(centroid)
-+                    if c:
-+                        cats[i] = c
-+
-+        return cats
-+
-+    def _getCategories(self, ln_id):
-+        if not Vect_line_alive (self.poMapInfo, ln_id):
-+            return none
-+
-+        poCats = Vect_new_cats_struct()
-+        if Vect_read_line(self.poMapInfo, None, poCats, ln_id) < 0:
-+            Vect_destroy_cats_struct(poCats)
-+            return None
-+
-+        cCats = poCats.contents
-+
-+        cats = {}
-+        for j in range(cCats.n_cats):
-+            if cats.has_key(cCats.field[j]):
-+                cats[cCats.field[j]].append(cCats.cat[j])
-+            else:
-+                cats[cCats.field[j]] = [cCats.cat[j]]
-     
-+        Vect_destroy_cats_struct(poCats)
-+        return cats
-+
-+    def _getBbox(self, ln_id):
-+        if not Vect_line_alive (self.poMapInfo, ln_id):
-+            return None
-+
-+        poPoints = Vect_new_line_struct()
-+        if Vect_read_line(self.poMapInfo, poPoints, None, ln_id) < 0:
-+            Vect_destroy_line_struct(poPoints)
-+            return []
-+
-+        geom = self._convertGeom(poPoints)
-+        bbox = self._createBbox(geom)
-+        Vect_destroy_line_struct(poPoints)
-+        return bbox
-+
-+    def _createBbox(self, points):
-+
-+        bbox = {}
-+        for pt in points:
-+            if not bbox.has_key('maxy'):
-+                bbox['maxy'] = pt[1]
-+                bbox['miny'] = pt[1]
-+                bbox['maxx'] = pt[0]
-+                bbox['minx'] = pt[0]
-+                continue
-+                
-+            if   bbox['maxy'] < pt[1]:
-+                bbox['maxy'] = pt[1]
-+            elif bbox['miny'] > pt[1]:
-+                bbox['miny'] = pt[1]
-+                
-+            if   bbox['maxx'] < pt[0]:
-+                bbox['maxx'] = pt[0]
-+            elif bbox['minx'] > pt[0]:
-+                bbox['minx'] = pt[0]
-+        return bbox
-+
-+    def _convertGeom(self, poPoints):
-+
-+        Points = poPoints.contents
-+
-+        pts_geom = []
-+        for j in range(Points.n_points):
-+            pts_geom.append((Points.x[j], Points.y[j]))
-+
-+        return pts_geom
-+
-     def MoveSelectedLines(self, move):
-         """!Move selected features
- 
-@@ -536,16 +725,45 @@
-         if not self._checkMap():
-             return -1
-         
-+        nsel = len(self._display.selected['ids'])
-+        if nsel < 1:
-+            return -1   
-+        
-         thresh = self._display.GetThreshold()
-         snap   = self._getSnapMode()
-         
-         poList = self._display.GetSelectedIList()
-+
-+        if self.emit_signals:
-+            old_bboxs = []
-+            old_areas_cats = []
-+            for sel_id in self._display.selected['ids']:
-+                ret = self._getLineAreaBboxCats(sel_id)
-+                if ret:
-+                    old_bboxs += ret[0]
-+                    old_areas_cats += ret[1]
-+        
-+            Vect_set_updated(self.poMapInfo, 1)
-+            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
-+        
-         nlines = Vedit_move_lines(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
-                                   poList,
-                                   move[0], move[1], 0,
-                                   snap, thresh)
-+
-         Vect_destroy_list(poList)
--        
-+
-+        if nlines > 0 and self.emit_signals:
-+            new_bboxs = []
-+            new_areas_cats = []
-+            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
-+            for i in range(n_up_lines_old, n_up_lines):
-+                new_id = Vect_get_updated_line(self.poMapInfo, i)
-+                ret = self._getLineAreaBboxCats(new_id)
-+                if ret:
-+                    new_bboxs += ret[0]
-+                    new_areas_cats += ret[1]
-+
-         if nlines > 0 and self._settings['breakLines']:
-             for i in range(1, nlines):
-                 self._breakLineAtIntersection(nlines + i, None, changeset)
-@@ -553,7 +771,13 @@
-         if nlines > 0:
-             self._addChangeset()
-             self.toolbar.EnableUndo()
--        
-+            
-+            if self.emit_signals:
-+                self.featuresMoved.emit(new_bboxs = new_bboxs,
-+                                        old_bboxs = old_bboxs, 
-+                                        old_areas_cats = old_areas_cats, 
-+                                        new_areas_cats = new_areas_cats)
-+
-         return nlines
- 
-     def MoveSelectedVertex(self, point, move):
-@@ -571,12 +795,21 @@
-         
-         if len(self._display.selected['ids']) != 1:
-             return -1
--        
-+
-+        # move only first found vertex in bbox 
-+        poList = self._display.GetSelectedIList()
-+
-+        if self.emit_signals:
-+            cList = poList.contents
-+            old_bboxs = [self._getBbox(cList.value[0])]
-+            old_areas_cats = [self._getLineAreasCategories(cList.value[0])]
-+
-+            Vect_set_updated(self.poMapInfo, 1)
-+            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
-+
-         Vect_reset_line(self.poPoints)
-         Vect_append_point(self.poPoints, point[0], point[1], 0.0)
--        
--        # move only first found vertex in bbox 
--        poList = self._display.GetSelectedIList()
-+
-         moved = Vedit_move_vertex(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
-                                   poList, self.poPoints,
-                                   self._display.GetThreshold(type = 'selectThresh'),
-@@ -584,7 +817,17 @@
-                                   move[0], move[1], 0.0,
-                                   1, self._getSnapMode())
-         Vect_destroy_list(poList)
--        
-+
-+        if moved > 0 and self.emit_signals:
-+            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
-+
-+            new_bboxs = []
-+            new_areas_cats = []
-+            for i in range(n_up_lines_old, n_up_lines):
-+                new_id = Vect_get_updated_line(self.poMapInfo, i)
-+                new_bboxs.append(self._getBbox(new_id))
-+                new_areas_cats.append(self._getLineAreasCategories(new_id))
-+
-         if moved > 0 and self._settings['breakLines']:
-             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
-                                           None)
-@@ -592,7 +835,13 @@
-         if moved > 0:
-             self._addChangeset()
-             self.toolbar.EnableUndo()
--        
-+
-+            if self.emit_signals:
-+                self.vertexMoved.emit(new_bboxs = new_bboxs,  
-+                                      new_areas_cats = new_areas_cats, 
-+                                      old_areas_cats = old_areas_cats, 
-+                                      old_bboxs = old_bboxs)
-+
-         return moved
- 
-     def AddVertex(self, coords):
-@@ -681,6 +930,10 @@
-             self._error.ReadLine(line)
-             return -1
-         
-+        if self.emit_signals:
-+            old_bboxs = [self._getBbox(line)]
-+            old_areas_cats = [self._getLineAreasCategories(line)]
-+
-         # build feature geometry
-         Vect_reset_line(self.poPoints)
-         for p in coords:
-@@ -696,6 +949,9 @@
-         
-         newline = Vect_rewrite_line(self.poMapInfo, line, ltype,
-                                     self.poPoints, self.poCats)
-+        if newline > 0 and self.emit_signals:
-+            new_geom = [self._getBbox(newline)]
-+            new_areas_cats = [self._getLineAreasCategories(newline)]
-         
-         if newline > 0 and self._settings['breakLines']:
-             self._breakLineAtIntersection(newline, None)
-@@ -703,7 +959,13 @@
-         if newline > 0:
-             self._addChangeset()
-             self.toolbar.EnableUndo()
--        
-+    
-+            if self.emit_signals:
-+                self.lineEdited.emit(old_bboxs = old_bboxs, 
-+                                     old_areas_cats = old_areas_cats, 
-+                                     new_bboxs = new_bboxs, 
-+                                     new_areas_cats = new_areas_cats)
-+
-         return newline
- 
-     def FlipLine(self):
-@@ -1514,6 +1776,16 @@
-             return 0
-         
-         poList  = self._display.GetSelectedIList()
-+
-+        if self.emit_signals:
-+            cList = poList.contents
-+            
-+            old_bboxs = [self._getBbox(cList.value[0])]
-+            old_areas_cats = [self._getLineAreasCategories(cList.value[0])]
-+
-+            Vect_set_updated(self.poMapInfo, 1)
-+            n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
-+
-         Vect_reset_line(self.poPoints)
-         Vect_append_point(self.poPoints, coords[0], coords[1], 0.0)
-         
-@@ -1525,15 +1797,35 @@
-         else:
-             ret = Vedit_remove_vertex(self.poMapInfo, poList,
-                                       self.poPoints, thresh)
-+
-         Vect_destroy_list(poList)
-+
-+        if ret > 0 and self.emit_signals:
-+            new_bboxs = []
-+            new_areas_cats = []
-+
-+            n_up_lines = Vect_get_num_updated_lines(self.poMapInfo)
-+            for i in range(n_up_lines_old, n_up_lines):
-+                new_id = Vect_get_updated_line(self.poMapInfo, i)
-+                new_areas_cats.append(self._getLineAreasCategories(new_id))
-+                new_bboxs.append(self._getBbox(new_id))
-         
-         if not add and ret > 0 and self._settings['breakLines']:
-             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
-                                           None)
--        
-+
-         if ret > 0:
-             self._addChangeset()
--                
-+
-+        if ret > 0 and self.emit_signals:
-+            if add:
-+                self.vertexAdded.emit(old_bboxs = old_bboxs, new_bboxs = new_bboxs)
-+            else:
-+                self.vertexRemoved.emit(old_bboxs = old_bboxs, 
-+                                        new_bboxs = new_bboxs,
-+                                        old_areas_cats = old_areas_cats,
-+                                        new_areas_cats = new_areas_cats)
-+
-         return 1
-     
-     def GetLineCats(self, line):
-Index: gui/wxpython/vdigit/toolbars.py
-===================================================================
---- gui/wxpython/vdigit/toolbars.py	(revision 57601)
-+++ gui/wxpython/vdigit/toolbars.py	(working copy)
-@@ -17,6 +17,7 @@
- import wx
- 
- from grass.script import core as grass
-+from grass.pydispatch.signal import Signal
- 
- from gui_core.toolbars  import BaseToolbar, BaseIcons
- from gui_core.dialogs   import CreateNewVector
-@@ -42,6 +43,8 @@
-         self.digit         = None
-         self._giface       = giface
-         
-+        self.editingStarted = Signal("VDigitToolbar.editingStarted")
-+
-         # currently selected map layer for editing (reference to MapLayer instance)
-         self.mapLayer = None
-         # list of vector layers from Layer Manager (only in the current mapset)
-@@ -860,6 +863,7 @@
-             alpha = int(opacity * 255)
-             self.digit.GetDisplay().UpdateSettings(alpha = alpha)
-         
-+        self.editingStarted.emit(vectMap = mapLayer.GetName(), digit = self.digit)
-         return True
- 
-     def StopEditing(self):
-Index: gui/wxpython/Makefile
-===================================================================
---- gui/wxpython/Makefile	(revision 57601)
-+++ gui/wxpython/Makefile	(working copy)
-@@ -13,7 +13,7 @@
- 	$(wildcard animation/* core/*.py dbmgr/* gcp/*.py gmodeler/* \
- 	gui_core/*.py iclass/* lmgr/*.py location_wizard/*.py mapwin/*.py mapdisp/*.py \
- 	mapswipe/* modules/*.py nviz/*.py psmap/* rlisetup/* timeline/* vdigit/* \
--	vnet/*.py web_services/*.py wxplot/*.py) \
-+	vnet/*.py web_services/*.py wxplot/*.py scatt_plot/*.py) \
- 	gis_set.py gis_set_error.py wxgui.py README
- 
- DSTFILES := $(patsubst %,$(ETCDIR)/%,$(SRCFILES)) \
-@@ -21,8 +21,9 @@
- 
- PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,animation core dbmgr gcp gmodeler \
- 	gui_core iclass lmgr location_wizard mapwin mapdisp modules nviz psmap \
--	mapswipe vdigit wxplot web_services rlisetup vnet timeline)
-+	mapswipe vdigit wxplot web_services rlisetup vnet timeline scatt_plot)
- 
-+
- DSTDIRS := $(patsubst %,$(ETCDIR)/%,icons scripts xml)
- 
- default: $(DSTFILES)
-Index: gui/wxpython/mapdisp/frame.py
-===================================================================
---- gui/wxpython/mapdisp/frame.py	(revision 57601)
-+++ gui/wxpython/mapdisp/frame.py	(working copy)
-@@ -225,6 +225,7 @@
-         #
-         self.dialogs = {}
-         self.dialogs['attributes'] = None
-+        self.dialogs['scatt_plot'] = None
-         self.dialogs['category'] = None
-         self.dialogs['barscale'] = None
-         self.dialogs['legend'] = None
-@@ -1168,6 +1169,19 @@
-         """!Returns toolbar with zooming tools"""
-         return self.toolbars['map']
- 
-+    def OnScatterplot2(self, event):
-+        """!Init interactive scatterplot tools
-+        """
-+        if self.dialogs['scatt_plot']:
-+            self.dialogs['scatt_plot'].Raise()
-+            return
-+
-+        from scatt_plot.dialogs import ScattPlotMainDialog
-+        self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface)
-+        
-+        self.dialogs['scatt_plot'].CenterOnScreen()
-+        self.dialogs['scatt_plot'].Show()
-+
-     def OnVNet(self, event):
-         """!Dialog for v.net* modules 
-         """
-Index: gui/wxpython/mapdisp/toolbars.py
-===================================================================
---- gui/wxpython/mapdisp/toolbars.py	(revision 57601)
-+++ gui/wxpython/mapdisp/toolbars.py	(working copy)
-@@ -239,7 +239,8 @@
-                       (MapIcons["scatter"],     self.parent.OnScatterplot),
-                       (MapIcons["histogram"],   self.parent.OnHistogramPyPlot),
-                       (BaseIcons["histogramD"], self.parent.OnHistogram),
--                      (MapIcons["vnet"],        self.parent.OnVNet)))
-+                      (MapIcons["vnet"],        self.parent.OnVNet),
-+                      (MapIcons["scatter"],     self.parent.OnScatterplot2)))
-         
-     def OnDecoration(self, event):
-         """!Decorations overlay menu
-Index: gui/wxpython/iclass/frame.py
-===================================================================
---- gui/wxpython/iclass/frame.py	(revision 57601)
-+++ gui/wxpython/iclass/frame.py	(working copy)
-@@ -64,6 +64,8 @@
-                                IClassExportAreasDialog, IClassMapDialog
- from iclass.plots       import PlotPanel
- 
-+from grass.pydispatch.signal import Signal
-+
- class IClassMapFrame(DoubleMapFrame):
-     """! wxIClass main frame
-     
-@@ -114,6 +116,10 @@
-             lambda:
-             self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
-         self.SetSize(size)
-+
-+        self.groupSet = Signal("IClassMapFrame.groupSet")
-+        self.categoryChanged = Signal('IClassMapFrame.categoryChanged')
-+
-         #
-         # Add toolbars
-         #
-@@ -177,7 +183,7 @@
-         self.dialogs['category']   = None
-         
-         # PyPlot init
--        self.plotPanel = PlotPanel(self, stats_data = self.stats_data)
-+        self.plotPanel = PlotPanel(self, giface = self._giface, stats_data = self.stats_data)
-                                    
-         self._addPanes()
-         self._mgr.Update()
-@@ -237,7 +243,7 @@
-             return False
-         
-         return vectorName
--        
-+    
-     def RemoveTempVector(self):
-         """!Removes temporary vector map with training areas"""
-         ret = RunCommand(prog = 'g.remove',
-@@ -477,21 +483,47 @@
-         
-         self.Render(self.GetFirstWindow())
-         
--    def OnAddBands(self, event):
-+    def AddBands(self):
-         """!Add imagery group"""
-         dlg = IClassGroupDialog(self, group = self.group)
--        if dlg.ShowModal() == wx.ID_OK:
--            self.SetGroup(dlg.GetGroup())
-+        
-+        while True:
-+            if dlg.ShowModal() == wx.ID_OK:
-+                if self.SetGroup(dlg.GetGroup()):
-+                    break
-+            else: 
-+                break
-+        
-         dlg.Destroy()
-         
-     def SetGroup(self, name):
-         """!Set imagery group"""
-         group = grass.find_file(name = name, element = 'group')
-         if group['name']:
-+            if not self.GroupData(group['name']):
-+                GError(_("No data found in group <%s>.\n" \
-+                         "Please create subgroup with same name as group and add the data there.") \
-+                           % name, parent = self)
-+                return False
-             self.group = group['name']
-+            self.groupSet.emit(group = group['name'])
-         else:
-             GError(_("Group <%s> not found") % name, parent = self)
--    
-+            return False
-+
-+        return True
-+
-+    def GroupData(self, group):
-+        res = RunCommand('i.group',
-+                         flags = 'g',
-+                         group = group, subgroup = group,
-+                         read = True).strip()
-+        bands = None
-+        if res.split('\n')[0]:
-+            bands = res.split('\n')
-+            
-+        return bands
-+
-     def OnImportAreas(self, event):
-         """!Import training areas"""
-         # check if we have any changes
-@@ -768,17 +800,20 @@
-         
-         Updates number of stddev, histograms, layer in preview display. 
-         """
--        stat = self.stats_data.GetStatistics(currentCat)
--        nstd = stat.nstd
--        self.toolbars['iClass'].UpdateStddev(nstd)
--        
--        self.plotPanel.UpdateCategory(currentCat)
--        self.plotPanel.OnPlotTypeSelected(None)
-+        if currentCat:
-+          stat = self.stats_data.GetStatistics(currentCat)
-+          nstd = stat.nstd
-+          self.toolbars['iClass'].UpdateStddev(nstd)
-+          
-+          self.plotPanel.UpdateCategory(currentCat)
-+          self.plotPanel.OnPlotTypeSelected(None)
-                                    
--        name = stat.rasterName
--        name = self.previewMapManager.GetAlias(name)
--        if name:
--            self.previewMapManager.SelectLayer(name)
-+          name = stat.rasterName
-+          name = self.previewMapManager.GetAlias(name)
-+          if name:
-+              self.previewMapManager.SelectLayer(name)
-+
-+        self.categoryChanged.emit(cat = currentCat)
-         
-     def DeleteAreas(self, cats):
-         """!Removes all training areas of given categories
-@@ -1105,27 +1140,6 @@
-         self.GetFirstWindow().SetModePointer()
-         self.GetSecondWindow().SetModePointer()
- 
--    def OnScatterplot(self, event):
--        """!Init interactive scatterplot tools
--        """
--        if self.dialogs['scatt_plot']:
--            self.dialogs['scatt_plot'].Raise()
--            return
--
--        try:
--          from scatt_plot.dialogs import ScattPlotMainDialog
--        except:
--          GError(parent  = self, message = _("The Scatter Plot Tool is not installed."))
--          return
--
--        self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface, iclass_mapwin = self.GetFirstWindow())
--
--        scatt_mgr = self.dialogs['scatt_plot'].GetScattMgr()
--        scatt_mgr.DigitDataChanged(self.toolbars['vdigit'].mapLayer.GetName(), self.GetFirstWindow().GetDigit())
--
--        self.dialogs['scatt_plot'].CenterOnScreen()
--        self.dialogs['scatt_plot'].Show()
--
- class MapManager:
-     """! Class for managing map renderer.
-     
-Index: gui/wxpython/iclass/plots.py
-===================================================================
---- gui/wxpython/iclass/plots.py	(revision 57601)
-+++ gui/wxpython/iclass/plots.py	(working copy)
-@@ -19,6 +19,7 @@
- import wx.lib.plot as plot
- import wx.lib.scrolledpanel as scrolled
- from core.utils import _
-+from core.gcmd import GError
- 
- class PlotPanel(scrolled.ScrolledPanel):
-     """!Panel for drawing multiple plots.
-@@ -28,7 +29,7 @@
-     for each band and for one category. Coincidence plots show min max range
-     of classes for each band.
-     """
--    def __init__(self, parent, stats_data):
-+    def __init__(self, parent, giface, stats_data):
-         scrolled.ScrolledPanel.__init__(self, parent)
-         
-         self.SetupScrolling(scroll_x = False, scroll_y = True)
-@@ -38,26 +39,71 @@
-         self.stats_data = stats_data
-         self.currentCat = None
-         
-+        self._giface = giface
-+
-         self.mainSizer = wx.BoxSizer(wx.VERTICAL)
--        
-+
-         self._createControlPanel()
--        
-+        self._createPlotPanel()
-+        self._createScatterPlotPanel()
-+
-         self.SetSizer(self.mainSizer)
-         self.mainSizer.Fit(self)
-         self.Layout()
--        
-+
-+    def _createPlotPanel(self):
-+
-+        self.canvasPanel = wx.Panel(parent=self)
-+        self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
-+        self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
-+        self.canvasPanel.SetSizer(self.canvasSizer)
-+
-     def _createControlPanel(self):
-         self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
-                                      choices = [_("Histograms"),
--                                                _("Coincident plots")])
-+                                                _("Coincident plots"),
-+                                                _("Scatter plots")])
-         self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
-         self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
--        
-+    
-+    def _createScatterPlotPanel(self):
-+        """!Init interactive scatterplot tools
-+        """
-+        try:
-+            from scatt_plot.frame import IClassScatterPlotsPanel
-+            self.scatt_plot_panel = IClassScatterPlotsPanel(parent=self, 
-+                                                            giface=self._giface, 
-+                                                            iclass_mapwin = self.parent.GetFirstWindow())
-+            self.mainSizer.Add(self.scatt_plot_panel, proportion = 1, flag = wx.EXPAND, border = 0)
-+            self.scatt_plot_panel.Hide()
-+        except ImportError as e:#TODO
-+            self.scatt_error = _("Scatter plot functionality is disabled. Reason:\n" \
-+                                 "Unable to import packages needed for scatter plot.\n%s" % e)
-+            GError(self.scatt_error)
-+            self.scatt_plot_panel = None
-+
-     def OnPlotTypeSelected(self, event):
-         """!Plot type selected"""
-+
-+        if self.plotSwitch.GetSelection() in [0, 1]:
-+            self.SetupScrolling(scroll_x = False, scroll_y = True)
-+            if self.scatt_plot_panel:
-+                self.scatt_plot_panel.Hide()
-+            self.canvasPanel.Show()
-+            self.Layout()
-+
-+        elif self.plotSwitch.GetSelection() == 2:
-+            self.SetupScrolling(scroll_x = False, scroll_y = False)
-+            if self.scatt_plot_panel:
-+                self.scatt_plot_panel.Show()
-+            else:
-+                GError(self.scatt_error)
-+            self.canvasPanel.Hide()
-+            self.Layout()
-+
-         if self.currentCat is None:
-             return
--        
-+
-         if self.plotSwitch.GetSelection() == 0:
-             stat = self.stats_data.GetStatistics(self.currentCat)
-             if not stat.IsReady():
-@@ -66,7 +112,10 @@
-             self.DrawHistograms(stat)
-         else:
-             self.DrawCoincidencePlots()
--            
-+
-+        self.Layout()
-+
-+
-     def StddevChanged(self):
-         """!Standard deviation multiplier changed, redraw histograms"""
-         if self.plotSwitch.GetSelection() == 0:
-@@ -89,7 +138,7 @@
-             panel.Destroy()
-             
-         self.canvasList = []
--            
-+
-     def ClearPlots(self):
-         """!Clears plot canvases"""
-         for bandIdx in range(len(self.bandList)):
-@@ -104,15 +153,15 @@
-     def CreatePlotCanvases(self):
-         """!Create plot canvases according to the number of bands"""
-         for band in self.bandList:
--            canvas = plot.PlotCanvas(self)
-+            canvas = plot.PlotCanvas(self.canvasPanel)
-             canvas.SetMinSize((-1, 140))
-             canvas.SetFontSizeTitle(10)
-             canvas.SetFontSizeAxis(8)
-             self.canvasList.append(canvas)
-             
--            self.mainSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
--
--        self.SetVirtualSize(self.GetBestVirtualSize()) 
-+            self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
-+        
-+        self.SetVirtualSize(self.GetBestVirtualSize())
-         self.Layout()
-         
-     def UpdatePlots(self, group, currentCat, stats_data):
-@@ -138,7 +187,7 @@
-         
-     def UpdateCategory(self, cat):
-         self.currentCat = cat
--        
-+    
-     def DrawCoincidencePlots(self):
-         """!Draw coincidence plots"""
-         for bandIdx in range(len(self.bandList)):
-Index: gui/wxpython/iclass/dialogs.py
-===================================================================
---- gui/wxpython/iclass/dialogs.py	(revision 57601)
-+++ gui/wxpython/iclass/dialogs.py	(working copy)
-@@ -333,13 +333,19 @@
-         toolbar.SetCategories(catNames = catNames, catIdx = cats)
-         if name in catNames:
-             toolbar.choice.SetStringSelection(name)
-+            cat = toolbar.GetSelectedCategoryIdx()
-         elif catNames:
-             toolbar.choice.SetSelection(0)
--            
-+            cat = toolbar.GetSelectedCategoryIdx()
-+        else:
-+            cat = None
-+
-         if toolbar.choice.IsEmpty():
-             toolbar.EnableControls(False)
-         else:
-             toolbar.EnableControls(True)
-+
-+        self.mapWindow.CategoryChanged(cat)
-         # don't forget to update maps, histo, ...
-         
-     def GetSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
-Index: gui/wxpython/iclass/toolbars.py
-===================================================================
---- gui/wxpython/iclass/toolbars.py	(revision 57601)
-+++ gui/wxpython/iclass/toolbars.py	(working copy)
-@@ -46,9 +46,7 @@
-         'importAreas' : MetaIcon(img = 'layer-import',
-                             label = _('Import training areas from vector map')),
-         'addRgb' : MetaIcon(img = 'layer-rgb-add',
--                            label = _('Add RGB map layer')),
--        'scatt_plot'    : MetaIcon(img = 'layer-raster-analyze',
--                                   label = _('Open Scatter Plot Tool (EXPERIMENTAL GSoC 2013)')),
-+                            label = _('Add RGB map layer'))
-         }
-         
- class IClassMapToolbar(BaseToolbar):
-@@ -117,10 +115,7 @@
-                                      ("zoomBack", icons["zoomBack"],
-                                       self.parent.OnZoomBack),
-                                      ("zoomToMap", icons["zoomExtent"],
--                                      self.parent.OnZoomToMap),
--                                     (None, ),
--                                     ("scatt_plot", iClassIcons["scatt_plot"],
--                                      self.parent.OnScatterplot)
-+                                      self.parent.OnZoomToMap)
-                                     ))
- class IClassToolbar(BaseToolbar):
-     """!IClass toolbar
-@@ -156,7 +151,7 @@
-         """!Toolbar data"""
-         icons = iClassIcons
-         return self._getToolbarData((("selectGroup", icons['selectGroup'],
--                                      self.parent.OnAddBands),
-+                                      lambda event : self.parent.AddBands()),
-                                       (None, ),
-                                       ("classManager", icons['classManager'],
-                                       self.parent.OnCategoryManager),
-Index: lib/imagery/scatt_sccats.c
-===================================================================
---- lib/imagery/scatt_sccats.c	(revision 0)
-+++ lib/imagery/scatt_sccats.c	(working copy)
-@@ -0,0 +1,405 @@
-+/*!
-+   \file lib/imagery/scatt_cat_rast.c
-+
-+   \brief Imagery library - functions for manipulation with scatter plot structs.
-+
-+   Copyright (C) 2013 by the GRASS Development Team
-+
-+   This program is free software under the GNU General Public License
-+   (>=v2).  Read the file COPYING that comes with GRASS for details.
-+
-+   \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
-+ */
-+
-+#include <grass/raster.h>
-+#include <grass/imagery.h>
-+#include <grass/gis.h>
-+
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <math.h>
-+#include <string.h>
-+
-+/*!
-+   \brief Compute band ids from scatter plot id.
-+
-+    Scatter plot id describes which bands defines the scatter plot.
-+
-+    Let say we have 3 bands, their ids are 0, 1 and 2.
-+    Scatter plot with id 0 consists of band 1 (b_1_id) 0 and  band 2 (b_2_id) 1.
-+    All scatter plots:
-+    scatt_id b_1_id b_2_id
-+    0        0      1
-+    1        0      2
-+    2        1      2
-+
-+   \param scatt_id scatter plot id
-+   \param n_bands number of bands
-+   \param [out] b_1_id id of band1
-+   \param[out] b_2_id id of band2
-+
-+   \return 0
-+ */
-+int I_id_scatt_to_bands(const int scatt_id, const int n_bands, int * b_1_id, int * b_2_id)
-+{   
-+    int n_b1 = n_bands - 1;
-+
-+    * b_1_id = (int) ((2 * n_b1 + 1 - sqrt((double)((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2);
-+
-+    * b_2_id = scatt_id - ((* b_1_id) * (2 * n_b1 + 1) - (* b_1_id) * (* b_1_id)) / 2 + (* b_1_id) + 1;
-+
-+    return 0;
-+}
-+
-+
-+/*!
-+   \brief Compute scatter plot id from band ids.
-+
-+    See also I_id_scatt_to_bands().
-+
-+   \param n_bands number of bands
-+   \param b_1_id id of band1
-+   \param b_1_id id of band2
-+   \param [out] scatt_id scatter plot id
-+
-+   \return 0
-+ */
-+int I_bands_to_id_scatt(const int b_1_id, const int b_2_id, const int n_bands, int * scatt_id)
-+{   
-+    int n_b1 = n_bands - 1;
-+
-+    * scatt_id = (b_1_id * (2 * n_b1 + 1) - b_1_id * b_1_id) / 2 + b_2_id - b_1_id - 1;
-+
-+    return 0;
-+}
-+
-+/*!
-+   \brief Initialize structure for storing scatter plots data.
-+
-+   \param cats pointer to scCats struct 
-+   \param n_bands number of bands
-+   \param type SC_SCATT_DATA - stores scatter plots 
-+   \param type SC_SCATT_CONDITIONS - stores selected areas in scatter plots
-+ */
-+void I_sc_init_cats(struct scCats * cats, int n_bands, int type)
-+{
-+    int i_cat;
-+
-+    cats->type = type;
-+
-+    cats->n_cats = 100;
-+    cats->n_a_cats = 0;
-+
-+    cats->n_bands = n_bands;
-+    cats->n_scatts = (n_bands - 1) * n_bands / 2;
-+
-+    cats->cats_arr = (struct scScatts **) G_malloc(cats->n_cats * sizeof(struct scScatts *));
-+    memset(cats->cats_arr, 0, cats-> n_cats * sizeof(struct scScatts *));
-+
-+    cats->cats_ids = (int *)  G_malloc(cats->n_cats * sizeof(int));
-+    cats->cats_idxs =(int *)  G_malloc(cats->n_cats * sizeof(int));
-+
-+    for(i_cat = 0; i_cat < cats->n_cats; i_cat++)
-+        cats->cats_idxs[i_cat] = -1;
-+
-+    return;
-+}
-+
-+/*!
-+   \brief Free data of struct scCats, the structure itself remains alocated.
-+
-+   \param cats pointer to existing scCats struct
-+ */
-+void I_sc_free_cats(struct scCats * cats)
-+{
-+    int i_cat;
-+
-+    for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
-+    {        
-+        if(cats->cats_arr[i_cat])
-+        {   
-+            G_free(cats->cats_arr[i_cat]->scatt_idxs);
-+            G_free(cats->cats_arr[i_cat]->scatts_bands);
-+            G_free(cats->cats_arr[i_cat]->scatts_arr);
-+            G_free(cats->cats_arr[i_cat]);
-+        }
-+    }
-+
-+    G_free(cats->cats_ids);
-+    G_free(cats->cats_idxs);
-+    G_free(cats->cats_arr);
-+
-+    cats->n_cats = 0;
-+    cats->n_a_cats = 0;
-+    cats->n_bands = 0;
-+    cats->n_scatts = 0;
-+    cats->type = -1;
-+
-+    return;
-+}
-+
-+#if 0
-+void I_sc_get_active_categories(int * a_cats_ids, int * n_a_cats, struct scCats * cats)
-+{
-+    a_cats_ids = cats->cats_ids;
-+    * n_a_cats = cats->n_a_cats;
-+}
-+#endif
-+
-+/*!
-+   \brief Add category.
-+    
-+    Category represents group of scatter plots.
-+
-+   \param cats pointer to scCats struct
-+
-+   \return assigned category id (starts with 0)
-+   \return -1 if maximum nuber of categories was reached
-+ */
-+int I_sc_add_cat(struct scCats * cats)
-+{
-+    int i_scatt, i_cat_id, cat_id;
-+    int n_a_cats = cats->n_a_cats;
-+
-+    if(cats->n_a_cats >= cats->n_cats)
-+        return -1;
-+
-+    for(i_cat_id = 0; i_cat_id < cats->n_cats; i_cat_id++)
-+        if(cats->cats_idxs[i_cat_id] < 0) {
-+            cat_id = i_cat_id;
-+            break;
-+        }
-+
-+    cats->cats_ids[n_a_cats] = cat_id;
-+    cats->cats_idxs[cat_id] = n_a_cats;
-+    
-+    cats->cats_arr[n_a_cats] = (struct scScatts *) G_malloc(sizeof(struct scScatts));
-+
-+    cats->cats_arr[n_a_cats]->scatts_arr = (struct scdScattData **) G_malloc(cats->n_scatts * sizeof(struct scdScattData *));
-+    memset((cats->cats_arr[n_a_cats]->scatts_arr), 0, cats->n_scatts * sizeof(struct scdScattData *));
-+    
-+    cats->cats_arr[n_a_cats]->n_a_scatts = 0;
-+
-+    cats->cats_arr[n_a_cats]->scatts_bands = (int *) G_malloc(cats->n_scatts * 2 * sizeof(int));
-+     
-+    cats->cats_arr[n_a_cats]->scatt_idxs = (int *) G_malloc(cats->n_scatts * sizeof(int));
-+    for(i_scatt = 0; i_scatt < cats->n_scatts; i_scatt++)
-+        cats->cats_arr[n_a_cats]->scatt_idxs[i_scatt] = -1;
-+    
-+    ++cats->n_a_cats;
-+
-+    return cat_id;
-+}
-+
-+#if 0
-+int I_sc_delete_cat(struct scCats * cats, int cat_id)
-+{
-+    int cat_idx, i_cat;
-+
-+    if(cat_id < 0 || cat_id >= cats->n_cats)
-+        return -1;
-+
-+    cat_idx = cats->cats_idxs[cat_id];
-+    if(cat_idx < 0)
-+        return -1;
-+
-+    G_free(cats->cats_arr[cat_idx]->scatt_idxs);
-+    G_free(cats->cats_arr[cat_idx]->scatts_bands);
-+    G_free(cats->cats_arr[cat_idx]->scatts_arr);
-+    G_free(cats->cats_arr[cat_idx]);
-+
-+    for(i_cat = cat_idx; i_cat < cats->n_a_cats - 1; i_cat++)
-+    {
-+        cats->cats_arr[i_cat] = cats->cats_arr[i_cat + 1];
-+        cats->cats_ids[i_cat] = cats->cats_ids[i_cat + 1];
-+    }
-+    cats->cats_idxs[cat_id] = -1; 
-+
-+    --cats->n_a_cats;
-+    
-+    return 0;
-+}
-+#endif
-+
-+/*!
-+   \brief Insert scatter plot data .
-+    Inserted scatt_data struct must have same type as cats struct (SC_SCATT_DATA or SC_SCATT_CONDITIONS).
-+
-+   \param cats pointer to scCats struct
-+   \param cat_id id number of category.
-+   \param scatt_id id number of scatter plot.
-+
-+   \return  0 on success
-+   \return -1 on failure
-+ */
-+int I_sc_insert_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
-+{
-+    int band_1, band_2, cat_idx, n_a_scatts;
-+    struct scScatts * scatts;
-+
-+    if(cat_id < 0 || cat_id >= cats->n_cats)
-+        return -1;
-+
-+    cat_idx = cats->cats_idxs[cat_id];
-+    if(cat_idx < 0)
-+        return -1;
-+
-+    if(scatt_id < 0 && scatt_id >= cats->n_scatts)
-+        return -1;
-+
-+    scatts = cats->cats_arr[cat_idx];
-+    if(scatts->scatt_idxs[scatt_id] >= 0)
-+        return -1;
-+
-+    if(!scatt_data->b_conds_arr && cats->type == SC_SCATT_CONDITIONS)
-+        return -1;
-+
-+    if(!scatt_data->scatt_vals_arr && cats->type == SC_SCATT_DATA)
-+        return -1;
-+
-+    n_a_scatts = scatts->n_a_scatts;
-+
-+    scatts->scatt_idxs[scatt_id] = n_a_scatts;
-+
-+    I_id_scatt_to_bands(scatt_id, cats->n_bands, &band_1, &band_2);
-+
-+    scatts->scatts_bands[n_a_scatts * 2] = band_1;
-+    scatts->scatts_bands[n_a_scatts * 2 + 1] = band_2;
-+
-+    scatts->scatts_arr[n_a_scatts] = scatt_data;
-+    ++scatts->n_a_scatts;
-+
-+    return 0;
-+}
-+
-+#if 0
-+int I_sc_remove_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
-+{
-+    int cat_idx, scatt_idx, n_init_scatts, i_scatt;
-+    struct scScatts * scatts;
-+
-+    if(cat_id < 0 && cat_id >= cats->n_cats)
-+        return -1;
-+
-+    cat_idx = cats->cats_idxs[cat_id];
-+    if(cat_idx < 0)
-+        return -1;
-+
-+    if(scatt_id < 0 || scatt_id >= cats->n_scatts)
-+        return -1;
-+
-+    scatts = cats->cats_arr[cat_idx];
-+    if(scatts->scatt_idxs[scatt_id] < 0)
-+        return -1;
-+
-+    scatt_data = scatts->scatts_arr[scatt_idx];
-+
-+    for(i_scatt = scatt_idx; i_scatt < scatts->n_a_scatts - 1; i_scatt++)
-+    {
-+        scatts->scatts_arr[i_scatt] = scatts->scatts_arr[i_scatt + 1];
-+        scatts->scatts_bands[i_scatt * 2] = scatts->scatts_bands[(i_scatt + 1)* 2];
-+        scatts->scatts_bands[i_scatt * 2 + 1] = scatts->scatts_bands[(i_scatt + 1) * 2 + 1];
-+    }
-+    scatts->scatts_arr[scatts->n_a_scatts] = NULL;
-+
-+    scatts->scatt_idxs[scatt_id] = -1;
-+
-+    scatt_data = scatts->scatts_arr[scatt_id];
-+    scatts->n_a_scatts--;
-+
-+    return 0;
-+}
-+
-+int I_sc_set_value(struct scCats * cats, int cat_id, int scatt_id, int value_idx, int value)
-+{
-+    int n_a_scatts = cats->cats_arr[cat_id]->n_a_scatts;
-+    int cat_idx, scatt_idx, ret;
-+
-+    cat_idx = cats->cats_idxs[cat_id];
-+    if(cat_idx < 0)
-+        return -1;
-+    
-+    if(cats->cats_arr[cat_idx]->scatt_idxs[scatt_id] < 0)
-+        return -1;
-+
-+    cat_idx = cats->cats_idxs[cat_id];
-+    scatt_idx = cats->cats_arr[cat_idx]->scatt_idxs[scatt_id];
-+
-+    I_scd_set_value(cats->cats_arr[cat_idx]->scatts_arr[scatt_idx], value_idx, value);
-+
-+    return 0;
-+}
-+#endif
-+
-+/*!
-+   \brief Insert scatter plot data.
-+    
-+   \param scatt_data pointer to existing struct scdScattData
-+   \param type SC_SCATT_DATA for scatter plots or SC_SCATT_CONDITIONS for selected areas in scatter plot
-+   \param n_vals number of data values
-+   \param data array of values (unsigned char for SC_SCATT_CONDITIONS, unsigned int for SC_SCATT_DATA)
-+ */
-+void I_scd_init_scatt_data(struct scdScattData * scatt_data, int type, int n_vals, void * data)
-+{
-+    scatt_data->n_vals = n_vals;
-+
-+    if(type == SC_SCATT_DATA)
-+    {   
-+        if(data)
-+            scatt_data->scatt_vals_arr = (unsigned int *) data;
-+        else {
-+            scatt_data->scatt_vals_arr = (unsigned int *) G_malloc(n_vals * sizeof(unsigned int));
-+            memset(scatt_data->scatt_vals_arr, 0, n_vals * sizeof(unsigned int)); 
-+        }
-+        scatt_data->b_conds_arr = NULL;
-+    }
-+    else if(type == SC_SCATT_CONDITIONS)
-+    {
-+        if(data)
-+            scatt_data->b_conds_arr = (unsigned char *) data;
-+        else {
-+            scatt_data->b_conds_arr = (unsigned char *) G_malloc(n_vals * sizeof(unsigned char));
-+            memset(scatt_data->b_conds_arr, 0, n_vals * sizeof(unsigned char));
-+        }
-+        scatt_data->scatt_vals_arr = NULL;
-+    }
-+
-+    return;
-+}
-+
-+
-+#if 0
-+void I_scd_get_range_min_max(struct scdScattData * scatt_data, CELL * band_1_min, CELL * band_1_max, CELL * band_2_min, CELL * band_2_max)
-+{
-+
-+    Rast_get_range_min_max(&(scatt_data->band_1_range), band_1_min, band_2_min);
-+    Rast_get_range_min_max(&(scatt_data->band_2_range), band_2_min, band_2_max);
-+
-+    return;
-+}
-+s
-+void * I_scd_get_data_ptr(struct scdScattData * scatt_data)
-+{
-+    if(!scatt_data->b_conds_arr)
-+        return scatt_data->b_conds_arr;
-+    else if(!scatt_data->scatt_vals_arr)
-+        return scatt_data->scatt_vals_arr;
-+
-+    return NULL;
-+}
-+
-+int I_scd_set_value(struct scdScattData * scatt_data, unsigned int val_idx, unsigned int val)
-+{
-+    if(val_idx < 0 && val_idx >  scatt_data->n_vals)
-+        return -1;
-+
-+    if(scatt_data->b_conds_arr)
-+        scatt_data->b_conds_arr[val_idx] = val;
-+    else if(scatt_data->scatt_vals_arr)
-+        scatt_data->scatt_vals_arr[val_idx] = val;
-+    else
-+        return -1;
-+
-+    return 0;
-+}
-+#endif
-Index: lib/imagery/scatt.c
-===================================================================
---- lib/imagery/scatt.c	(revision 0)
-+++ lib/imagery/scatt.c	(working copy)
-@@ -0,0 +1,746 @@
-+/*!
-+   \file lib/imagery/scatt.c
-+
-+   \brief Imagery library - functions for wx Scatter Plot Tool.
-+
-+   Low level functions used by wx Scatter Plot Tool.
-+
-+   Copyright (C) 2013 by the GRASS Development Team
-+
-+   This program is free software under the GNU General Public License
-+   (>=v2).  Read the file COPYING that comes with GRASS for details.
-+
-+   \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
-+ */
-+
-+#include <grass/raster.h>
-+#include <grass/imagery.h>
-+#include <grass/gis.h>
-+#include <grass/glocale.h>
-+
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <math.h>
-+#include <string.h>
-+
-+
-+struct rast_row
-+{
-+    CELL * row;
-+    char * null_row;
-+    struct Range rast_range; /*Range of whole raster.*/
-+};
-+
-+/*!
-+   \brief Create pgm header.
-+
-+   Scatter plot internally generates pgm files. These pgms have header in format created by this function.
-+    
-+   \param region region to be pgm header generated for 
-+   \param [out] header header of pgm file
-+ */
-+static int get_cat_rast_header(struct Cell_head * region, char * header){
-+    return sprintf(header, "P5\n%d\n%d\n1\n", region->cols, region->rows);
-+}
-+
-+/*!
-+   \brief Create category raster conditions file.
-+    
-+   \param cat_rast_region region to be file generated for
-+   \param cat_rast path of generated category raster file
-+ */
-+int I_create_cat_rast(struct Cell_head * cat_rast_region,  const char * cat_rast)
-+{
-+    FILE * f_cat_rast;
-+    char cat_rast_header[1024];//TODO magic number 
-+    int i_row, i_col;
-+    int head_nchars;
-+
-+    unsigned char * row_data;
-+
-+    f_cat_rast = fopen(cat_rast, "wb");
-+    if(!f_cat_rast) {
-+        G_warning("Unable to create category raster condition file <%s>.", cat_rast);
-+        return -1;
-+    }
-+
-+    head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
-+
-+    fwrite(cat_rast_header, sizeof(char), head_nchars/sizeof(char), f_cat_rast);
-+    if (ferror(f_cat_rast)){
-+        fclose(f_cat_rast);
-+        G_warning(_("Unable to write header into category raster condition file <%s>."), cat_rast);
-+        return -1;
-+    }
-+
-+    row_data = (unsigned char *) G_malloc(cat_rast_region->cols * sizeof(unsigned char));
-+    for(i_col = 0; i_col < cat_rast_region->cols; i_col++)
-+        row_data[i_col] = 0 & 255;
-+
-+    for(i_row = 0; i_row < cat_rast_region->rows; i_row++) {
-+        fwrite(row_data, sizeof(unsigned char), (cat_rast_region->cols)/sizeof(unsigned char), f_cat_rast);
-+        if (ferror(f_cat_rast))
-+        {
-+            fclose(f_cat_rast);
-+            G_warning(_("Unable to write into category raster condition file <%s>."), cat_rast);
-+            return -1;
-+        }
-+    }
-+
-+    fclose(f_cat_rast);
-+    return 0;
-+}
-+
-+static int print_reg(struct Cell_head * intersec, const char * pref, int dbg_level)
-+{
-+    G_debug(dbg_level, "%s:\n n:%f\ns:%f\ne:%f\nw:%f\nns_res:%f\new_res:%f", pref, intersec->north, intersec->south, 
-+               intersec->east, intersec->west, intersec->ns_res, intersec->ew_res);
-+}
-+
-+/*!
-+   \brief Find intersection region of two regions.
-+
-+   \param A pointer to intersected region
-+   \param B pointer to intersected region
-+   \param [out] intersec pointer to intersection region of regions A B (relevant params of the region are: south, north, east, west)
-+
-+   \return  0 if interection exists
-+   \return -1 if regions does not intersect
-+ */
-+static int regions_intersecion(struct Cell_head * A, struct Cell_head * B, struct Cell_head * intersec)
-+{
-+
-+    if(B->north < A->south) return -1;
-+    else if(B->north > A->north) intersec->north = A->north;
-+    else intersec->north = B->north;
-+
-+    if(B->south > A->north) return -1;
-+    else if(B->south < A->south) intersec->south = A->south;
-+    else intersec->south = B->south;
-+
-+    if(B->east < A->west) return -1;
-+    else if(B->east > A->east) intersec->east = A->east;
-+    else intersec->east = B->east;
-+
-+    if(B->west > A->east) return -1;
-+    else if(B->west < A->west) intersec->west = A->west;
-+    else intersec->west = B->west;
-+
-+    if(intersec->north == intersec->south) return -1;
-+
-+    if(intersec->east == intersec->west) return -1;
-+
-+    return 0;
-+
-+}
-+
-+/*!
-+   \brief Get rows and cols numbers, which defines intersection of the regions.
-+  
-+   \param A pointer to intersected region
-+   \param B pointer to intersected region (A and B must have same resolution)
-+   \param [out] A_bounds rows and cols numbers of A stored in south, north, east, west, which defines intersection of A and B
-+   \param [out] B_bounds rows and cols numbers of B stored in south, north, east, west, which defines intersection of A and B
-+
-+   \return  0 if interection exists
-+   \return -1 if regions do not intersect
-+   \return -2 resolution of regions is not same 
-+*/
-+static int get_rows_and_cols_bounds(struct Cell_head * A,  struct Cell_head * B, struct Cell_head * A_bounds,  struct Cell_head * B_bounds)
-+{
-+    float ns_res, ew_res;
-+
-+    struct Cell_head intersec;
-+
-+    /* TODO is it right check? */
-+    if(abs(A->ns_res - B->ns_res) > GRASS_EPSILON) {
-+        G_debug(0, "'get_rows_and_cols_bounds' ns_res does not fit, A->ns_res: %f B->ns_res: %f", A->ns_res, B->ns_res);
-+        return -2;
-+    }
-+
-+    if(abs(A->ew_res - B->ew_res) > GRASS_EPSILON) {
-+        G_debug(0, "'get_rows_and_cols_bounds' ew_res does not fit, A->ew_res: %f B->ew_res: %f", A->ew_res, B->ew_res);
-+        return -2;
-+    }
-+
-+    ns_res = A->ns_res;
-+    ew_res = A->ew_res;
-+
-+    if(regions_intersecion(A, B, &intersec) == -1)
-+        return -1;
-+
-+    A_bounds->north = ceil((A->north - intersec.north - ns_res * 0.5) / ns_res);
-+    A_bounds->south = ceil((A->north - intersec.south - ns_res * 0.5) / ns_res);
-+
-+    A_bounds->east = ceil((intersec.east - A->west - ew_res * 0.5) / ew_res);
-+    A_bounds->west = ceil((intersec.west - A->west - ew_res * 0.5) / ew_res);
-+
-+    B_bounds->north = ceil((B->north - intersec.north - ns_res * 0.5) / ns_res);
-+    B_bounds->south = ceil((B->north - intersec.south - ns_res * 0.5) / ns_res);
-+
-+    B_bounds->east = ceil((intersec.east - B->west - ew_res * 0.5) / ew_res);
-+    B_bounds->west = ceil((intersec.west - B->west - ew_res * 0.5) / ew_res);
-+
-+    return 0;
-+}
-+
-+/*!
-+   \brief Insert raster map patch into pgm file.
-+  
-+   \param patch_rast name of raster map
-+   \param cat_rast_region region of category raster file
-+   \param cat_rast path to category raster file
-+
-+   \return  0 on success
-+   \return -1 on failure
-+*/
-+int I_insert_patch_to_cat_rast(const char * patch_rast, struct Cell_head * cat_rast_region,  const char * cat_rast)
-+{
-+
-+    FILE * f_cat_rast;
-+    struct Cell_head patch_region, patch_bounds, cat_rast_bounds;
-+    char cat_rast_header[1024];//TODO magic number 
-+    int i_row, i_col, ncols, nrows, cat_rast_col, patch_col, val;
-+    int head_nchars, ret;
-+    int fd_patch_rast, init_shift, step_shift;
-+    unsigned char * patch_data;
-+
-+    char * null_chunk_row;
-+
-+    const char *mapset;
-+
-+    struct Cell_head patch_lines, cat_rast_lines;
-+
-+    unsigned char * row_data;
-+
-+    f_cat_rast = fopen(cat_rast, "rb+");
-+    if(!f_cat_rast) {
-+        G_warning(_("Unable to open category raster condtions file <%s>."), cat_rast);
-+        return -1;
-+    }
-+
-+    head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
-+    if ((mapset = G_find_raster(patch_rast,"")) == NULL) {
-+        fclose(f_cat_rast);
-+        G_warning(_("Unable to find patch raster <%s>."), patch_rast);
-+        return -1;
-+    }
-+
-+    Rast_get_cellhd(patch_rast, mapset, &patch_region);
-+    Rast_set_window(&patch_region);
-+            
-+    if ((fd_patch_rast = Rast_open_old(patch_rast, mapset)) < 0) {
-+        fclose(f_cat_rast);
-+        return -1;
-+    }
-+
-+    ret = get_rows_and_cols_bounds(cat_rast_region, &patch_region, &cat_rast_bounds, &patch_bounds);
-+    if(ret == -2) { 
-+        G_warning(_("Resolutions of patch <%s> and patched file <%s> are not same."), patch_rast, cat_rast);
-+
-+        Rast_close(fd_patch_rast);
-+        fclose(f_cat_rast);
-+
-+        return -1;
-+    }
-+    else if (ret == -1){
-+
-+        Rast_close(fd_patch_rast);
-+        fclose(f_cat_rast);
-+
-+        return 0;
-+    }
-+
-+    ncols = cat_rast_bounds.east - cat_rast_bounds.west;
-+    nrows = cat_rast_bounds.south - cat_rast_bounds.north;
-+
-+    patch_data = (unsigned char *) G_malloc(ncols * sizeof(unsigned char));
-+
-+    init_shift = head_nchars + cat_rast_region->cols * cat_rast_bounds.north + cat_rast_bounds.west;
-+
-+    if(fseek(f_cat_rast, init_shift, SEEK_SET) != 0) {
-+        G_warning(_("Corrupted  category raster conditions file <%s> (fseek failed)"), cat_rast);
-+
-+        Rast_close(fd_patch_rast);
-+        G_free(null_chunk_row);
-+        fclose(f_cat_rast);
-+
-+        return -1;
-+    }
-+
-+    step_shift = cat_rast_region->cols - ncols;
-+
-+    null_chunk_row =  Rast_allocate_null_buf();
-+    
-+    for(i_row = 0; i_row < nrows; i_row++) {
-+        Rast_get_null_value_row (fd_patch_rast, null_chunk_row, i_row + patch_bounds.north);
-+
-+        for(i_col = 0; i_col < ncols; i_col++) {
-+            patch_col = patch_bounds.west + i_col;
-+
-+            if(null_chunk_row[patch_col] != 1) 
-+                patch_data[i_col] = 1 & 255;
-+            else {
-+                patch_data[i_col] = 0 & 255;
-+            }
-+        }
-+
-+        fwrite(patch_data, sizeof(unsigned char), (ncols)/sizeof(unsigned char), f_cat_rast);
-+        if (ferror(f_cat_rast))
-+        {
-+            G_warning(_("Unable to write into category raster conditions file <%s>"), cat_rast);
-+            
-+            Rast_close(fd_patch_rast);
-+            G_free(null_chunk_row);
-+            fclose(f_cat_rast);
-+
-+            return -1;
-+        }
-+        if(fseek(f_cat_rast, step_shift, SEEK_CUR) != 0) {
-+            G_warning(_("Corrupted  category raster conditions file <%s> (fseek failed)"), cat_rast);
-+            
-+            Rast_close(fd_patch_rast);
-+            G_free(null_chunk_row);
-+            fclose(f_cat_rast);
-+            
-+            return -1;
-+        }
-+    }
-+
-+    Rast_close(fd_patch_rast);
-+    G_free(null_chunk_row);
-+    fclose(f_cat_rast);
-+    return 0;
-+}
-+
-+/*!
-+   \brief Updates scatter plots data in category by pixels which meets category conditions.
-+  
-+   \param bands_rows data represents data describig one row from raster band
-+   \param belongs_pix array which defines which pixels belongs to category (1 value) and which not (0 value)
-+   \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, which are modified according to values in belongs_pix
-+*/
-+static inline void update_cat_scatt_plts(struct rast_row * bands_rows, unsigned short * belongs_pix, struct scScatts * scatts)
-+{
-+    int band_axis_1, band_axis_2, i_scatt, array_idx, cat_idx, i_chunk_rows_pix, max_arr_idx;
-+
-+    CELL * b_1_row;
-+    CELL * b_2_row;
-+    char * b_1_null_row,* b_2_null_row;
-+    struct rast_row b_1_rast_row, b_2_rast_row;
-+
-+    struct Range b_1_range, b_2_range;
-+    int b_1_range_size;
-+
-+    int row_size = Rast_window_cols();
-+
-+    int * scatts_bands = scatts->scatts_bands;
-+
-+    for(i_scatt = 0; i_scatt < scatts->n_a_scatts; i_scatt++)
-+    {   
-+        b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
-+        b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
-+
-+        b_1_row = b_1_rast_row.row;
-+        b_2_row = b_2_rast_row.row;
-+
-+        b_1_null_row =  b_1_rast_row.null_row;
-+        b_2_null_row =  b_2_rast_row.null_row;
-+
-+        b_1_range = b_1_rast_row.rast_range;
-+        b_2_range = b_2_rast_row.rast_range;
-+        
-+        b_1_range_size = b_1_range.max - b_1_range.min + 1;
-+        max_arr_idx = (b_1_range.max -  b_1_range.min + 1) * (b_2_range.max -  b_2_range.min + 1);
-+
-+        for(i_chunk_rows_pix = 0; i_chunk_rows_pix < row_size; i_chunk_rows_pix++)
-+        {
-+            /* pixel does not belongs to scatter plot or has null value in one of the bands */
-+            if(!belongs_pix[i_chunk_rows_pix] || 
-+                b_1_null_row[i_chunk_rows_pix] == 1 || 
-+                b_2_null_row[i_chunk_rows_pix] == 1)                
-+                continue;
-+
-+            /* index in scatter plot array */
-+            array_idx = b_1_row[i_chunk_rows_pix] - b_1_range.min + (b_2_row[i_chunk_rows_pix] - b_2_range.min) * b_1_range_size;
-+
-+            if(array_idx < 0 || array_idx >= max_arr_idx) {
-+                        G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
-+                continue;
-+            }
-+
-+            /* increment scatter plot value */
-+            ++scatts->scatts_arr[i_scatt]->scatt_vals_arr[array_idx];
-+        }
-+    }
-+}
-+
-+/*!
-+   \brief Computes scatter plots data from chunk_rows.
-+
-+   \param scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
-+   \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are selected areas (condtitions)stored
-+
-+   \param chunk_rows data arrays of chunk_rows from analyzed raster bands (all data in chunk_rows, null_chunk_rows and belongs_pix arrays represents same region)
-+   \param null_chunk_rows null data arrays of chunk_rows from analyzed raster bands
-+   \param row_size size of data in chunk_rows, null_chunk_rows and belongs_pix arrays
-+   \param f_cats_rasts_conds file which stores selected areas (conditions) from mapwindow see I_create_cat_rast() and I_pa
-+   \param fd_cats_rasts array of openedraster maps which represents all selected pixels for category
-+   \param region analysis region
-+
-+   \return  0 on success
-+   \return -1 on failure
-+*/
-+static inline int compute_scatts_from_chunk_row(struct Cell_head *region, struct scCats * scatt_conds, 
-+                                                FILE ** f_cats_rasts_conds, struct rast_row * bands_rows, 
-+                                                struct scCats * scatts, int * fd_cats_rasts)
-+{
-+
-+    int i_rows_pix, i_cat, i_scatt, n_a_scatts, n_pixs;
-+    int cat_id, scatt_plts_cat_idx, array_idx, max_arr_idx;
-+    char * b_1_null_row,* b_2_null_row;
-+    struct rast_row b_1_rast_row, b_2_rast_row;
-+    CELL * cat_rast_row;
-+
-+    struct scScatts * scatts_conds;
-+    struct scScatts * scatts_scatt_plts;
-+    struct scdScattData * conds;
-+
-+    struct Range b_1_range, b_2_range;
-+    int b_1_range_size;
-+
-+    int * scatts_bands;
-+    struct scdScattData ** scatts_arr;
-+
-+    CELL * b_1_row;
-+    CELL * b_2_row;
-+    unsigned char * i_scatt_conds;
-+
-+    int row_size = Rast_window_cols();
-+
-+    unsigned short * belongs_pix = (unsigned short *) G_malloc(row_size * sizeof(unsigned short)); 
-+    unsigned char * rast_pixs = (unsigned char *) G_malloc(row_size * sizeof(unsigned char));
-+    cat_rast_row =  Rast_allocate_c_buf();
-+
-+     
-+    for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
-+    {
-+        scatts_conds = scatt_conds->cats_arr[i_cat];
-+
-+        cat_id = scatt_conds->cats_ids[i_cat];
-+
-+        scatt_plts_cat_idx = scatts->cats_idxs[cat_id];
-+        if(scatt_plts_cat_idx < 0)
-+            continue;
-+        scatts_scatt_plts = scatts->cats_arr[scatt_plts_cat_idx];
-+
-+        G_zero(belongs_pix, row_size * sizeof(unsigned short));
-+
-+        /* if category has no conditions defined, scatter plots without any constraint are computed (default scatter plots) */
-+        if(!scatts_conds->n_a_scatts && !f_cats_rasts_conds[i_cat]) {
-+            for(i_scatt = 0; i_scatt < scatts_scatt_plts->n_a_scatts; i_scatt++)
-+            {       
-+                /* all pixels belongs */
-+                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)                
-+                    belongs_pix[i_rows_pix] = 1;
-+            }
-+        }
-+        /* compute belonging pixels for defined conditions */
-+        else
-+        {
-+            scatts_bands = scatts_conds->scatts_bands;
-+
-+            /* check conditions from category raster condtitions file */
-+            if(f_cats_rasts_conds[i_cat]) {
-+                n_pixs = fread(rast_pixs, sizeof(unsigned char), (row_size)/sizeof(unsigned char), f_cats_rasts_conds[i_cat]);
-+
-+                if (ferror(f_cats_rasts_conds[i_cat]))
-+                {
-+                    G_free(rast_pixs);
-+                    G_free(belongs_pix);
-+                    G_warning(_("Unable to read from category raster condtition file."));
-+                    return -1;
-+                }
-+                if (n_pixs != n_pixs) {
-+                    G_free(rast_pixs);
-+                    G_free(belongs_pix);
-+                    G_warning(_("Invalid size of category raster conditions file."));
-+                    return -1;
-+
-+                }
-+
-+                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+                {
-+                    if(rast_pixs[i_rows_pix] != 0 & 255)
-+                        belongs_pix[i_rows_pix] = 1;
-+                }
-+            }
-+
-+            /* check condtions defined in scatter plots*/
-+            for(i_scatt = 0; i_scatt < scatts_conds->n_a_scatts; i_scatt++)
-+            {   
-+                b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
-+                b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
-+
-+                b_1_row = b_1_rast_row.row;
-+                b_2_row = b_2_rast_row.row;
-+
-+                b_1_null_row =  b_1_rast_row.null_row;
-+                b_2_null_row =  b_2_rast_row.null_row;
-+
-+                b_1_range = b_1_rast_row.rast_range;
-+                b_2_range = b_2_rast_row.rast_range;
-+
-+                b_1_range_size = b_1_range.max - b_1_range.min + 1;
-+                max_arr_idx = (b_1_range.max -  b_1_range.min + 1) * (b_2_range.max -  b_2_range.min + 1);
-+
-+                i_scatt_conds = scatts_conds->scatts_arr[i_scatt]->b_conds_arr;
-+
-+                for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+                {
-+                    /* pixels already belongs to category from category raster conditions file or contains null value in one of the bands */
-+                    if(belongs_pix[i_rows_pix] || 
-+                       b_1_null_row[i_rows_pix] == 1 || 
-+                       b_2_null_row[i_rows_pix] == 1)
-+                        continue;
-+
-+                    array_idx = b_1_row[i_rows_pix] - b_1_range.min + (b_2_row[i_rows_pix] - b_2_range.min) * b_1_range_size;
-+                    if(array_idx < 0 || array_idx >= max_arr_idx) {
-+                        G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
-+                        continue;
-+                    }
-+                    /* pixels meets condtion defined in scatter plot */
-+                    if(i_scatt_conds[array_idx])
-+                        belongs_pix[i_rows_pix] = 1;
-+                }                
-+            }
-+        }
-+
-+        /* update category raster with belonging pixels */
-+        if(fd_cats_rasts[i_cat] >= 0) {
-+            Rast_set_null_value(cat_rast_row, Rast_window_cols(), CELL_TYPE); 
-+
-+            for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+                if(belongs_pix[i_rows_pix])
-+                    cat_rast_row[i_rows_pix] = belongs_pix[i_rows_pix];
-+
-+            Rast_put_c_row (fd_cats_rasts[i_cat], cat_rast_row); 
-+        }
-+
-+        /* update scatter plots with belonging pixels */
-+        update_cat_scatt_plts(bands_rows, belongs_pix, scatts_scatt_plts);
-+    }
-+
-+    G_free(cat_rast_row);
-+    G_free(rast_pixs);
-+    G_free(belongs_pix);
-+
-+    return 0;
-+}
-+
-+/*!
-+   \brief Get list if bands needed to be opened for analysis from scCats struct.
-+*/
-+static void get_needed_bands(struct scCats * cats, int * b_needed_bands)
-+{
-+    // results in b_needed_bands - array of bools - if item has value 1, band (defined by item index) is needed to be opened
-+    int i_cat, i_scatt, cat_id;
-+
-+    for(i_cat = 0;  i_cat < cats->n_a_cats; i_cat++)
-+    {   
-+        for(i_scatt = 0;  i_scatt < cats->cats_arr[i_cat]->n_a_scatts; i_scatt++)
-+        {   
-+            G_debug(3, "Active scatt %d in catt %d", i_scatt, i_cat);
-+
-+            b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2]] = 1;
-+            b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2 + 1]] = 1;
-+        }
-+    }
-+    return;
-+}
-+
-+/*!
-+   \brief Helper function for clean up.
-+*/
-+static void free_compute_scatts_data(int * fd_bands, struct rast_row * bands_rows, int n_a_bands, int * bands_ids, 
-+                                     int * fd_cats_rasts, FILE ** f_cats_rasts_conds, int n_a_cats)
-+{
-+    int i, band_id;
-+
-+    for(i = 0; i < n_a_bands; i++)
-+    {   
-+        band_id = bands_ids[i];
-+        if(band_id >= 0) {
-+            Rast_close(fd_bands[i]);
-+            G_free(bands_rows[band_id].row);
-+            G_free(bands_rows[band_id].null_row);
-+        }
-+    }
-+     
-+    if(f_cats_rasts_conds)
-+        for(i = 0; i < n_a_cats; i++)
-+            if(f_cats_rasts_conds[i])
-+                fclose(f_cats_rasts_conds[i]);
-+
-+    if(fd_cats_rasts)
-+        for(i = 0; i < n_a_cats; i++)
-+            if(fd_cats_rasts[i] >= 0)
-+                Rast_close(fd_cats_rasts[i]);
-+
-+}
-+
-+/*!
-+   \brief Compute scatter plots data.
-+
-+    If category has not defined no category raster condition file and no scatter plot with consdtion,
-+    default scatter plot is computed.
-+
-+   \param region analysis region, beaware that all input data must be prepared for this region (bands (their ranges), cats_rasts_conds rasters...)
-+   \param region function calls Rast_set_window for this region
-+   \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are stored selected areas (conditions) in scatter plots
-+   \param cats_rasts_conds paths to category raster conditions files representing selected areas (conditions) in rasters for every category 
-+   \param cats_rasts_conds index in array represents corresponding category id
-+   \param cats_rasts_conds for manupulation with category raster conditions file see also I_id_scatt_to_bands() and I_insert_patch_to_cat_rast()
-+   \param bands names of analyzed bands, order of bands is defined by their id
-+   \param n_bands number of bands
-+   \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
-+   \param [out] cats_rasts array of raster maps names where will be stored all selected pixels for every category
-+
-+   \return  0 on success
-+   \return -1 on failure
-+*/
-+int I_compute_scatts(struct Cell_head *region, struct scCats * scatt_conds, const char ** cats_rasts_conds,
-+                     const char ** bands, int n_bands, struct scCats * scatts, const char ** cats_rasts) 
-+{
-+    const char *mapset;
-+    char header[1024];
-+
-+    int fd_cats_rasts[scatt_conds->n_a_cats];
-+    FILE * f_cats_rasts_conds[scatt_conds->n_a_cats];
-+
-+    struct rast_row bands_rows[n_bands];
-+
-+    RASTER_MAP_TYPE data_type;
-+
-+    int nrows, i_band, n_a_bands, band_id, 
-+        i, i_row, head_nchars, i_cat, id_cat;
-+   
-+    int fd_bands[n_bands];
-+    int bands_ids[n_bands];
-+    int b_needed_bands[n_bands];  
-+
-+    Rast_set_window(region);
-+
-+    for(i_band = 0; i_band < n_bands; i_band++)
-+        fd_bands[i_band] = -1;
-+    
-+    for(i_band = 0; i_band < n_bands; i_band++)
-+        bands_ids[i_band] = -1;
-+
-+    if (n_bands != scatts->n_bands ||
-+        n_bands != scatt_conds->n_bands)
-+        return -1;
-+
-+    memset(b_needed_bands, 0, (size_t)n_bands * sizeof(int));
-+
-+    get_needed_bands(scatt_conds, &b_needed_bands[0]);
-+    get_needed_bands(scatts, &b_needed_bands[0]);
-+
-+    n_a_bands = 0;
-+
-+    /* open band rasters, which are needed for computation */
-+    for(band_id = 0; band_id < n_bands; band_id++)
-+    {
-+        if(b_needed_bands[band_id])
-+        {
-+            G_debug(3, "Opening raster no. %d with name: %s", band_id, bands[band_id]);
-+
-+            if ((mapset = G_find_raster2(bands[band_id],"")) == NULL) {
-+                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
-+                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+                G_warning(_("Unbale to read find raster <%s>"), bands[band_id]);
-+                return -1;
-+            }
-+            
-+            if ((fd_bands[n_a_bands] = Rast_open_old(bands[band_id], mapset)) < 0) {
-+                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
-+                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+                G_warning(_("Unbale to open raster <%s>"), bands[band_id]);
-+                return -1;
-+            }
-+
-+            data_type = Rast_get_map_type(fd_bands[n_a_bands]);
-+            if(data_type != CELL_TYPE) {
-+                G_warning(_("Raster <%s> type is not <%s>"), bands[band_id], "CELL");
-+                return -1;
-+            }
-+
-+            bands_rows[band_id].row =  Rast_allocate_c_buf();
-+            bands_rows[band_id].null_row =  Rast_allocate_null_buf();
-+
-+            if(Rast_read_range(bands[band_id], mapset, &bands_rows[band_id].rast_range) != 1){
-+                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, 
-+                                         bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+                G_warning(_("Unable to read range of raster <%s>"), bands[band_id]);
-+                return -1;
-+            }      
-+
-+            bands_ids[n_a_bands] = band_id;
-+            ++n_a_bands;
-+        }
-+    }
-+
-+    /* open category rasters condition files and category rasters */
-+    for(i_cat = 0; i_cat < scatts->n_a_cats; i_cat++)
-+    {
-+        id_cat = scatts->cats_ids[i_cat];
-+        if(cats_rasts[id_cat]) {
-+            fd_cats_rasts[i_cat] = Rast_open_new(cats_rasts[id_cat], CELL_TYPE);   
-+        }
-+        else
-+            fd_cats_rasts[i_cat] = -1;
-+
-+        if(cats_rasts_conds[id_cat]) {
-+            f_cats_rasts_conds[i_cat] = fopen(cats_rasts_conds[id_cat], "r");
-+            if(!f_cats_rasts_conds[i_cat]) {
-+                free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, 
-+                                         f_cats_rasts_conds, f_cats_rasts_conds, scatt_conds->n_a_cats);
-+                G_warning(_("Unable to open category raster condtition file <%s>"), bands[band_id]);
-+                return -1;
-+            }
-+        }
-+        else
-+            f_cats_rasts_conds[i_cat] = NULL;
-+    }
-+
-+    head_nchars =  get_cat_rast_header(region, header);
-+    for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
-+        if(f_cats_rasts_conds[i_cat])
-+            if( fseek(f_cats_rasts_conds[i_cat] , head_nchars, SEEK_SET) != 0) {
-+                G_warning(_("Corrupted category raster conditions file (fseek failed)"));
-+                return -1;
-+            }
-+
-+    nrows = Rast_window_rows();
-+
-+    /* analyze bands by rows */
-+    for (i_row = 0; i_row < nrows; i_row++)
-+    {
-+        for(i_band = 0; i_band < n_a_bands; i_band++)
-+        {   
-+            band_id = bands_ids[i_band];
-+            Rast_get_c_row(fd_bands[i_band], bands_rows[band_id].row, i_row);
-+            Rast_get_null_value_row (fd_bands[i_band], bands_rows[band_id].null_row, i_row);
-+        }
-+        if(compute_scatts_from_chunk_row(region, scatt_conds, f_cats_rasts_conds, bands_rows, scatts, fd_cats_rasts) == -1) 
-+        {
-+            free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, fd_cats_rasts, 
-+                                     f_cats_rasts_conds, scatt_conds->n_a_cats);
-+            return -1;
-+        }
-+ 
-+    }
-+    free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, 
-+                             fd_cats_rasts, f_cats_rasts_conds, scatt_conds->n_a_cats); 
-+    return 0;    
-+}
-\ No newline at end of file
-Index: lib/vector/Vlib/open.c
-===================================================================
---- lib/vector/Vlib/open.c	(revision 57601)
-+++ lib/vector/Vlib/open.c	(working copy)
-@@ -240,7 +240,9 @@
-         }
-         else {
-             char file_path[GPATH_MAX];
--            
-+            /* reduce to current mapset if search path was set */
-+            if(strcmp(Map->mapset, "") == 0)
-+                Map->mapset = G_store(G_mapset());
-             /* temporary map: reduce to current mapset if search path
-              * was set */
-             if (strcmp(Map->mapset, "") == 0)
+--- gui/icons/grass/polygon.png	(revision 57633)
++++ gui/icons/grass/polygon.png	(working copy)
+
+Property changes on: gui/icons/grass/polygon.png
+___________________________________________________________________
+Added: svn:mime-type
+## -0,0 +1 ##
++application/octet-stream
+\ No newline at end of property



More information about the grass-commit mailing list