/*
 *  $Id: stats.c 30029 2026-06-09 13:46:07Z yeti-dn $
 *  Copyright (C) 2003-2026 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@gwyddion.net.
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 *  License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
 *  later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 *  details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <glib/gi18n-lib.h>
#include <string.h>
#include <errno.h>
#include <gtk/gtk.h>
#include <gwy.h>

enum {
    PARAM_MASKING,
    PARAM_INSTANT_UPDATE,
    PARAM_REPORT_STYLE,
    PARAM_HOLD_SELECTION,

    WIDGET_RESULTS_MOMENT,
    WIDGET_RESULTS_ORDER,
    WIDGET_RESULTS_HYBRID,
    WIDGET_RESULTS_OTHER,
};

typedef struct {
    gdouble avg;
    gdouble Sa;
    gdouble rms;
    gdouble skew;
    gdouble kurtosis;
    gdouble projarea;
    gdouble theta;
    gdouble phi;
} StatsUncertanties;

#define GWY_TYPE_TOOL_STATS            (gwy_tool_stats_get_type())
#define GWY_TOOL_STATS(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), GWY_TYPE_TOOL_STATS, GwyToolStats))
#define GWY_IS_TOOL_STATS(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), GWY_TYPE_TOOL_STATS))
#define GWY_TOOL_STATS_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), GWY_TYPE_TOOL_STATS, GwyToolStatsClass))

typedef struct _GwyToolStats      GwyToolStats;
typedef struct _GwyToolStatsClass GwyToolStatsClass;

struct _GwyToolStats {
    GwyPlainTool parent_instance;

    GwyParams *params;
    GwyResults *results;

    GwyRectSelectionLabels *rlabels;
    GtkWidget *update;

    GwyParamTable *table_options;
    GwyParamTable *table_results;

    gint isel[4];
    gint isel_prev[4];
    gdouble rsel[4];

    gboolean same_units;
};

struct _GwyToolStatsClass {
    GwyPlainToolClass parent_class;
};

static gboolean     module_register                 (void);
static GwyParamDef* define_module_params            (void);
static GType        gwy_tool_stats_get_type         (void)                      G_GNUC_CONST;
static void         gwy_tool_stats_finalize         (GObject *object);
static void         gwy_tool_stats_init_dialog      (GwyToolStats *tool);
static void         gwy_tool_stats_data_switched    (GwyTool *gwytool,
                                                     GwyDataView *data_view);
static void         gwy_tool_stats_data_changed     (GwyPlainTool *plain_tool);
static void         gwy_tool_stats_mask_changed     (GwyPlainTool *plain_tool);
static void         gwy_tool_stats_response         (GwyTool *tool,
                                                     gint response_id);
static void         gwy_tool_stats_selection_changed(GwyPlainTool *plain_tool,
                                                     gint hint);
static void         update_selected_rectangle       (GwyToolStats *tool);
static void         param_changed                   (GwyToolStats *tool,
                                                     gint id);
static void         update_sensitivity              (GwyToolStats *tool);
static void         update_labels                   (GwyToolStats *tool);
static gboolean     calculate                       (GwyToolStats *tool);
static void         update_units                    (GwyToolStats *tool);
static GwyResults*  create_results                  (void);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Statistics tool."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "4.4",
    "David Nečas (Yeti) & Petr Klapetek",
    "2003",
};

GWY_MODULE_QUERY2(module_info, stats)

G_DEFINE_TYPE(GwyToolStats, gwy_tool_stats, GWY_TYPE_PLAIN_TOOL)

static gboolean
module_register(void)
{
    gwy_tool_func_register(GWY_TYPE_TOOL_STATS);

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, "stats");
    gwy_param_def_add_enum(paramdef, PARAM_MASKING, "masking", NULL, GWY_TYPE_MASKING_TYPE, GWY_MASK_IGNORE);
    gwy_param_def_add_instant_updates(paramdef, PARAM_INSTANT_UPDATE, "instant_update", NULL, TRUE);
    gwy_param_def_add_report_type(paramdef, PARAM_REPORT_STYLE, "report_style", _("Save Statistical Quantities"),
                                  GWY_RESULTS_EXPORT_PARAMETERS, GWY_RESULTS_REPORT_COLON);
    gwy_param_def_add_hold_selection(paramdef, PARAM_HOLD_SELECTION, "hold_selection", NULL);

    return paramdef;
}

static void
gwy_tool_stats_class_init(GwyToolStatsClass *klass)
{
    GwyPlainToolClass *ptool_class = GWY_PLAIN_TOOL_CLASS(klass);
    GwyToolClass *tool_class = GWY_TOOL_CLASS(klass);
    GObjectClass *gobject_class = G_OBJECT_CLASS(klass);

    gobject_class->finalize = gwy_tool_stats_finalize;

    tool_class->icon_name = GWY_ICON_STAT_QUANTITIES;
    tool_class->title = _("Statistical Quantities");
    tool_class->tooltip = _("Statistical quantities");
    tool_class->prefix = "/module/stats";
    tool_class->data_switched = gwy_tool_stats_data_switched;
    tool_class->response = gwy_tool_stats_response;

    ptool_class->data_changed = gwy_tool_stats_data_changed;
    ptool_class->mask_changed = gwy_tool_stats_mask_changed;
    ptool_class->selection_changed = gwy_tool_stats_selection_changed;
}

static void
gwy_tool_stats_finalize(GObject *object)
{
    GwyToolStats *tool = GWY_TOOL_STATS(object);

    gwy_params_save_to_settings(tool->params);
    g_clear_object(&tool->params);
    g_clear_object(&tool->results);

    G_OBJECT_CLASS(gwy_tool_stats_parent_class)->finalize(object);
}

static void
gwy_tool_stats_init(GwyToolStats *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);

    plain_tool->lazy_updates = TRUE;
    plain_tool->unit_style = GWY_UNIT_FORMAT_VFMARKUP;

    tool->params = gwy_params_new_from_settings(define_module_params());
    tool->results = create_results();

    gwy_plain_tool_connect_selection(plain_tool, GWY_TYPE_LAYER_RECTANGLE, "rectangle");
    memset(tool->isel_prev, 0xff, 4*sizeof(gint));
    gwy_plain_tool_enable_selection_holding(plain_tool);

    gwy_tool_stats_init_dialog(tool);
}

static void
gwy_tool_stats_rect_updated(GwyToolStats *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);

    gwy_rect_selection_labels_select(tool->rlabels, plain_tool->selection, plain_tool->field);
}

static void
gwy_tool_stats_init_dialog(GwyToolStats *tool)
{
    GtkDialog *dialog = GTK_DIALOG(GWY_TOOL(tool)->dialog);
    GtkWidget *hbox, *vbox;
    GwyParamTable *table;

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), hbox, FALSE, FALSE, 0);

    /* Selection info */
    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_box_pack_start(GTK_BOX(hbox), vbox, FALSE, FALSE, 0);

    tool->rlabels = gwy_rect_selection_labels_new(TRUE, G_CALLBACK(gwy_tool_stats_rect_updated), tool);
    gtk_box_pack_start(GTK_BOX(vbox), gwy_rect_selection_labels_get_table(tool->rlabels), FALSE, FALSE, 0);

    /* Options */
    table = tool->table_options = gwy_param_table_new(tool->params);
    gwy_param_table_append_header(table, -1, _("Masking Mode"));
    gwy_param_table_append_radio_item(table, PARAM_MASKING, GWY_MASK_EXCLUDE);
    gwy_param_table_append_radio_item(table, PARAM_MASKING, GWY_MASK_INCLUDE);
    gwy_param_table_append_radio_item(table, PARAM_MASKING, GWY_MASK_IGNORE);
    gwy_param_table_append_header(table, -1, _("Options"));
    gwy_param_table_append_checkbox(table, PARAM_INSTANT_UPDATE);
    gwy_param_table_append_hold_selection(table, PARAM_HOLD_SELECTION);
    gwy_plain_tool_add_param_table(GWY_PLAIN_TOOL(tool), table);
    gtk_box_pack_start(GTK_BOX(vbox), gwy_param_table_widget(table), FALSE, FALSE, 0);

    /* Parameters */
    table = tool->table_results = gwy_param_table_new(tool->params);
    gwy_param_table_append_header(table, -1, _("Moment-Based"));
    gwy_param_table_append_results(table, WIDGET_RESULTS_MOMENT, tool->results,
                                   "avg", "rms", "rms_gw", "Sa", "skew", "kurtosis",
                                   NULL);
    gwy_param_table_append_header(table, -1, _("Order-Based"));
    gwy_param_table_append_results(table, WIDGET_RESULTS_ORDER, tool->results,
                                   "min", "max", "median", "Sp", "Sv", "Sz",
                                   NULL);
    gwy_param_table_append_header(table, -1, _("Hybrid"));
    gwy_param_table_append_results(table, WIDGET_RESULTS_HYBRID, tool->results,
                                   "projarea", "area", "volume", "Sdq", "var", "theta", "phi",
                                   NULL);
    gwy_param_table_append_header(table, -1, _("Other"));
    gwy_param_table_append_results(table, WIDGET_RESULTS_OTHER, tool->results,
                                   "linedis",
                                   NULL);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_report(table, PARAM_REPORT_STYLE);
    gwy_param_table_report_set_results(table, PARAM_REPORT_STYLE, tool->results);
    gwy_plain_tool_add_param_table(GWY_PLAIN_TOOL(tool), table);
    gtk_box_pack_start(GTK_BOX(hbox), gwy_param_table_widget(table), FALSE, FALSE, 0);

    tool->update = gwy_stock_add_button_to_dialog(GTK_DIALOG(dialog), GWY_STOCK_UPDATE);
    gwy_plain_tool_add_clear_button(GWY_PLAIN_TOOL(tool));
    gwy_tool_add_hide_button(GWY_TOOL(tool), TRUE);
    gwy_help_add_to_tool_dialog(dialog, GWY_TOOL(tool), GWY_HELP_DEFAULT);

    update_sensitivity(tool);

    g_signal_connect_swapped(tool->table_options, "param-changed", G_CALLBACK(param_changed), tool);
    g_signal_connect_swapped(tool->table_results, "param-changed", G_CALLBACK(param_changed), tool);

    gtk_widget_show_all(gtk_dialog_get_content_area(dialog));
}

