/*
 *  $Id: level.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 <string.h>
#include <gtk/gtk.h>
#include <gwy.h>

#define RUN_MODES (GWY_RUN_IMMEDIATE | GWY_RUN_INTERACTIVE)

enum {
    PARAM_MASKING,
};

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static GwyDialogOutcome run_gui             (GwyParams *params,
                                             const gchar *funcname);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Levels data by simple plane subtraction or by rotation, and fixes minimal or mean value to zero."),
    "Yeti <yeti@gwyddion.net>",
    "3.2",
    "David Nečas (Yeti) & Petr Klapetek",
    "2003",
};

GWY_MODULE_QUERY2(module_info, level)

static gboolean
module_register(void)
{
    gwy_image_func_register("level",
                            module_main,
                            N_("/_Level/Plane _Level"),
                            GWY_ICON_LEVEL,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Level data by mean plane subtraction"));
    gwy_image_func_register("level_rotate",
                            module_main,
                            N_("/_Level/Level _Rotate"),
                            NULL,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Automatically level data by plane rotation"));
    gwy_image_func_register("fix_zero",
                            module_main,
                            N_("/_Level/Fix _Zero"),
                            GWY_ICON_FIX_ZERO,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Shift minimum data value to zero"));
    gwy_image_func_register("zero_mean",
                            module_main,
                            N_("/_Level/Zero _Mean Value"),
                            GWY_ICON_ZERO_MEAN,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Shift mean data value to zero"));
    gwy_image_func_register("zero_max",
                            module_main,
                            N_("/_Level/Zero Ma_ximum Value"),
                            GWY_ICON_ZERO_MAXIMUM,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Shift maximum data value to zero"));

    return TRUE;
}

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

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_add_enum(paramdef, PARAM_MASKING, "mode", NULL, GWY_TYPE_MASKING_TYPE, GWY_MASK_EXCLUDE);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    const gchar *funcname = gwy_image_func_current();
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    GwyMaskingType masking;
    GwyParams *params;
    GwyField *dfield;
    GwyNield *mask;
    gdouble c, bx, by;
    gint xres, yres;
    GQuark quark;
    gint id;

    g_return_if_fail(mode & RUN_MODES);
    gwy_data_browser_get_current(GWY_APP_FIELD_KEY, &quark,
                                 GWY_APP_FIELD, &dfield,
                                 GWY_APP_FIELD_ID, &id,
                                 GWY_APP_MASK_FIELD, &mask,
                                 0);
    g_return_if_fail(dfield && quark);

    /* We have multiple functions with the same set of parameters. */
    gwy_param_def_set_function_name(define_module_params(), funcname);
    params = gwy_params_new_from_settings(define_module_params());
    if (mode != GWY_RUN_IMMEDIATE && mask) {
        outcome = run_gui(params, funcname);
        gwy_params_save_to_settings(params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    masking = gwy_params_get_masking(params, PARAM_MASKING, &mask);

    xres = gwy_field_get_xres(dfield);
    yres = gwy_field_get_yres(dfield);

    gwy_app_undo_qcheckpoint(GWY_DICT(data), quark, NULL);

    if (gwy_stramong(funcname, "level", "level_rotate", NULL)) {
        gwy_field_area_fit_plane(dfield, mask, masking, 0, 0, xres, yres, &c, &bx, &by);
        if (gwy_strequal(funcname, "level_rotate")) {
            bx = gwy_field_rtoj(dfield, bx);
            by = gwy_field_rtoi(dfield, by);
            gwy_field_plane_rotate(dfield, atan2(bx, 1), atan2(by, 1), GWY_INTERPOLATION_LINEAR);
            gwy_debug("b = %g, alpha = %g deg, c = %g, beta = %g deg",
                      bx, gwy_rad2deg(atan2(bx, 1)), by, gwy_rad2deg(atan2(by, 1)));
        }
        else {
            c = -0.5*(bx*gwy_field_get_xres(dfield) + by*gwy_field_get_yres(dfield));
            gwy_field_plane_level(dfield, c, bx, by);
        }
    }
    else if (gwy_strequal(funcname, "fix_zero")) {
        gwy_field_add(dfield, -gwy_field_area_min(dfield, mask, masking, 0, 0, xres, yres));
    }
    else if (gwy_strequal(funcname, "zero_mean")) {
        gwy_field_add(dfield, -gwy_field_area_mean(dfield, mask, masking, 0, 0, xres, yres));
    }
    else if (gwy_strequal(funcname, "zero_max")) {
        gwy_field_add(dfield, -gwy_field_area_max(dfield, mask, masking, 0, 0, xres, yres));
    }
    else {
        g_assert_not_reached();
    }

    gwy_log_add(data, GWY_FILE_IMAGE, id, id);
    gwy_field_data_changed(dfield);

end:
    g_object_unref(params);
}

static GwyDialogOutcome
run_gui(GwyParams *params, const gchar *funcname)
{
    const gchar *title = NULL;
    GwyDialog *dialog;
    GwyParamTable *table;

    if (gwy_strequal(funcname, "level"))
        title = _("Plane Level");
    else if (gwy_strequal(funcname, "level_rotate"))
        title = _("Level Rotate");
    else if (gwy_strequal(funcname, "fix_zero"))
        title = _("Fix Zero");
    else if (gwy_strequal(funcname, "zero_mean"))
        title = _("Zero Mean Value");
    else if (gwy_strequal(funcname, "zero_max"))
        title = _("Zero Maximum Value");
    else {
        g_assert_not_reached();
    }

    dialog = GWY_DIALOG(gwy_dialog_new(title));
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);
    table = gwy_param_table_new(params);
    gwy_param_table_append_radio(table, PARAM_MASKING);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, FALSE, 0);

    return gwy_dialog_run(dialog);
}

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