/*
 *  $Id: pltfile.c 28789 2025-11-04 17:14:03Z yeti-dn $
 *  Copyright (C) 2009-2025 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.
 */

/**
 * [FILE-MAGIC-FREEDESKTOP]
 * <mime-type type="application/x-nanosurf-plt-spm">
 *   <comment>Nanosurf PLT data</comment>
 *   <magic priority="80">
 *     <match type="string" offset="0" value="#Channel: ">
 *       <match type="string" offset="12:32" value="#Frame  :"/>
 *     </match>
 *   </magic>
 *   <glob pattern="*.plt"/>
 *   <glob pattern="*.PLT"/>
 * </mime-type>
 **/

/**
 * [FILE-MAGIC-FILEMAGIC]
 * # Nanosurf PLT
 * # Must look for some header strings, the entire file is text
 * 0 string \x23Channel:\x20
 * >&0 search/40 \x23Frame\x20\x20:\x20 Nanosurf PLT SPM text data
 **/

/**
 * [FILE-MAGIC-USERGUIDE]
 * Nanosurf PLT
 * .plt
 * Read
 **/

#include "config.h"
#include <glib/gi18n-lib.h>
#include <string.h>
#include <stdlib.h>
#include <gwy.h>

#include "err.h"

#define MAGIC1 "#Channel:"
#define MAGIC2 "#Frame  :"
#define MAGIC3 "#Lines  :"
#define MAGIC4 "#Points :"
#define EXTENSION ".plt"

static gboolean module_register(void);
static gint     detect_file    (const GwyFileDetectInfo *fileinfo,
                                gboolean only_name);
static GwyFile* load_file      (const gchar *filename,
                                GwyRunModeFlags mode,
                                GError **error);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Imports Nanosurf PLT files."),
    "Yeti <yeti@gwyddion.net>",
    "0.3",
    "David Nečas (Yeti)",
    "2009",
};

GWY_MODULE_QUERY2(module_info, pltfile)

static gboolean
module_register(void)
{
    gwy_file_func_register("pltfile",
                           N_("Nanosurf PLT files (.plt)"),
                           detect_file, load_file, NULL, NULL);

    return TRUE;
}

static gint
detect_file(const GwyFileDetectInfo *fileinfo, gboolean only_name)
{
    if (only_name)
        return g_str_has_suffix(fileinfo->name_lowercase, EXTENSION) ? 10 : 0;

    if (strncmp(fileinfo->head, MAGIC1, sizeof(MAGIC1)-1) == 0
        && strstr(fileinfo->head, MAGIC2)
        && strstr(fileinfo->head, MAGIC3)
        && strstr(fileinfo->head, MAGIC4))
        return 90;

    return 0;
}

static GwyFile*
load_file(const gchar *filename,
          G_GNUC_UNUSED GwyRunModeFlags mode,
          GError **error)
{
    GwyFile *file = NULL;
    GwyField *dfield = NULL;
    GwyTextHeaderParser parser;
    gchar *xunit, *yunit, *zunit;
    gchar *p, *value, *buffer = NULL;
    GHashTable *hash = NULL;
    gsize size;
    GError *err = NULL;
    gdouble xreal, yreal;
    G_GNUC_UNUSED gdouble zreal;
    gint xres, yres;

    if (!g_file_get_contents(filename, &buffer, &size, &err)) {
        err_GET_FILE_CONTENTS(error, &err);
        goto fail;
    }

    if (strncmp(buffer, MAGIC1, MIN(size, sizeof(MAGIC1)-1))) {
        err_FILE_TYPE(error, "Nanosurf PLT");
        goto fail;
    }

    /* Find the first line not starting with '#' */
    for (p = buffer; (p - buffer) + 1 < size; p++) {
        if ((p[0] == '\n' || p[0] == '\r') && (p[1] != '\n' && p[1] != '#')) {
            break;
        }
    }
    *p = '\0';
    p++;

    gwy_clear1(parser);
    parser.line_prefix = "#";
    parser.key_value_separator = ":";
    hash = gwy_text_header_parse(buffer, &parser, NULL, NULL);
    if (!require_keys(hash, error, "Channel", "Lines", "Points", "XRange", "YRange", "ZRange", NULL))
        goto fail;

    xres = atoi(g_hash_table_lookup(hash, "Points"));
    yres = atoi(g_hash_table_lookup(hash, "Lines"));
    if (err_DIMENSION(error, xres) || err_DIMENSION(error, yres))
        goto fail;

    xreal = g_ascii_strtod(g_hash_table_lookup(hash, "XRange"), &xunit);
    sanitise_real_size(&xreal, "x size");
    yreal = g_ascii_strtod(g_hash_table_lookup(hash, "YRange"), &yunit);
    sanitise_real_size(&yreal, "y size");
    zreal = g_ascii_strtod(g_hash_table_lookup(hash, "ZRange"), &zunit);

    dfield = gwy_field_new(xres, yres, xreal, yreal, FALSE);
    gwy_unit_set_from_string(gwy_field_get_unit_xy(dfield), xunit);
    gwy_unit_set_from_string(gwy_field_get_unit_z(dfield), zunit);
    if (!gwy_unit_equal_string(gwy_field_get_unit_xy(dfield), yunit))
        g_warning("X and Y units differ, using X");

    if (!gwy_parse_doubles(p, gwy_field_get_data(dfield), GWY_PARSE_DOUBLES_FREE_FORM, &yres, &xres, &p, &err)) {
        err_PARSE_DOUBLES(error, &err);
        g_object_unref(dfield);
        goto fail;
    }

    file = gwy_file_new_in_construction();
    gwy_file_pass_image(file, 0, dfield);

    if ((value = g_hash_table_lookup(hash, "Channel")))
        gwy_file_set_title(file, GWY_FILE_IMAGE, 0, value, FALSE);
    else
        gwy_image_title_fall_back(file, 0);

    gwy_log_add_import(file, GWY_FILE_IMAGE, 0, NULL, filename);

fail:
    g_free(buffer);
    g_hash_table_destroy(hash);

    return file;
}

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