static void
gwy_tool_stats_data_switched(GwyTool *gwytool,
                             GwyDataView *data_view)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(gwytool);
    GwyToolStats *tool = GWY_TOOL_STATS(gwytool);
    gboolean ignore = (data_view == plain_tool->data_view);

    GWY_TOOL_CLASS(gwy_tool_stats_parent_class)->data_switched(gwytool, data_view);

    if (ignore || plain_tool->init_failed)
        return;

    gwy_param_table_set_sensitive(tool->table_results, PARAM_REPORT_STYLE, FALSE);
    if (data_view) {
        gwy_object_set_or_reset(plain_tool->layer, GWY_TYPE_LAYER_RECTANGLE,
                                "editable", TRUE,
                                "focus", -1,
                                NULL);
        gwy_selection_set_max_objects(plain_tool->selection, 1);
        gwy_plain_tool_hold_selection(plain_tool, gwy_params_get_flags(tool->params, PARAM_HOLD_SELECTION));
        update_units(tool);
    }
    update_labels(tool);
}

static void
update_units(GwyToolStats *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwyField *field = plain_tool->field;
    GwyUnit *siunitxy = gwy_field_get_unit_xy(field);
    GwyUnit *siunitz = gwy_field_get_unit_z(field);

    gwy_results_set_unit(tool->results, "x", siunitxy);
    gwy_results_set_unit(tool->results, "y", siunitxy);
    gwy_results_set_unit(tool->results, "z", siunitz);
    tool->same_units = gwy_unit_equal(siunitxy, siunitz);
}

