/*
 *  $Id: volume_stepline.c 29425 2026-02-02 10:08:27Z yeti-dn $
 *  Copyright (C) 2018 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 <gtk/gtk.h>
#include <gwy.h>
#include "libgwyddion/omp.h"

#define RUN_MODES (GWY_RUN_IMMEDIATE)

static gboolean module_register  (void);
static void     module_main      (GwyFile *data,
                                  GwyRunModeFlags mode);
static void     brick_level      (GwyBrick *brick);
static void     step_line_correct(GwyField *field);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Performs step line correction"),
    "Yeti <yeti@gwyddion.net>, Luke Somers <lsomers@sas.upenn.edu>, Petr Klapetek <klapetek@gwyddion.net>",
    "1.0",
    "David Nečas (Yeti) & Petr Klapetek & Luke Somers",
    "2023",
};

GWY_MODULE_QUERY2(module_info, volume_stepline)

static gboolean
module_register(void)
{
    gwy_volume_func_register("volume_stepline",
                             module_main,
                             N_("/_Correct Data/Ste_p Line Correction"),
                             NULL,
                             RUN_MODES,
                             GWY_MENU_FLAG_VOLUME,
                             N_("Step line correction in all XY planes"));

    return TRUE;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    GwyBrick *brick = NULL;
    gint id, newid;

    g_return_if_fail(mode & RUN_MODES);

    gwy_data_browser_get_current(GWY_APP_BRICK, &brick,
                                 GWY_APP_BRICK_ID, &id,
                                 0);
    g_return_if_fail(GWY_IS_BRICK(brick));

    brick = gwy_brick_copy(brick);
    gwy_app_wait_start(gwy_data_browser_get_window_for_data(data, GWY_FILE_VOLUME, id), _("Step line correction..."));
    brick_level(brick);
    gwy_app_wait_finish();
    newid = gwy_file_add_volume(data, brick, NULL);
    gwy_file_set_visible(data, GWY_FILE_VOLUME, newid, TRUE);
    gwy_file_set_title(data, GWY_FILE_VOLUME, newid, _("Step line corrected"), TRUE);
    g_object_unref(brick);
    gwy_file_sync_items(data, GWY_FILE_VOLUME, id,
                        data, GWY_FILE_VOLUME, newid,
                        GWY_FILE_ITEM_PALETTE, FALSE);
    gwy_log_add(data, GWY_FILE_VOLUME, id, newid);
}

static void
brick_level(GwyBrick *brick)
{
    gint xres = gwy_brick_get_xres(brick);
    gint yres = gwy_brick_get_yres(brick);
    gint zres = gwy_brick_get_zres(brick);

#ifdef _OPENMP
#pragma omp parallel if(gwy_threads_are_enabled()) default(none) \
            shared(brick,xres,yres,zres)
#endif
    {
        GwyField *field = gwy_field_new(xres, yres, xres, yres, FALSE);
        gint k;
        gint kfrom = gwy_omp_chunk_start(zres), kto = gwy_omp_chunk_end(zres);
        for (k = kfrom; k < kto; k++) {
            gwy_brick_extract_xy_plane(brick, field, k);
            step_line_correct(field);
            gwy_brick_set_xy_plane(brick, field, k);
        }

        g_object_unref(field);
    }
}

static void
calculate_segment_correction(const gdouble *drow,
                             gdouble *output,
                             gint xres,
                             gint len)
{
    const gint min_len = 4;

    if (len >= min_len) {
        gdouble corr = 0.0;
        for (gint j = 0; j < len; j++)
            corr += (drow[j] + drow[2*xres + j])/2.0 - drow[xres + j];
        corr /= len;
        for (gint j = 0; j < len; j++)
            output[j] = (3*corr + (drow[j] + drow[2*xres + j])/2.0 - drow[xres + j])/4.0;
    }
    /* output is expected to be zero-initialised. */
}

static void
line_correct_step_iter(GwyField *field,
                       GwyField *tmp)
{
    const gdouble threshold = 3.0;

    gwy_field_clear(tmp);
    gint yres = gwy_field_get_yres(field), xres = gwy_field_get_xres(field);
    const gdouble *d = gwy_field_get_data_const(field);
    gdouble *b = gwy_field_get_data(tmp);

    gdouble w = 0.0;
    for (gint i = 0; i < yres-1; i++) {
        const gdouble *drow = d + i*xres;
        for (gint j = 0; j < xres; j++) {
            gdouble v = drow[j + xres] - drow[j];
            w += v*v;
        }
    }
    w = w/(yres-1)/xres;

    gint *mrow = g_new(gint, xres);
    for (gint i = 0; i < yres-2; i++) {
        const gdouble *drow = d + i*xres;
        gdouble *brow = b + i*xres;
        gwy_clear(mrow, xres);

        for (gint j = 0; j < xres; j++) {
            gdouble u = drow[xres + j];
            gdouble v = (u - drow[j])*(u - drow[j + 2*xres]);
            if (G_UNLIKELY(v > threshold*w)) {
                if (2*u - drow[j] - drow[j + 2*xres] > 0)
                    mrow[j] = 1;
                else
                    mrow[j] = -1;
            }
        }

        gint len = 1, j;
        for (j = 1; j < xres; j++) {
            if (mrow[j] == mrow[j-1])
                len++;
            else {
                if (mrow[j-1])
                    calculate_segment_correction(drow + j-len, brow + j-len, xres, len);
                len = 1;
            }
        }
        if (mrow[j-1])
            calculate_segment_correction(drow + j-len, brow + j-len, xres, len);
    }

    gwy_field_sum_fields(field, field, tmp);
}

static void
step_line_correct(GwyField *field)
{
    gdouble avg = gwy_field_mean(field);
    GwyLine *shifts = gwy_field_find_row_shifts_trimmed_mean(field, NULL, GWY_MASK_IGNORE, 0.5, 0);
    gwy_field_subtract_row_shifts(field, shifts);
    g_object_unref(shifts);

    GwyField *tmp = gwy_field_new_alike(field, TRUE);
    line_correct_step_iter(field, tmp);
    line_correct_step_iter(field, tmp);
    g_object_unref(tmp);

    gwy_field_filter_conservative(field, 5);
    gwy_field_add(field, avg - gwy_field_mean(field));
    gwy_field_data_changed(field);
}

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