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

#include "UT_Compat.h"

#if defined (WIN32)
    #include <windows.h>
#endif

#include "UT_Error.h"
#include "UT_Vector.h"
#include "UT_Memory.h"

#include <tcl.h>
#include <tk.h>
#include "UTT_TclIf.h"
#include "UTT_SwatchTclIf.h"
#include "UTT_VecTclIf.h"
#include "IPT_TclIf.h"

/* We need at least the Tcl_Obj interface that was started in 8.0 */
#if TCL_MAJOR_VERSION < 8
    #error "we need Tcl 8.0 or greater to build this"

/* Check for Stubs compatibility when asked for it. */
#elif defined(USE_TCL_STUBS) && TCL_MAJOR_VERSION == 8 && \
	(TCL_MINOR_VERSION == 0 || \
        (TCL_MINOR_VERSION == 1 && TCL_RELEASE_LEVEL != TCL_FINAL_RELEASE))
    #error "Stubs interface doesn't work in 8.0 and alpha/beta 8.1; only 8.1.0+"
#endif

#ifdef _MSC_VER
    /* Only do this when MSVC++ is compiling us. */
    #ifdef USE_TCL_STUBS
	/* Mark this .obj as needing tcl's Stubs library. */
	#pragma comment(lib, "tclstub" \
	    STRINGIFY(JOIN(TCL_MAJOR_VERSION,TCL_MINOR_VERSION)) ".lib")
	#if !defined(_MT) || !defined(_DLL) || defined(_DEBUG)
	    /* This fixes a bug with how the Stubs library was compiled.
	     * The requirement for msvcrt.lib from tclstubXX.lib should
	     * be removed.
	     */
	    #pragma comment(linker, "-nodefaultlib:msvcrt.lib")
	#endif
    #else
	/* Mark this .obj needing the import library */
	#pragma comment(lib, "tcl" \
	    STRINGIFY(JOIN(TCL_MAJOR_VERSION,TCL_MINOR_VERSION)) ".lib")
    #endif
#endif

/* #define DEBUG_LOCAL */

static int initMyLibs (Tcl_Interp *interp)
{
    if (UTT_InitTclLib (interp) == TCL_ERROR) {
	printf ("Error initializing TclLib\n");
	return TCL_ERROR;
    }

    if (UTT_InitTclSwatchLib (interp) == TCL_ERROR) {
	printf ("Error initializing TclSwatchLib\n");
	return TCL_ERROR;
    }

    if (UTT_InitTclVecLib (interp) == TCL_ERROR) {
        printf ("Error initializing TclVecLib\n");
        return TCL_ERROR;
    }

    if (IPT_InitTclImgLib (interp) == TCL_ERROR) {
	printf ("Error initializing TclImgLib\n");
	return TCL_ERROR;
    }

    return TCL_OK;
}

#undef  TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS DLLEXPORT

EXTERN int Poimg_Init (Tcl_Interp *interp)
{
    if (Tcl_InitStubs (interp, "8.1", 0) == NULL) {
	return TCL_ERROR;
    }

    if (Tk_InitStubs (interp, "8.1", 0) == NULL) {
	return TCL_ERROR;
    }

    if (initMyLibs (interp) == TCL_ERROR)
	return TCL_ERROR;

    #if defined (DEBUG_LOCAL)
	printf ("poImg dynamic library initialized\n"); fflush (stdout);
    #endif

    return Tcl_PkgProvide (interp, PACKAGE_NAME, PACKAGE_VERSION);
}
