
#include <stdio.h>
#ifndef WIN32
#include <dlfcn.h>
#endif

#include "gsys/cfc.h"
#include "sic-message-c.h"

#define gpack_sic_import CFC_EXPORT_NAME(gpack_sic_import)
#define gmaster_import CFC_EXPORT_NAME( gmaster_import)
void CFC_API gmaster_import( );

#define GAG_MAX_PACK_NAME_LENGTH 256

void gpack_c_import( void (*fct)( ), int debug, int *error)
{
    gmaster_import( fct, &debug, error);
}

void CFC_API gpack_sic_import( const CFC_FString package_name, int* debug, int* error
                       CFC_DECLARE_STRING_LENGTH(package_name))
{
    char name[GAG_MAX_PACK_NAME_LENGTH];
    char lib_name[GAG_MAX_PACK_NAME_LENGTH];
    char fct_name[GAG_MAX_PACK_NAME_LENGTH];

    CFC_f2c_strcpy( name, package_name, CFC_STRING_LENGTH_MIN( package_name,
     GAG_MAX_PACK_NAME_LENGTH));

    strcpy( fct_name, name);
    strcat( fct_name, "_sic_import");

    {
        void (*fct)( int, int*);
#ifndef WIN32
        void *lib;

        strcpy( lib_name, "lib");
        strcat( lib_name, name);
#ifndef darwin
        strcat( lib_name, ".so");
#else
        strcat( lib_name, ".so");
#endif
        lib = dlopen( lib_name, RTLD_NOW);
        if (lib == NULL) {
            sic_c_message(seve_e, "IMPORT", "Unknown package %s",name);
            *error = 1;
            return;
        }
        fct = dlsym( lib, fct_name);
#else /* WIN32 */
        HINSTANCE dll;

        strcpy( lib_name, name);
        strcat( lib_name, ".dll");
        dll = LoadLibrary( lib_name);
        if (dll == NULL) {
            sic_c_message(seve_e, "IMPORT", "Unknown package %s",name);
            *error = 1;
            return;
        }
        fct = (void (*)( int, int*))GetProcAddress( dll, fct_name);
#endif /* WIN32 */
        if (fct == NULL) {
            sic_c_message(seve_e, "IMPORT", "%s is not an importable package",name);
            *error = 1;
            return;
        }
        fct( *debug, error);
    }
}

