/*
 *  $Id: rprofile.c 30047 2026-06-11 08:30:45Z 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 <stdlib.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "libgwyddion/omp.h"

enum {
    RESPONSE_IMPROVE = GWY_RESPONSE_USER,
    RESPONSE_IMPROVE_ALL,
};

enum {
    COLUMN_I, COLUMN_X1, COLUMN_Y1, COLUMN_X2, COLUMN_Y2, NCOLUMNS
};

enum {
    PARAM_RESOLUTION,
    PARAM_FIXRES,
    PARAM_NUMBER_LINES,
    PARAM_SEPARATE,
    PARAM_MASKING,
    PARAM_TARGET_GRAPH,
    PARAM_HOLD_SELECTION,
    PARAM_OPTIONS_VISIBLE,

    BUTTON_IMPROVE,
    BUTTON_IMPROVE_ALL,
};

#define GWY_TYPE_TOOL_RPROFILE            (gwy_tool_rprofile_get_type())
#define GWY_TOOL_RPROFILE(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), GWY_TYPE_TOOL_RPROFILE, GwyToolRprofile))
#define GWY_IS_TOOL_RPROFILE(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), GWY_TYPE_TOOL_RPROFILE))
#define GWY_TOOL_RPROFILE_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), GWY_TYPE_TOOL_RPROFILE, GwyToolRprofileClass))

typedef struct _GwyToolRprofile      GwyToolRprofile;
typedef struct _GwyToolRprofileClass GwyToolRprofileClass;

struct _GwyToolRprofile {
    GwyPlainTool parent_instance;

    GwyParams *params;

    GtkTreeView *treeview;
    GtkTreeModel *model;

    GwyGraphModel *gmodel;

    GtkWidget *options;
    GwyParamTable *table;

    GwyValueFormat *pixel_format;
};

struct _GwyToolRprofileClass {
    GwyPlainToolClass parent_class;
};

static gboolean     module_register                    (void);
static GwyParamDef* define_module_params               (void);
static GType        gwy_tool_rprofile_get_type         (void)                      G_GNUC_CONST;
static void         gwy_tool_rprofile_finalize         (GObject *object);
static void         gwy_tool_rprofile_init_dialog      (GwyToolRprofile *tool);
static void         gwy_tool_rprofile_data_switched    (GwyTool *gwytool,
                                                        GwyDataView *data_view);
static void         gwy_tool_rprofile_response         (GwyTool *gwytool,
                                                        gint response_id);
static void         gwy_tool_rprofile_data_changed     (GwyPlainTool *plain_tool);
static void         gwy_tool_rprofile_selection_changed(GwyPlainTool *plain_tool,
                                                        gint hint);
static void         gwy_tool_rprofile_apply            (GwyToolRprofile *tool);
static void         param_changed                      (GwyToolRprofile *tool,
                                                        gint id);
static void         update_symm_sensitivty             (GwyToolRprofile *tool);
static void         update_curve                       (GwyToolRprofile *tool,
                                                        gint i);
static void         update_all_curves                  (GwyToolRprofile *tool);
static void         improve_all                        (GwyToolRprofile *tool);
static void         improve                            (GwyToolRprofile *tool);
static void         symmetrize_profile                 (GwyToolRprofile *tool,
                                                        gint id);
static void         render_cell                        (GtkCellLayout *layout,
                                                        GtkCellRenderer *renderer,
                                                        GtkTreeModel *model,
                                                        GtkTreeIter *iter,
                                                        gpointer user_data);
static void         render_color                       (GtkCellLayout *layout,
                                                        GtkCellRenderer *renderer,
                                                        GtkTreeModel *model,
                                                        GtkTreeIter *iter,
                                                        gpointer user_data);
static gdouble      angular_average_mismatch           (GwyField *field,
                                                        GwyNield *mask,
                                                        GwyMaskingType masking,
                                                        gdouble x,
                                                        gdouble y,
                                                        gdouble r,
                                                        gint nstats);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Creates angularly averaged profile graphs."),
    "Yeti <yeti@gwyddion.net>",
    "2.2",
    "David Nečas (Yeti) & Petr Klapetek",
    "2018",
};

GWY_MODULE_QUERY2(module_info, rprofile)

G_DEFINE_TYPE(GwyToolRprofile, gwy_tool_rprofile, GWY_TYPE_PLAIN_TOOL)

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

    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, "rprofile");
    gwy_param_def_add_int(paramdef, PARAM_RESOLUTION, "resolution", _("_Fixed resolution"), 4, 16384, 120);
    gwy_param_def_add_boolean(paramdef, PARAM_FIXRES, "fixres", _("_Fixed resolution"), FALSE);
    gwy_param_def_add_boolean(paramdef, PARAM_NUMBER_LINES, "number_lines", _("_Number lines"), TRUE);
    gwy_param_def_add_boolean(paramdef, PARAM_SEPARATE, "separate", _("_Separate profiles"), FALSE);
    gwy_param_def_add_enum(paramdef, PARAM_MASKING, "masking", NULL, GWY_TYPE_MASKING_TYPE, GWY_MASK_IGNORE);
    gwy_param_def_add_target_graph(paramdef, PARAM_TARGET_GRAPH, NULL, NULL);
    gwy_param_def_add_hold_selection(paramdef, PARAM_HOLD_SELECTION, "hold_selection", NULL);
    gwy_param_def_add_boolean(paramdef, PARAM_OPTIONS_VISIBLE, "options_visible", NULL, FALSE);

    return paramdef;
}

static void
gwy_tool_rprofile_class_init(GwyToolRprofileClass *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_rprofile_finalize;

    tool_class->icon_name = GWY_ICON_RADIAL_PROFILE;
    tool_class->title = _("Radial Profiles");
    tool_class->tooltip = _("Extract angularly averaged profiles");
    tool_class->prefix = "/module/rprofile";
    tool_class->default_width = 640;
    tool_class->default_height = 400;
    tool_class->data_switched = gwy_tool_rprofile_data_switched;
    tool_class->response = gwy_tool_rprofile_response;

    ptool_class->data_changed = gwy_tool_rprofile_data_changed;
    ptool_class->selection_changed = gwy_tool_rprofile_selection_changed;
}

static void
gwy_tool_rprofile_finalize(GObject *object)
{
    GwyToolRprofile *tool = GWY_TOOL_RPROFILE(object);

    gwy_params_save_to_settings(tool->params);
    g_clear_object(&tool->params);
    if (tool->model) {
        gtk_tree_view_set_model(tool->treeview, NULL);
        g_clear_object(&tool->model);
    }
    g_clear_object(&tool->gmodel);
    GWY_FREE_VALUE_FORMAT(tool->pixel_format);

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

static void
gwy_tool_rprofile_init(GwyToolRprofile *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);

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

    tool->params = gwy_params_new_from_settings(define_module_params());
    tool->pixel_format = gwy_value_format_new(1.0, 0, _("px"));

    gwy_plain_tool_connect_selection(plain_tool, GWY_TYPE_LAYER_LINE, "line");
    gwy_plain_tool_enable_selection_holding(plain_tool);

    gwy_tool_rprofile_init_dialog(tool);
}

static void
gwy_tool_rprofile_init_dialog(GwyToolRprofile *tool)
{
    static const gchar *column_titles[] = {
        "<b>n</b>", "<b>x<sub>1</sub></b>", "<b>y<sub>1</sub></b>", "<b>x<sub>2</sub></b>", "<b>y<sub>2</sub></b>",
    };
    GtkDialog *dialog = GTK_DIALOG(GWY_TOOL(tool)->dialog);
    GtkTreeViewColumn *column;
    GtkTreeSelection *selection;
    GtkCellRenderer *renderer;
    GtkWidget *scwin, *label, *hbox, *vbox, *options, *graph;
    GwyParamTable *table;
    GwyNullStore *store;
    guint i;

    tool->gmodel = gwy_graph_model_new();
    g_object_set(tool->gmodel, "title", _("Radial profiles"), "label-visible", FALSE, NULL);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), hbox, TRUE, TRUE, 0);

    /* Left pane */
    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
    gtk_widget_set_hexpand(vbox, FALSE);
    gtk_box_pack_start(GTK_BOX(hbox), vbox, FALSE, TRUE, 0);

    /* Line coordinates */
    store = gwy_null_store_new(0);
    tool->model = GTK_TREE_MODEL(store);
    tool->treeview = GTK_TREE_VIEW(gtk_tree_view_new_with_model(tool->model));
    gwy_plain_tool_enable_object_deletion(GWY_PLAIN_TOOL(tool), tool->treeview);

    for (i = 0; i < NCOLUMNS; i++) {
        column = gtk_tree_view_column_new();
        gtk_tree_view_column_set_expand(column, TRUE);
        gtk_tree_view_column_set_alignment(column, 0.5);
        g_object_set_data(G_OBJECT(column), "id", GUINT_TO_POINTER(i));
        renderer = gtk_cell_renderer_text_new();
        g_object_set(renderer, "xalign", 1.0, NULL);
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(column), renderer, TRUE);
        gtk_cell_layout_set_cell_data_func(GTK_CELL_LAYOUT(column), renderer, render_cell, tool, NULL);
        if (i == COLUMN_I) {
            renderer = gwy_cell_renderer_color_new();
            gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(column), renderer, FALSE);
            gtk_cell_layout_set_cell_data_func(GTK_CELL_LAYOUT(column), renderer, render_color, tool, NULL);
        }

        label = gtk_label_new(NULL);
        gtk_label_set_markup(GTK_LABEL(label), column_titles[i]);
        gtk_tree_view_column_set_widget(column, label);
        gtk_widget_show(label);
        gtk_tree_view_append_column(tool->treeview, column);
    }

    scwin = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_container_add(GTK_CONTAINER(scwin), GTK_WIDGET(tool->treeview));
    gtk_box_pack_start(GTK_BOX(vbox), scwin, TRUE, TRUE, 0);

    /* Options */
    options = gwy_create_expander_with_param(_("<b>Options</b>"), tool->params, PARAM_OPTIONS_VISIBLE);
    gtk_box_pack_start(GTK_BOX(vbox), options, FALSE, FALSE, 0);

    table = tool->table = gwy_param_table_new(tool->params);
    gwy_param_table_append_button(table, BUTTON_IMPROVE, -1, RESPONSE_IMPROVE, _("S_ymmetrize"));
    gwy_param_table_append_button(table, BUTTON_IMPROVE_ALL, BUTTON_IMPROVE,
                                  RESPONSE_IMPROVE_ALL, _("Symmetrize _All"));
    gwy_param_table_append_slider(table, PARAM_RESOLUTION);
    gwy_param_table_add_enabler(table, PARAM_FIXRES, PARAM_RESOLUTION);
    gwy_param_table_append_checkbox(table, PARAM_NUMBER_LINES);
    gwy_param_table_append_checkbox(table, PARAM_SEPARATE);
    gwy_param_table_append_combo(table, PARAM_MASKING);
    gwy_param_table_append_target_graph(table, PARAM_TARGET_GRAPH, tool->gmodel);
    gwy_param_table_append_hold_selection(table, PARAM_HOLD_SELECTION);
    gtk_container_add(GTK_CONTAINER(options), gwy_param_table_widget(table));
    gwy_plain_tool_add_param_table(GWY_PLAIN_TOOL(tool), table);

    graph = gwy_graph_new(tool->gmodel);
    gwy_graph_enable_user_input(GWY_GRAPH(graph), FALSE);
    gtk_box_pack_start(GTK_BOX(hbox), graph, TRUE, TRUE, 2);

    gwy_plain_tool_add_clear_button(GWY_PLAIN_TOOL(tool));
    gwy_tool_add_hide_button(GWY_TOOL(tool), FALSE);
    gwy_plain_tool_add_apply_button(GWY_PLAIN_TOOL(tool));
    gtk_dialog_set_default_response(dialog, GTK_RESPONSE_APPLY);
    gtk_dialog_set_response_sensitive(dialog, GTK_RESPONSE_APPLY, FALSE);
    gwy_help_add_to_tool_dialog(dialog, GWY_TOOL(tool), GWY_HELP_DEFAULT);

    selection = gtk_tree_view_get_selection(tool->treeview);
    g_signal_connect_swapped(selection, "changed", G_CALLBACK(update_symm_sensitivty), tool);
    g_signal_connect_swapped(tool->table, "param-changed", G_CALLBACK(param_changed), tool);

    gtk_widget_show_all(gtk_dialog_get_content_area(dialog));
    gwy_param_table_param_changed(tool->table, -1);
}