static void
update_selected_rectangle(GwyToolStats *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwySelection *selection = plain_tool->selection;
    GwyField *field = plain_tool->field;
    gint n = selection ? gwy_selection_get_data(selection, NULL) : 0;

    gwy_rect_selection_labels_fill(tool->rlabels, n == 1 ? selection : NULL, field, NULL, tool->isel);
}

static void
param_changed(GwyToolStats *tool, gint id)
{
    GwyParams *params = tool->params;
    gboolean do_update = (id != PARAM_INSTANT_UPDATE && id != PARAM_MASKING && id != PARAM_REPORT_STYLE);

    if (id == PARAM_INSTANT_UPDATE)
        do_update = do_update || gwy_params_get_boolean(params, PARAM_INSTANT_UPDATE);
    if (id == PARAM_MASKING)
        do_update = do_update || (GWY_PLAIN_TOOL(tool)->field && GWY_PLAIN_TOOL(tool)->mask_field);
    if (id < 0 || id == PARAM_INSTANT_UPDATE)
        update_sensitivity(tool);
    if (do_update)
        update_labels(tool);
}

static void
update_sensitivity(GwyToolStats *tool)
{
    gtk_widget_set_sensitive(tool->update, !gwy_params_get_boolean(tool->params, PARAM_INSTANT_UPDATE));
}

