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

static gboolean    module_register(void);
static void        module_main    (GwyFile *data,
                                   GwyRunModeFlags mode);
static GwyScatter* pick_points    (GwyScatter *scatter);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Simple XYZ automated crop."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "2.0",
    "David Nečas (Yeti) & Petr Klapetek",
    "2023",
};

GWY_MODULE_QUERY2(module_info, xyz_autocrop)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("autocrop",
                          module_main,
                          N_("/Crop Automatically"),
                          GWY_ICON_FIX_ZERO,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Crop data automatically to cover scanned areas"));

    return TRUE;
}

static void
module_main(GwyFile *data, G_GNUC_UNUSED GwyRunModeFlags mode)
{
    GwyScatter *scatter = NULL;
    gint id;

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

    GQuark quark = gwy_file_key_xyz(id);
    gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &quark);

    GwyScatter *newscatter = pick_points(scatter);
    gint newid = gwy_file_add_xyz(data, newscatter);

    gwy_file_set_visible(data, GWY_FILE_XYZ, newid, TRUE);
    gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("Cropped"), 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(newscatter);
}

static gdouble
get_lpos(GwyLine *dline, gdouble value)
{
    const gdouble *linedata = gwy_line_get_data(dline);
    gint res = gwy_line_get_res(dline);

    for (gint i = 1; i < res; i++) {
        if (linedata[i] > value)
            return gwy_line_itor(dline, i-1) + gwy_line_get_offset(dline);
    }
    return gwy_line_itor(dline, gwy_line_get_res(dline)-1);
}

static gdouble
get_rpos(GwyLine *dline, gdouble value)
{
    const gdouble *linedata = gwy_line_get_data(dline);
    gint res = gwy_line_get_res(dline);

    for (gint i = 0; i < res-1; i++) {
        if (linedata[i] > value)
            return gwy_line_itor(dline, i+1) + gwy_line_get_offset(dline);
    }
    return gwy_line_itor(dline, gwy_line_get_res(dline)-1);
}

static GwyScatter*
pick_points(GwyScatter *scatter)
{
    gint xres = 500, yres = 500;
    gdouble xmin, xmax, ymin, ymax;

    gwy_scatter_xrange(scatter, &xmin, &xmax);
    gwy_scatter_yrange(scatter, &ymin, &ymax);

    GwyField *mapfield = gwy_field_new(xres, yres, xmax - xmin, ymax - ymin, FALSE);
    gwy_field_average_xy_z(mapfield, NULL, gwy_scatter_get_xy_const(scatter), NULL, gwy_scatter_get_n_points(scatter));

    GwyLine *xline = gwy_line_new(xres, xmax - xmin, FALSE);
    GwyLine *yline = gwy_line_new(yres, ymax - ymin, FALSE);

    gwy_field_line_stats(mapfield, xline, GWY_LINE_STAT_MEAN, GWY_ORIENTATION_VERTICAL);
    gwy_field_line_stats(mapfield, yline, GWY_LINE_STAT_MEAN, GWY_ORIENTATION_HORIZONTAL);
    g_object_unref(mapfield);

    gwy_line_set_offset(xline, xmin);
    gwy_line_set_offset(yline, ymin);
    gwy_line_set_real(xline, xmax - xmin);
    gwy_line_set_real(yline, ymax - ymin);

    gwy_line_cumulate(xline, FALSE);
    gwy_line_cumulate(yline, FALSE);
    gwy_line_multiply(xline, 1.0/gwy_line_get_val(xline, xres-1));
    gwy_line_multiply(yline, 1.0/gwy_line_get_val(yline, yres-1));

    gdouble xfrom = get_lpos(xline, 0.05);
    gdouble xto = get_rpos(xline, 0.95);

    gdouble yfrom = get_lpos(yline, 0.05);
    gdouble yto = get_rpos(yline, 0.95);

    g_object_unref(xline);
    g_object_unref(yline);

    return gwy_scatter_new_part(scatter, xfrom, xto, yfrom, yto);
}

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