static void
gwy_tool_rprofile_data_switched(GwyTool *gwytool, GwyDataView *data_view)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(gwytool);
    GwyToolRprofile *tool = GWY_TOOL_RPROFILE(gwytool);
    gboolean ignore = (data_view == plain_tool->data_view);

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

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

    if (data_view) {
        gwy_object_set_or_reset(plain_tool->layer, GWY_TYPE_LAYER_LINE,
                                "numbered", gwy_params_get_boolean(tool->params, PARAM_NUMBER_LINES),
                                "thickness", 1.0,
                                "center-tick", TRUE,
                                "editable", TRUE,
                                "focus", -1,
                                NULL);
        gwy_selection_set_max_objects(plain_tool->selection, 1024);
        gwy_plain_tool_hold_selection(plain_tool, gwy_params_get_flags(tool->params, PARAM_HOLD_SELECTION));
    }

    gwy_graph_model_remove_all_curves(tool->gmodel);
    update_all_curves(tool);
    gwy_param_table_data_id_refilter(tool->table, PARAM_TARGET_GRAPH);
}

static void
gwy_tool_rprofile_response(GwyTool *gwytool, gint response_id)
{
    GwyToolRprofile *tool = GWY_TOOL_RPROFILE(gwytool);

    GWY_TOOL_CLASS(gwy_tool_rprofile_parent_class)->response(gwytool, response_id);

    if (response_id == GTK_RESPONSE_APPLY)
        gwy_tool_rprofile_apply(tool);
    else if (response_id == RESPONSE_IMPROVE)
        improve(tool);
    else if (response_id == RESPONSE_IMPROVE_ALL)
        improve_all(tool);
}