static void
gwy_tool_stats_data_changed(GwyPlainTool *plain_tool)
{
    GwyToolStats *tool = GWY_TOOL_STATS(plain_tool);

    update_selected_rectangle(tool);
    update_units(tool);
    update_labels(tool);
}

static void
gwy_tool_stats_mask_changed(GwyPlainTool *plain_tool)
{
    GwyToolStats *tool = GWY_TOOL_STATS(plain_tool);

    if (gwy_params_get_enum(tool->params, PARAM_MASKING) != GWY_MASK_IGNORE)
        update_labels(tool);
}

static void
gwy_tool_stats_response(GwyTool *tool,
                        gint response_id)
{
    GWY_TOOL_CLASS(gwy_tool_stats_parent_class)->response(tool, response_id);

    if (response_id == GWY_RESPONSE_UPDATE)
        update_labels(GWY_TOOL_STATS(tool));
}

static void
gwy_tool_stats_selection_changed(GwyPlainTool *plain_tool,
                                 gint hint)
{
    GwyToolStats *tool = GWY_TOOL_STATS(plain_tool);

    g_return_if_fail(hint <= 0);
    update_selected_rectangle(tool);
    if (gwy_params_get_boolean(tool->params, PARAM_INSTANT_UPDATE)) {
        if (memcmp(tool->isel, tool->isel_prev, 4*sizeof(gint)) != 0)
            update_labels(tool);
    }
    else
        gwy_param_table_set_sensitive(tool->table_results, PARAM_REPORT_STYLE, FALSE);
}

static void
update_labels(GwyToolStats *tool)
{
    static const gint results_ids[] = {
        WIDGET_RESULTS_MOMENT, WIDGET_RESULTS_ORDER, WIDGET_RESULTS_HYBRID, WIDGET_RESULTS_OTHER,
    };
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    guint i;

    if (!plain_tool->field) {
        for (i = 0; i < G_N_ELEMENTS(results_ids); i++)
            gwy_param_table_results_clear(tool->table_results, results_ids[i]);
        return;
    }

    if (plain_tool->pending_updates & GWY_PLAIN_TOOL_CHANGED_SELECTION)
        update_selected_rectangle(tool);
    plain_tool->pending_updates = 0;

    if (calculate(tool)) {
        for (i = 0; i < G_N_ELEMENTS(results_ids); i++)
            gwy_param_table_results_fill(tool->table_results, results_ids[i]);
    }
}

/* See libgwyddion/internal.h */
static inline gint
nielded_included(const gint *m, GwyMaskingType masking)
{
    if (masking == GWY_MASK_INCLUDE)
        return *m > 0;
    if (masking == GWY_MASK_EXCLUDE)
        return *m <= 0;
    return 1;
}

static gdouble
gwy_field_scan_line_discrepancy(GwyField *field,
                                GwyNield *mask,
                                GwyMaskingType masking,
                                gint col, gint row,
                                gint width, gint height)
{
    gint xres = field->xres, yres = field->yres;

    /* Cannot calculate discrepancy with only one scan line. */
    if (yres < 2)
        return 0.0;

    gdouble s2 = 0.0;
    gint n = 0;
    const gdouble *data = gwy_field_get_data_const(field);
    const gint *mdata = mask ? gwy_nield_get_data_const(mask) : NULL;
    for (gint i = 0; i < height; i++) {
        /* Take the two neighbour rows, except for the first and last one, where we simply calculate the difference
         * from the sole neigbour. */
        const gdouble *drow = data + (row + i)*xres + col;
        const gdouble *drowp = (row + i > 0) ? drow - xres : drow + xres;
        const gdouble *drown = (row + i < yres-1) ? drow + xres : drow - xres;
        if (mask) {
            const gint *mrow = mdata + (row + i)*xres + col;
            for (gint j = 0; j < width; j++) {
                if (nielded_included(mrow + j, masking)) {
                    gdouble v = drow[j] - 0.5*(drowp[j] + drown[j]);
                    s2 += v*v;
                    n++;
                }
            }
        }
        else {
            for (gint j = 0; j < width; j++) {
                gdouble v = drow[j] - 0.5*(drowp[j] + drown[j]);
                s2 += v*v;
            }
            n += width;
        }
    }

    return n ? sqrt(s2/n) : 0.0;
}

