/*
 *  $Id: xyz_average.c 29828 2026-04-16 18:09:34Z 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_IMMEDIATE)

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

static gboolean module_register(void);
static void     module_main    (GwyFile *data,
                                GwyRunModeFlags mode);
static gboolean execute        (ModuleArgs *args,
                                GwyFile *data,
                                gint id);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Averages coinciding points in XYZ data."),
    "Yeti <yeti@gwyddion.net>",
    "3.0",
    "David Nečas (Yeti)",
    "2018",
};

GWY_MODULE_QUERY2(module_info, xyz_average)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_average",
                          module_main,
                          N_("/_Average Identical Positions"),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Average coinciding XYZ points"));

    return TRUE;
}

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

    ModuleArgs args;
    gwy_clear1(args);
    gint id;

    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));

    if (!execute(&args, data, id))
        return;

    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, _("Points averaged"), 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);
}

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;
    gsize n = gwy_scatter_get_n_points(scatter);

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

    gsize nnew = 0;
    guint nvalues = gwy_scatter_get_n_values(scatter);
    gdouble *merged = merge_coninciding_xyz(gwy_scatter_get_xy_const(scatter), gwy_scatter_get_data_const(scatter, 0),
                                            n, nvalues, &nnew);
    gwy_app_wait_finish();

    GwyScatter *result = args->result = gwy_scatter_new_alike(scatter);
    gwy_scatter_resize(result, nnew);
    GwyXY *xy = gwy_scatter_get_xy(result);
    gdouble *data = gwy_scatter_get_data(result, 0);
    guint nvxy = nvalues + 2;
    if (nnew < n) {
        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];
        }
    }
    g_free(merged);

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