static void
gwy_tool_rprofile_data_changed(GwyPlainTool *plain_tool)
{
    update_all_curves(GWY_TOOL_RPROFILE(plain_tool));
    gwy_param_table_data_id_refilter(GWY_TOOL_RPROFILE(plain_tool)->table, PARAM_TARGET_GRAPH);
}

static void
gwy_tool_rprofile_selection_changed(GwyPlainTool *plain_tool,
                                    gint hint)
{
    GwyToolRprofile *tool = GWY_TOOL_RPROFILE(plain_tool);
    GtkDialog *dialog = GTK_DIALOG(GWY_TOOL(tool)->dialog);
    GwyNullStore *store = store = GWY_NULL_STORE(tool->model);
    gint n = gwy_null_store_get_n_rows(store);

    g_return_if_fail(hint <= n);

    if (hint < 0) {
        gtk_tree_view_set_model(tool->treeview, NULL);
        n = (plain_tool->selection ? gwy_selection_get_data(plain_tool->selection, NULL) : 0);
        gwy_null_store_set_n_rows(store, n);
        gtk_tree_view_set_model(tool->treeview, tool->model);
        gwy_graph_model_remove_all_curves(tool->gmodel);
        update_all_curves(tool);
    }
    else {
        GtkTreeSelection *selection;
        GtkTreePath *path;
        GtkTreeIter iter;

        if (hint < n)
            gwy_null_store_row_changed(store, hint);
        else
            gwy_null_store_set_n_rows(store, n+1);
        update_curve(tool, hint);
        n++;

        gtk_tree_model_iter_nth_child(tool->model, &iter, NULL, hint);
        path = gtk_tree_model_get_path(tool->model, &iter);
        selection = gtk_tree_view_get_selection(tool->treeview);
        gtk_tree_selection_select_iter(selection, &iter);
        gtk_tree_view_scroll_to_cell(tool->treeview, path, NULL, FALSE, 0.0, 0.0);
        gtk_tree_path_free(path);
    }

    gtk_dialog_set_response_sensitive(dialog, GTK_RESPONSE_APPLY, n > 0);
}