static gboolean
calculate(GwyToolStats *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwyField *field = plain_tool->field;
    GwyNield *mask = plain_tool->mask_field;
    GwyMaskingType masking = gwy_params_get_masking(tool->params, PARAM_MASKING, &mask);
    GwyResults *results = tool->results;
    gboolean have_inclination = FALSE;

    gwy_param_table_set_sensitive(tool->table_results, PARAM_REPORT_STYLE, FALSE);
    gwy_assign(tool->isel_prev, tool->isel, 4);
    gint col = tool->isel[0];
    gint row = tool->isel[1];
    gint w = tool->isel[2]+1 - tool->isel[0];
    gint h = tool->isel[3]+1 - tool->isel[1];
    gwy_debug("%d x %d at (%d, %d)", w, h, col, row);

    if (!w || !h)
        return FALSE;

    gdouble xoff = gwy_field_get_xoffset(field), yoff = gwy_field_get_yoffset(field);

    gdouble q = gwy_field_get_dx(field) * gwy_field_get_dy(field);
    gint nn = w*h;
    if (mask) {
        nn = gwy_nield_area_count(mask, NULL, GWY_MASK_IGNORE, col, row, w, h);
        if (masking == GWY_MASK_EXCLUDE)
            nn = w*h - nn;
    }
    gdouble projarea = nn * q;
    /* TODO: do something more reasonable when nn == 0 */

    gdouble min, max, avg, Sa, rms, skew, kurtosis;
    gwy_field_area_min_max(field, mask, masking, col, row, w, h, &min, &max);
    gwy_field_area_stats(field, mask, masking, col, row, w, h, &avg, &Sa, &rms, &skew, &kurtosis);
    gdouble rms_gw = rms;
    if (masking == GWY_MASK_INCLUDE)
        rms_gw = gwy_field_area_grainwise_rms(field, mask, col, row, w, h);

    gdouble median = gwy_field_area_median(field, mask, masking, col, row, w, h);
    gdouble var = gwy_field_area_variation(field, mask, masking, col, row, w, h);
    gdouble Sdq = gwy_field_area_rms_slope(field, mask, masking, col, row, w, h);

    gdouble linedis = gwy_field_scan_line_discrepancy(field, mask, masking, col, row, w, h);
    if (linedis > 0.0)
        linedis /= sqrt(gwy_field_area_mean_square(field, mask, masking, col, row, w, h));

    gdouble area = 0.0;
    if (tool->same_units)
        area = gwy_field_area_surface_area(field, mask, masking, col, row, w, h);
    gdouble volume = gwy_field_area_volume(field, mask, masking, GWY_FIELD_VOLUME_DEFAULT, col, row, w, h);

    gdouble theta = 0.0, phi = 0.0;
    if (tool->same_units) {
        gdouble nx, ny, nz;
        if ((have_inclination = gwy_field_area_normal_coeffs(field, mask, masking, col, row, w, h,
                                                             &nx, &ny, &nz))) {
            theta = atan2(hypot(nx, ny), nz);
            /* Inclination is upslope, not down. It is not the normal. */
            phi = atan2(ny, nx) + G_PI;
        }
    }

    gwy_results_fill_format(results, "isel", "w", w, "h", h, "x", col, "y", row, NULL);
    gwy_results_fill_format(results, "realsel",
                            "w", fabs(tool->rsel[2] - tool->rsel[0]),
                            "h", fabs(tool->rsel[3] - tool->rsel[1]),
                            "x", MIN(tool->rsel[0], tool->rsel[2]) + xoff,
                            "y", MIN(tool->rsel[1], tool->rsel[3]) + yoff,
                            NULL);
    gwy_results_fill_values(results,
                            "masking", !!mask,
                            "min", min,
                            "max", max,
                            "median", median,
                            "Sp", max - avg,
                            "Sv", avg - min,
                            "Sz", max - min,
                            "rms_gw", rms_gw,
                            "area", area,
                            "Sdq", Sdq,
                            "volume", volume,
                            "var", var,
                            "linedis", linedis,
                            NULL);

    /* Try to have the same format for area and projected area but only if it is sane. */
    gwy_results_unbind_formats(results, "area", "projarea", NULL);
    if (area < 120.0*projarea)
        gwy_results_bind_formats(results, "area", "projarea", NULL);

    gwy_results_fill_values(results,
                            "avg", avg,
                            "Sa", Sa,
                            "rms", rms,
                            "skew", skew,
                            "kurtosis", kurtosis,
                            "projarea", projarea,
                            "phi", phi,
                            "theta", theta,
                            NULL);

    if (!have_inclination)
        gwy_results_set_na(results, "phi", "theta", NULL);
    if (!tool->same_units)
        gwy_results_set_na(tool->results, "area", "theta", "phi", NULL);
    if (mask && masking == GWY_MASK_EXCLUDE)
        gwy_results_set_na(tool->results, "rms_gw", NULL);

    gwy_results_fill_filename(results, "file", GWY_FILE(plain_tool->container));
    gwy_results_fill_data_name(results, "image", GWY_FILE(plain_tool->container), GWY_FILE_IMAGE, plain_tool->id);

    gwy_param_table_set_sensitive(tool->table_results, PARAM_REPORT_STYLE, TRUE);

    return TRUE;
}

