/*
 *  $Id: xyz_merge.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2019-2026 David Necas (Yeti).
 *
 *  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 <stdlib.h>
#include <gtk/gtk.h>
#include <gwy.h>

#define RUN_MODES (GWY_RUN_INTERACTIVE | GWY_RUN_IMMEDIATE)

enum {
    PARAM_DO_AVERAGE,
    PARAM_OTHER_SCATTER,
};

typedef struct {
    GwyParams *params;
    GwyScatter *scatter;
    GwyScatter *result;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static GwyDialogOutcome run_gui             (ModuleArgs *arg);
static gboolean         merge_data_filter   (GwyFile *data,
                                             gint id,
                                             gpointer user_data);
static gboolean         execute             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Elementary XYZ data operations."),
    "Yeti <yeti@gwyddion.net>",
    "2.0",
    "David Nečas (Yeti)",
    "2018",
};

GWY_MODULE_QUERY2(module_info, xyz_merge)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_merge",
                          module_main,
                          N_("/_Merge..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Merge two XYZ point sets"));

    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, gwy_xyz_func_current());
    gwy_param_def_add_xyz_id(paramdef, PARAM_OTHER_SCATTER, "op2", _("Second _XYZ data"));
    gwy_param_def_add_boolean(paramdef, PARAM_DO_AVERAGE, "do_average", _("_Average coincident points"), TRUE);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    g_return_if_fail(mode & RUN_MODES);

    ModuleArgs args;
    gint id;
    gwy_clear1(args);

    args.params = gwy_params_new_from_settings(define_module_params());

    gwy_data_browser_get_current(GWY_APP_SCATTER, &args.scatter,
                                 GWY_APP_SCATTER_ID, &id,
                                 0);
    g_return_if_fail(GWY_IS_SCATTER(args.scatter));

    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    if (outcome != GWY_DIALOG_HAVE_RESULT) {
        if (!execute(&args, data, id))
            goto end;
    }

    gint newid = gwy_file_add_xyz(data, args.result);

    gwy_file_set_visible(data, GWY_FILE_XYZ, newid, TRUE);
    gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Merged"), TRUE);
    gwy_file_sync_items(data, GWY_FILE_XYZ, id,
                        data, GWY_FILE_XYZ, newid,
                        GWY_FILE_ITEM_PALETTE, FALSE);
    gwy_log_add(data, GWY_FILE_XYZ, id, newid);

    g_object_unref(args.result);

end:
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args)
{
    ModuleGUI gui;
    gwy_clear1(gui);
    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Merge XYZ Data"));
    GwyDialog *dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    GwyParamTable *table = gui.table = gwy_param_table_new(args->params);
    gwy_param_table_append_xyz_id(table, PARAM_OTHER_SCATTER);
    gwy_param_table_data_id_set_filter(table, PARAM_OTHER_SCATTER, merge_data_filter, &gui, NULL);
    gwy_param_table_append_checkbox(table, PARAM_DO_AVERAGE);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), TRUE, TRUE, 0);

    return gwy_dialog_run(dialog);
}

static gboolean
merge_data_filter(GwyFile *data, gint id, gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;
    GwyScatter *scatter = gui->args->scatter;
    GwyScatter *otherscatter = gwy_file_get_xyz(data, id);

    if (otherscatter == scatter)
        return FALSE;

    return !gwy_scatter_is_incompatible(otherscatter, scatter,
                                        GWY_DATA_MISMATCH_LATERAL | GWY_DATA_MISMATCH_VALUE);
}

static int
compare_xy(gconstpointer a, gconstpointer b)
{
    return memcmp(a, b, sizeof(GwyXY));
}

static void
merge_points(gdouble *xyz, gsize len, gdouble *target, guint nvxy)
{
    if (target != xyz)
        gwy_assign(target, xyz, nvxy);
    if (len == 1)
        return;

    for (gsize j = 1; j < len; j++) {
        xyz += nvxy;
        for (guint k = 2; k < nvxy; k++)
            target[k] += xyz[k];
    }
    for (guint k = 2; k < nvxy; k++)
        target[k] /= len;
}

/* Merge exact matches.  We do not promise anything cleverer. */
static gdouble*
merge_coninciding_xyz(const GwyXY *xy, const gdouble *data, gsize n, gint nvalues, gsize *nnew)
{
    guint nvxy = nvalues + 2;
    gdouble *sorted = g_new(gdouble, n*nvxy);
    for (gsize i = 0; i < n; i++) {
        gdouble *xyz = sorted + i*nvxy;
        xyz[0] = xy[i].x;
        xyz[1] = xy[i].y;
        for (guint k = 0; k < nvalues; k++)
            xyz[2+k] = data[k*n + i];
    }
    qsort(sorted, n, nvxy*sizeof(gdouble), compare_xy);

    gsize pos = 0, bstart = 0;
    for (gsize i = 1; i < n; i++) {
        gdouble *xyz = sorted + i*nvxy, *xyzbstart = sorted + bstart*nvxy;
        if (xyz[0] != xyzbstart[0] || xyz[1] != xyzbstart[1]) {
            merge_points(xyzbstart, i-bstart, sorted + pos*nvxy, nvxy);
            bstart = i;
            pos++;
        }
    }
    merge_points(sorted + bstart*nvxy, n-bstart, sorted + pos*nvxy, nvxy);
    pos++;

    *nnew = pos;
    return sorted;
}

static gboolean
execute(ModuleArgs *args, GwyFile *file, gint id)
{
    GwyScatter *scatter = args->scatter;
    GwyScatter *scatter2 = gwy_params_get_xyz(args->params, PARAM_OTHER_SCATTER);
    if (!scatter2)
        return FALSE;

    GtkWindow *window = gwy_data_browser_get_window_for_data(file, GWY_FILE_XYZ, id);
    gwy_app_wait_cursor_start(window);

    gboolean do_average = gwy_params_get_boolean(args->params, PARAM_DO_AVERAGE);
    GwyScatter *result = args->result = gwy_scatter_new_alike(scatter);
    gsize n1 = gwy_scatter_get_n_points(scatter);
    gsize n2 = gwy_scatter_get_n_points(scatter2);
    gsize n12 = n1 + n2;
    gint nvalues = gwy_scatter_get_n_values(scatter);
    gwy_scatter_resize(result, n12);
    GwyXY *xy = gwy_scatter_get_xy(result);
    gwy_assign(xy, gwy_scatter_get_xy_const(scatter), n1);
    gwy_assign(xy + n1, gwy_scatter_get_xy_const(scatter2), n2);
    gdouble *data = gwy_scatter_get_data(result, 0);
    for (gint i = 0; i < nvalues; i++) {
        gwy_assign(data + n12*i, gwy_scatter_get_data_const(scatter, i), n1);
        gwy_assign(data + n12*i + n1, gwy_scatter_get_data_const(scatter2, i), n2);
    }

    if (do_average) {
        gsize nnew;
        gdouble *merged = merge_coninciding_xyz(xy, data, n12, nvalues, &nnew);
        guint nvxy = nvalues + 2;
        if (nnew < n12) {
            for (gsize i = 0; i < nnew; i++) {
                gdouble *xyz = merged + i*nvxy;
                xy[i].x = xyz[0];
                xy[i].y = xyz[1];
                for (guint k = 0; k < nvalues; k++)
                    data[k*nnew + i] = xyz[2+k];
            }
            gwy_scatter_resize(result, nnew);
        }
        g_free(merged);
    }

    gwy_app_wait_finish();

    return TRUE;
}

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