static void
param_changed(GwyToolRprofile *tool, gint id)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwyParams *params = tool->params;
    gboolean do_update = (id != PARAM_MASKING && id != PARAM_SEPARATE && id != PARAM_NUMBER_LINES
                          && id != PARAM_TARGET_GRAPH && id != PARAM_OPTIONS_VISIBLE);

    if (id == PARAM_MASKING)
        do_update = do_update || (plain_tool->field && plain_tool->mask_field);
    if (id < 0 || id == PARAM_NUMBER_LINES) {
        if (plain_tool->layer)
            g_object_set(plain_tool->layer, "numbered", gwy_params_get_boolean(params, PARAM_NUMBER_LINES), NULL);
    }
    if (id < 0 || id == PARAM_SEPARATE) {
        gboolean separate = gwy_params_get_boolean(params, PARAM_SEPARATE);
        GwyAppDataId dataid = GWY_APP_DATA_ID_NONE;

        gwy_param_table_set_sensitive(tool->table, PARAM_TARGET_GRAPH, !separate);
        if (separate)
            gwy_param_table_set_data_id(tool->table, PARAM_TARGET_GRAPH, dataid);
    }
    if (do_update)
        update_all_curves(tool);
}

static void
update_symm_sensitivty(GwyToolRprofile *tool)
{
    GtkTreeSelection *selection = gtk_tree_view_get_selection(tool->treeview);
    gboolean is_selected, has_lines;
    GtkTreeModel *model;
    GtkTreeIter iter;

    is_selected = gtk_tree_selection_get_selected(selection, &model, &iter);
    has_lines = (model && gtk_tree_model_iter_n_children(model, NULL) > 0);

    gwy_param_table_set_sensitive(tool->table, BUTTON_IMPROVE, is_selected);
    gwy_param_table_set_sensitive(tool->table, BUTTON_IMPROVE_ALL, has_lines);
}

