/*
 *  $Id: xyz_split.c 30111 2026-06-22 11:02:00Z yeti-dn $
 *  Copyright (C) 2016-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 <gtk/gtk.h>
#include <gwy.h>

#define RUN_MODES (GWY_RUN_INTERACTIVE | GWY_RUN_IMMEDIATE)

enum {
    PARAM_METHOD,
};

typedef enum {
    XYZ_SPLIT_LR = 0,
    XYZ_SPLIT_UD = 1,
} XYZSplitType;

typedef struct {
    GwyParams *params;
    GwyScatter *scatter;
    GwyScatter *result_fw;
    GwyScatter *result_bw;
} ModuleArgs;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("XYZ data split based on direction."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "3.0",
    "Petr Klapetek",
    "2019",
};

GWY_MODULE_QUERY2(module_info, xyz_split)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_split",
                          module_main,
                          N_("/Split by Direction..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Split XYZ data based on direction"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static const GwyEnum methods[] = {
        { N_("Left-right"),      XYZ_SPLIT_LR, },
        { N_("Upward-downward"), XYZ_SPLIT_UD, },
    };
    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_gwyenum(paramdef, PARAM_METHOD, "method", _("Split direction"),
                              methods, G_N_ELEMENTS(methods), XYZ_SPLIT_LR);

    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    ModuleArgs args;
    gwy_clear1(args);

    gint id, newid;
    XYZSplitType method;

    g_return_if_fail(mode & RUN_MODES);

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

    args.params = gwy_params_new_from_settings(define_module_params());
    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_PROCEED)
        execute(&args);

    method = gwy_params_get_enum(args.params, PARAM_METHOD);

    newid = gwy_file_add_xyz(data, args.result_fw);

    gwy_file_set_visible(data, GWY_FILE_XYZ, newid, TRUE);
    if (method == XYZ_SPLIT_LR)
        gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Split right direction"), TRUE);
    else
        gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Split down direction"), 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_fw);

    newid = gwy_file_add_xyz(data, args.result_bw);

    gwy_file_set_visible(data, GWY_FILE_XYZ, newid, TRUE);
    if (method == XYZ_SPLIT_LR)
        gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Split left direction"), TRUE);
    else
        gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Split up direction"), 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_bw);

end:
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args)
{
    GwyDialog *dialog;
    GwyParamTable *table;

    dialog = GWY_DIALOG(gwy_dialog_new(_("Split XYZ Data")));
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    table = gwy_param_table_new(args->params);
    gwy_param_table_append_radio(table, PARAM_METHOD);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, TRUE, 0);

    return gwy_dialog_run(dialog);
}

static void
execute(ModuleArgs *args)
{
    XYZSplitType method = gwy_params_get_enum(args->params, PARAM_METHOD);
    GwyScatter *scatter = args->scatter;

    const GwyXY *xy = gwy_scatter_get_xy_const(scatter);
    gsize n = gwy_scatter_get_n_points(scatter);
    guint32 *fw_subset = g_new0(guint32, (n + 31)/32);
    guint32 *bw_subset = g_new0(guint32, (n + 31)/32);

    if (method == XYZ_SPLIT_LR) {
       for (gsize k = 0; k < n-1; k++) {
          if (xy[k+1].x > xy[k].x)
              fw_subset[k/32] |= (1u << (k % 32));
          if (xy[k+1].x < xy[k].x)
              bw_subset[k/32] |= (1u << (k % 32));
       }
    }
    else {
       for (gsize k = 0; k < n-1; k++) {
          if (xy[k+1].y > xy[k].y)
              fw_subset[k/32] |= (1u << (k % 32));
          if (xy[k+1].y < xy[k].y)
              bw_subset[k/32] |= (1u << (k % 32));
       }
    }

    args->result_fw = gwy_scatter_copy(scatter);
    gwy_scatter_reduce_to_subset(args->result_fw, fw_subset);
    g_free(fw_subset);

    args->result_bw = gwy_scatter_copy(scatter);
    gwy_scatter_reduce_to_subset(args->result_bw, bw_subset);
    g_free(bw_subset);
}

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