//
// Copyright(C) 2005-2014 Simon Howard
// Copyright(C) 2014 Fabian Greffrath
// Copyright(C) 2025 Guilherme Miranda
//
// 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.
//
//
// Parses INCLUDE directives in BEX files
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "deh_io.h"
#include "deh_main.h"
#include "m_misc.h"

static boolean bex_nested = false;

static int DEH_BEXIncludeStart(deh_context_t *context, char *line)
{
    extern boolean bex_notext;

    if (!DEH_FileName(context))
    {
        DEH_Warning(context, "DEHACKED lumps may not include files");
        return -1;
    }

    if (bex_nested)
    {
        DEH_Warning(context, "Included files may not include other files");
        return -1;
    }

    char *inc_file = malloc(strlen(line) + 1);

    if (sscanf(line, "INCLUDE NOTEXT %32s", inc_file) == 1)
    {
        bex_notext = true;
    }
    else if (sscanf(line, "INCLUDE %32s", inc_file) == 1)
    {
        // well, fine
    }
    else
    {
        DEH_Warning(context, "Parse error on section start");
        free(inc_file);
        return -1;
    }

    // first, try loading the file right away
    char *try_path = inc_file;
    char *deh_file = DEH_FileName(context);
    if (!M_FileExistsNotDir(try_path))
    {
        // second, try loading the file in the directory of the current file
        char *dir = M_DirName(deh_file);
        try_path = M_StringJoin(dir, DIR_SEPARATOR_S, inc_file);
        free(dir);
    }

    bex_nested = true;

    if (!M_FileExistsNotDir(try_path) || !DEH_LoadFile(try_path))
    {
        DEH_Warning(context, "Could not include \"%s\"", inc_file);
    }

    bex_nested = false;
    bex_notext = false;

    if (try_path != inc_file)
    {
        free(try_path);
    }
    free(inc_file);

    return 0;
}

static void DEH_BEXIncludeParseLine(deh_context_t *context, char *line, int tag)
{
    // not used
}

deh_section_t deh_section_bex_includes =
{
    "INCLUDE",
    NULL,
    DEH_BEXIncludeStart,
    DEH_BEXIncludeParseLine,
    NULL,
    NULL,
};