static gint
calculate_lineres(GwyToolRprofile *tool, const gdouble *line)
{
    GwyField *dfield = GWY_PLAIN_TOOL(tool)->field;
    gint xl1, xl2, yl1, yl2, lineres;

    if (gwy_params_get_boolean(tool->params, PARAM_FIXRES))
        return gwy_params_get_int(tool->params, PARAM_RESOLUTION);

    xl1 = floor(gwy_field_rtoj(dfield, line[0]));
    yl1 = floor(gwy_field_rtoi(dfield, line[1]));
    xl2 = floor(gwy_field_rtoj(dfield, line[2]));
    yl2 = floor(gwy_field_rtoi(dfield, line[3]));
    lineres = GWY_ROUND(hypot(abs(xl1 - xl2) + 1, abs(yl1 - yl2) + 1));
    lineres = MAX(lineres, 4);

    return lineres;
}

static void
update_curve(GwyToolRprofile *tool, gint i)
{
    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);
    GwyGraphCurveModel *gcmodel;
    gdouble xc, yc, r, line[4];
    gint n, lineres;
    gchar *desc;
    const GwyRGBA *color;

    g_return_if_fail(plain_tool->selection);
    if (!gwy_selection_get_object(plain_tool->selection, i, line))
        g_return_if_reached();
    lineres = calculate_lineres(tool, line);

    xc = 0.5*(line[0] + line[2]) + field->xoff;
    yc = 0.5*(line[1] + line[3]) + field->yoff;
    r = 0.5*hypot(line[2] - line[0], line[3] - line[1]);

    /* Just create some line when there is none. */
    r = fmax(r, hypot(gwy_field_get_dx(field), gwy_field_get_dy(field)));
    GwyLine *profile = gwy_field_angular_average(field, mask, masking, xc, yc, r, lineres);

    n = gwy_graph_model_get_n_curves(tool->gmodel);
    if (i < n) {
        gcmodel = gwy_graph_model_get_curve(tool->gmodel, i);
        gwy_graph_curve_model_set_data_from_line(gcmodel, profile, 0, 0);
    }
    else {
        gcmodel = gwy_graph_curve_model_new();
        desc = g_strdup_printf(_("Radial profile %d"), i+1);
        color = gwy_graph_get_preset_color(i);
        g_object_set(gcmodel,
                     "mode", GWY_GRAPH_CURVE_LINE,
                     "description", desc,
                     "color", color,
                     NULL);
        g_free(desc);
        gwy_graph_curve_model_set_data_from_line(gcmodel, profile, 0, 0);
        gwy_graph_model_add_curve(tool->gmodel, gcmodel);
        g_object_unref(gcmodel);

        if (i == 0) {
            gwy_graph_model_set_units_from_field(tool->gmodel, field, 1, 0, 0, 1);
            gwy_param_table_data_id_refilter(tool->table, PARAM_TARGET_GRAPH);
        }
    }
    g_object_unref(profile);
}

static void
improve(GwyToolRprofile *tool)
{
    GtkTreeSelection *selection;
    GtkTreeModel *model;
    GtkTreePath *path;
    GtkTreeIter iter;
    const gint *indices;

    selection = gtk_tree_view_get_selection(tool->treeview);
    if (!gtk_tree_selection_get_selected(selection, &model, &iter))
        return;

    path = gtk_tree_model_get_path(model, &iter);
    indices = gtk_tree_path_get_indices(path);
    gwy_app_wait_cursor_start(GTK_WINDOW(GWY_TOOL(tool)->dialog));
    symmetrize_profile(tool, indices[0]);
    gwy_app_wait_cursor_finish(GTK_WINDOW(GWY_TOOL(tool)->dialog));
    gtk_tree_path_free(path);
}

static void
improve_all(GwyToolRprofile *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    gint n, i;

    if (!plain_tool->selection || !(n = gwy_selection_get_data(plain_tool->selection, NULL)))
        return;

    gwy_app_wait_cursor_start(GTK_WINDOW(GWY_TOOL(tool)->dialog));
    for (i = 0; i < n; i++)
        symmetrize_profile(tool, i);
    gwy_app_wait_cursor_finish(GTK_WINDOW(GWY_TOOL(tool)->dialog));
}

