#include "dynamic_libs.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

RT_DLLEXPORT rt_dynlib rtOpenCallerLib(void) {
    return (rt_dynlib)GetModuleHandleW(NULL);
}

RT_DLLEXPORT rt_dynlib rtOpenLib(const char *libname) {
    wchar_t libname_w[MAX_PATH];
    MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, libname, -1, libname_w, MAX_PATH);
    HMODULE mod = LoadLibraryW(libname_w);
    return (rt_dynlib)mod;
}

RT_DLLEXPORT void *rtGetSymbol(rt_dynlib lib, const char *symbol) {
    return (void *)GetProcAddress((HMODULE)lib, symbol);
}

RT_DLLEXPORT void rtCloseLib(rt_dynlib lib) {
    FreeLibrary((HMODULE)lib);
}

#elif defined(__linux__)
#include <dlfcn.h>

RT_DLLEXPORT rt_dynlib rtOpenCallerLib(void) {
    return dlopen(NULL, RTLD_NOW | RTLD_LOCAL);
}

RT_DLLEXPORT rt_dynlib rtOpenLib(const char *libname) {
    return dlopen(libname, RTLD_NOW | RTLD_LOCAL);
}

RT_DLLEXPORT void *rtGetSymbol(rt_dynlib lib, const char *symbol) {
    return dlsym(lib, symbol);
}

RT_DLLEXPORT void rtCloseLib(rt_dynlib lib) {
    dlclose(lib);
}

#endif
