#include "Config.h"

#ifdef ALLEGRO4
u8 locateConfigPath(const u8* filename, u8* configPath)
{
    u8 i = 0;
    u8 pathBuffer[260];

    // Initialise the path buffer used for storing the relative path.
    memset(pathBuffer, 0, 260);

    // Only going up the tree a limited number of times.
    for (i = 0; i < 6; ++i)
    {
        // Add the filename to the config path.
        append_filename(configPath, pathBuffer, filename, sizeof(pathBuffer));

        // Convert the relative path to a full path and fix any directory separators.
        canonicalize_filename(configPath, configPath, 260);

        // Check if the config path exists.
        if (exists(configPath))
        {
            // Successfully located config path.
            return 0;
        }
        else
        {
            // Move one level up the directory tree.
            append_filename(pathBuffer, pathBuffer, "../", sizeof(pathBuffer));
        }
    }

    // Failed to locate config path.
    return -1;
}

#elif ALLEGRO5

ALLEGRO_PATH* locateConfigPath(const char* filename)
{
    // Start from the current directory and assume that the config file is in this directory.
    ALLEGRO_PATH* directory = al_create_path(al_get_current_directory());
    al_set_path_filename(directory, filename);

    // Make sure that the directory is still valid.
    while (al_get_path_num_components(directory) > 0)
    {
        // Check if the config file exists in the directory.
        if (al_filename_exists(al_path_cstr(directory, '/')))
        {
            return directory;
        }
        else
        {
            // Remove the part of the directory before the filename.
            al_remove_path_component(directory, -1);
        }
    }

    // Cleanup the directory created.
    al_destroy_path(directory);

    // Return NULL as the filename does not exist.
    return NULL;
}
#endif

#ifndef CPC
u8 calculateScaleFactor(u16 screenWidth, u16 screenHeight)
{
    // The scale factor is the amount that the sprite width can be multiplied by (in multiples of 16).
    // 320x200 = 16->16
    // 640x400 = 16->32
    // 960x600 = 16->48
    // 1280x800 = 16->64
    // 1600x1000 = 16->80
    // 1920x1200 = 16->96
    u8 xScaleFactor = screenWidth / 320;
    u8 yScaleFactor = screenHeight / 200;

    if (xScaleFactor > yScaleFactor)
    {
        return yScaleFactor;
    }
    else
    {
        return xScaleFactor;
    }
}
#endif