static void
update_all_curves(GwyToolRprofile *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    gint n, i;

    if (!plain_tool->selection || !(n = gwy_selection_get_data(plain_tool->selection, NULL))) {
        gwy_graph_model_remove_all_curves(tool->gmodel);
        return;
    }

    for (i = 0; i < n; i++)
        update_curve(tool, 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
angular_average_mismatch(GwyField *field,
                         GwyNield *mask,
                         GwyMaskingType masking,
                         gdouble x,
                         gdouble y,
                         gdouble r,
                         gint nstats)
{
    gint ifrom, ito, jfrom, jto, k, xres, yres, i, j;
    gdouble xreal, yreal, dx, dy, xoff, yoff, h, mismatch;
    gdouble *target, *weight, *sum2;

    g_return_val_if_fail(GWY_IS_FIELD(field), G_MAXDOUBLE);
    g_return_val_if_fail(r >= 0.0, G_MAXDOUBLE);
    xres = field->xres;
    yres = field->yres;

    if (mask) {
        g_return_val_if_fail(GWY_IS_NIELD(mask), G_MAXDOUBLE);
        g_return_val_if_fail(mask->xres == xres, G_MAXDOUBLE);
        g_return_val_if_fail(mask->yres == yres, G_MAXDOUBLE);
    }

    xreal = field->xreal;
    yreal = field->yreal;
    xoff = field->xoff;
    yoff = field->yoff;
    g_return_val_if_fail(x >= xoff && x <= xoff + xreal, G_MAXDOUBLE);
    g_return_val_if_fail(y >= yoff && y <= yoff + yreal, G_MAXDOUBLE);
    /* Just for integer overflow; we limit i and j ranges explicitly later. */
    r = MIN(r, hypot(xreal, yreal));
    x -= xoff;
    y -= yoff;

    dx = xreal/xres;
    dy = yreal/yres;

    /* Prefer sampling close to the shorter step. */
    if (nstats < 1) {
        h = 2.0*dx*dy/(dx + dy);
        nstats = GWY_ROUND(r/h);
        nstats = MAX(nstats, 1);
    }
    h = r/nstats;

    const gdouble *d = gwy_field_get_data_const(field);
    const gint *m = mask ? gwy_nield_get_data_const(mask) : NULL;

    /* Just return something for single-point lines. */
    if (nstats < 2 || r == 0.0)
        return G_MAXDOUBLE;

    ifrom = (gint)floor(gwy_field_rtoi(field, y - r));
    ifrom = MAX(ifrom, 0);
    ito = (gint)ceil(gwy_field_rtoi(field, y + r));
    ito = MIN(ito, yres-1);

    jfrom = (gint)floor(gwy_field_rtoj(field, x - r));
    jfrom = MAX(jfrom, 0);
    jto = (gint)ceil(gwy_field_rtoj(field, x + r));
    jto = MIN(jto, xres-1);

    sum2 = g_new0(gdouble, 3*nstats);
    target = sum2 + 1;
    weight = target + 1;
    for (i = ifrom; i < ito; i++) {
        gdouble yy = (i + 0.5)*dy - y;
        for (j = jfrom; j <= jto; j++) {
            if (!nielded_included(m + i*xres + j, masking))
                continue;

            gdouble xx = (j + 0.5)*dx - x;
            gdouble v = d[i*xres + j];
            gdouble rr = sqrt(xx*xx + yy*yy)/h;
            gint kk = floor(rr);
            if (kk+1 >= nstats) {
                if (kk+1 == nstats) {
                    sum2[3*kk + 0] += v*v;
                    sum2[3*kk + 1] += v;
                    sum2[3*kk + 2] += 1.0;
                }
                continue;
            }

            rr -= kk;
            if (rr <= 0.5)
                rr = 2.0*rr*rr;
            else
                rr = 1.0 - 2.0*(1.0 - rr)*(1.0 - rr);

            sum2[3*kk + 0] += (1.0 - rr)*v*v;
            sum2[3*kk + 1] += (1.0 - rr)*v;
            sum2[3*kk + 2] += 1.0 - rr;
            sum2[3*kk + 3] += rr*v*v;
            sum2[3*kk + 4] += rr*v;
            sum2[3*kk + 5] += rr;
        }
    }

    mismatch = 0.0;
    for (k = 0; k < nstats; k++) {
        gdouble wk = weight[3*k];
        if (wk)
            mismatch += sum2[3*k]/wk - gwy_powi(target[3*k]/wk, 2);
    }

    g_free(sum2);

    return mismatch;
}

static gdouble
calculate_angular_mismatch(GwyField *dfield,
                           GwyNield *mask, GwyMaskingType masking,
                           const gdouble *line, gint lineres)
{
    gdouble xc, yc, r;

    xc = 0.5*(line[0] + line[2]) + dfield->xoff;
    yc = 0.5*(line[1] + line[3]) + dfield->yoff;
    r = 0.5*hypot(line[2] - line[0], line[3] - line[1]);

    return angular_average_mismatch(dfield, mask, masking, xc, yc, r, lineres);
}

static gboolean
optimize_profile_at_scale(GwyField *dfield,
                          GwyNield *mask,
                          GwyMaskingType masking,
                          gdouble r,
                          gdouble *line,
                          gint lineres,
                          gdouble *mismatch)
{
    enum { GRID_H = 3, GRID_N = 2*GRID_H + 1, GRID_NN = GRID_N*GRID_N };

    gdouble xreal = dfield->xreal, yreal = dfield->yreal;
    gint besti = 0, bestj = 0;
    gdouble dx = gwy_field_get_dx(dfield);
    gdouble dy = gwy_field_get_dy(dfield);
    gdouble allvar[GRID_NN];
    gdouble bestvar = G_MAXDOUBLE;

#ifdef _OPENMP
#pragma omp parallel if(gwy_threads_are_enabled()) default(none) \
            shared(allvar,line,dfield,mask,masking,r,xreal,yreal,lineres)
#endif
    {
        gint ijfrom = gwy_omp_chunk_start(GRID_NN);
        gint ijto = gwy_omp_chunk_end(GRID_NN);

        for (gint ij = ijfrom; ij < ijto; ij++) {
            gint i = ij/GRID_N - GRID_H, j = ij % GRID_N - GRID_H;
            gdouble offline[4] = {
                line[0] + j*r, line[1] + i*r, line[2] + j*r, line[3] + i*r,
            };

            allvar[ij] = G_MAXDOUBLE;
            if (i*i + j*j > 2*2 + 3*3)
                continue;

            if (offline[0] < 0.0 || offline[2] > xreal
                || offline[1] < 0.0 || offline[3] > yreal)
                continue;

            allvar[ij] = calculate_angular_mismatch(dfield, mask, masking, offline, lineres);
        }
    }

    for (gint ij = 0; ij < GRID_NN; ij++) {
        gint i = ij/GRID_N - GRID_H, j = ij % GRID_N - GRID_H;

        if (i*i + j*j <= 2*2 + 3*3 && allvar[ij] < bestvar) {
            besti = i;
            bestj = j;
            bestvar = allvar[ij];
        }
    }

    line[0] += bestj*r;
    line[1] += besti*r;
    line[2] += bestj*r;
    line[3] += besti*r;
    *mismatch = bestvar;

    gwy_debug("symmetrize at scale profiles %g: (%d,%d)", r, bestj, besti);
    return r <= 0.05 * 2*dx*dy/(dx + dy);
}

static void
symmetrize_profile(GwyToolRprofile *tool, gint id)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwyField *dfield = GWY_PLAIN_TOOL(tool)->field;
    GwyNield *mask = plain_tool->mask_field;
    GwyMaskingType masking = gwy_params_get_masking(tool->params, PARAM_MASKING, &mask);
    gdouble line_coarse[4], line_fine[4];
    gdouble r, dx, dy, h, mismatch_fine, mismatch_coarse;
    gint lineres;

    g_return_if_fail(plain_tool->selection);
    if (!gwy_selection_get_object(plain_tool->selection, id, line_fine))
        g_return_if_reached();
    gwy_assign(line_coarse, line_fine, G_N_ELEMENTS(line_fine));
    dx = gwy_field_get_dx(dfield);
    dy = gwy_field_get_dy(dfield);
    lineres = calculate_lineres(tool, line_fine);

    /* Don't attempt to optimise very short lines. It would end up in tears. */
    if (hypot((line_fine[2] - line_fine[0])/dx, (line_fine[3] - line_fine[1])/dy) < 4.0)
        return;
    h = hypot(line_fine[2] - line_fine[0], line_fine[3] - line_fine[1]);

    r = 0.07*h;
    while (!optimize_profile_at_scale(dfield, mask, masking, r, line_coarse, lineres, &mismatch_coarse))
        r *= 0.25;

    r = 0.015*h;
    while (!optimize_profile_at_scale(dfield, mask, masking, r, line_fine, lineres, &mismatch_fine))
        r *= 0.25;

    if (mismatch_fine <= 1.1*mismatch_coarse)
        gwy_selection_set_object(plain_tool->selection, id, line_fine);
    else
        gwy_selection_set_object(plain_tool->selection, id, line_coarse);
}

static void
render_cell(GtkCellLayout *layout,
            GtkCellRenderer *renderer,
            GtkTreeModel *model,
            GtkTreeIter *iter,
            gpointer user_data)
{
    GwyToolRprofile *tool = (GwyToolRprofile*)user_data;
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    guint id = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(layout), "id"));
    const GwyValueFormat *vf = tool->pixel_format;
    gchar buf[32];
    gdouble line[4];
    gdouble val;
    guint idx;

    gtk_tree_model_get(model, iter, 0, &idx, -1);
    if (id == COLUMN_I) {
        g_snprintf(buf, sizeof(buf), "%d", idx + 1);
        g_object_set(renderer, "text", buf, NULL);
        return;
    }

    plain_tool = GWY_PLAIN_TOOL(tool);
    gwy_selection_get_object(plain_tool->selection, idx, line);

    if (id == COLUMN_X1)
        val = floor(gwy_field_rtoj(plain_tool->field, line[0]));
    else if (id == COLUMN_Y1)
        val = floor(gwy_field_rtoi(plain_tool->field, line[1]));
    else if (id == COLUMN_X2)
        val = floor(gwy_field_rtoj(plain_tool->field, line[2]));
    else if (id == COLUMN_Y2)
        val = floor(gwy_field_rtoi(plain_tool->field, line[3]));
    else {
        g_return_if_reached();
    }

    if (vf)
        g_snprintf(buf, sizeof(buf), "%.*f", vf->precision, val/vf->magnitude);
    else
        g_snprintf(buf, sizeof(buf), "%.3g", val);

    g_object_set(renderer, "text", buf, NULL);
}

static void
render_color(G_GNUC_UNUSED GtkCellLayout *layout,
             GtkCellRenderer *renderer,
             GtkTreeModel *model,
             GtkTreeIter *iter,
             gpointer user_data)
{
    GwyToolRprofile *tool = (GwyToolRprofile*)user_data;
    GwyGraphCurveModel *gcmodel;
    GwyRGBA *rgba;
    guint idx;

    gtk_tree_model_get(model, iter, 0, &idx, -1);
    gcmodel = gwy_graph_model_get_curve(tool->gmodel, idx);
    g_object_get(gcmodel, "color", &rgba, NULL);
    g_object_set(renderer, "color", rgba, NULL);
    gwy_rgba_free(rgba);
}

static void
gwy_tool_rprofile_apply(GwyToolRprofile *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    gboolean separate = gwy_params_get_boolean(tool->params, PARAM_SEPARATE);
    GwyGraphCurveModel *gcmodel;
    GwyGraphModel *gmodel;
    gchar *s;

    g_return_if_fail(plain_tool->selection);
    gint n = gwy_selection_get_data(plain_tool->selection, NULL);
    g_return_if_fail(n);

    if ((gmodel = gwy_params_get_graph(tool->params, PARAM_TARGET_GRAPH))) {
        gwy_graph_model_append_curves(gmodel, tool->gmodel, 1);
        return;
    }

    if (!separate) {
        gmodel = gwy_graph_model_copy(tool->gmodel);
        g_object_set(gmodel, "label-visible", TRUE, NULL);
        gint newid = gwy_file_add_graph(GWY_FILE(plain_tool->container), gmodel);
        gwy_file_set_visible(GWY_FILE(plain_tool->container), GWY_FILE_GRAPH, newid, TRUE);
        g_object_unref(gmodel);
        return;
    }

    for (gint i = 0; i < n; i++) {
        gmodel = gwy_graph_model_new_alike(tool->gmodel);
        g_object_set(gmodel, "label-visible", TRUE, NULL);
        gcmodel = gwy_graph_model_get_curve(tool->gmodel, i);
        gcmodel = gwy_graph_curve_model_copy(gcmodel);

        gwy_graph_model_add_curve(gmodel, gcmodel);
        g_object_unref(gcmodel);
        g_object_get(gcmodel, "description", &s, NULL);
        g_object_set(gmodel, "title", s, NULL);
        g_free(s);
        gint newid = gwy_file_add_graph(GWY_FILE(plain_tool->container), gmodel);
        gwy_file_set_visible(GWY_FILE(plain_tool->container), GWY_FILE_GRAPH, newid, TRUE);
        g_object_unref(gmodel);
    }
}

/* 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 : */