static GwyResults*
create_results(void)
{
    GwyResults *results = gwy_results_new();

    gwy_results_add_header(results, N_("Statistical Quantities"));
    gwy_results_add_value_str(results, "file", N_("File"));
    gwy_results_add_value_str(results, "image", N_("Image"));
    gwy_results_add_format(results, "isel", N_("Selected area"), TRUE,
                           N_("%{w}i × %{h}i at (%{x}i, %{y}i)"),
                           "unit-str", N_("px"), "translate-unit", TRUE,
                           NULL);
    gwy_results_add_format(results, "realsel", "", TRUE,
                           N_("%{w}v × %{h}v at (%{x}v, %{y}v)"),
                           "power-x", 1,
                           NULL);
    gwy_results_add_value_yesno(results, "masking", N_("Mask in use"));
    gwy_results_add_separator(results);

    gwy_results_add_value_z(results, "avg", N_("Average value"));
    gwy_results_add_value(results, "rms", N_("RMS roughness"), "power-z", 1, "symbol", "Sq", NULL);
    gwy_results_add_value_z(results, "rms_gw", N_("RMS (grain-wise)"));
    gwy_results_add_value(results, "Sa", N_("Mean roughness"), "power-z", 1, "symbol", "Sa", NULL);
    gwy_results_bind_formats(results, "Sa", "rms", "rms_gw", NULL);
    gwy_results_add_value(results, "skew", N_("Skew"), "symbol", "Ssk", NULL);
    gwy_results_add_value_plain(results, "kurtosis", N_("Excess kurtosis"));
    gwy_results_add_separator(results);

    gwy_results_add_value_z(results, "min", N_("Minimum"));
    gwy_results_add_value_z(results, "max", N_("Maximum"));
    gwy_results_add_value_z(results, "median", N_("Median"));
    gwy_results_add_value(results, "Sp", N_("Maximum peak height"), "power-z", 1, "symbol", "Sp", NULL);
    gwy_results_add_value(results, "Sv", N_("Maximum pit depth"), "power-z", 1, "symbol", "Sv", NULL);
    gwy_results_add_value(results, "Sz", N_("Maximum height"), "power-z", 1, "symbol", "Sz", NULL);
    gwy_results_bind_formats(results, "min", "max", "avg", "median", "Sp", "Sv", "Sz", NULL);
    gwy_results_add_separator(results);

    gwy_results_add_value(results, "projarea", N_("Projected area"),
                          "type", GWY_RESULTS_VALUE_FLOAT,
                          "power-x", 1, "power-y", 1,
                          NULL);
    gwy_results_add_value(results, "area", N_("Surface area"),
                          "type", GWY_RESULTS_VALUE_FLOAT,
                          "power-x", 1, "power-y", 1,
                          NULL);
    gwy_results_add_value(results, "Sdq", N_("Surface slope"),
                          "type", GWY_RESULTS_VALUE_FLOAT,
                          "power-x", -1, "power-z", 1,
                          "symbol", "Sdq",
                          NULL);
    gwy_results_add_value(results, "volume", N_("Volume"),
                          "type", GWY_RESULTS_VALUE_FLOAT,
                          "power-x", 1, "power-y", 1, "power-z", 1,
                          NULL);
    gwy_results_add_value(results, "var", N_("Variation"),
                          "type", GWY_RESULTS_VALUE_FLOAT,
                          "power-x", 1, "power-z", 1,
                          NULL);
    gwy_results_add_value_angle(results, "theta", N_("Inclination θ"));
    gwy_results_add_value_angle(results, "phi", N_("Inclination φ"));
    gwy_results_add_separator(results);

    gwy_results_add_value_plain(results, "linedis", N_("Scan line discrepancy"));

    return results;
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */
