#include "extensions.h"

#if defined(__APPLE__)||defined(__APPLE_CC__)
	#include <Carbon/Carbon.h>
#endif

// taken out of NeHeGL framework!
int check_for_extension(char *extstr)
{
	const unsigned char *pszExtensions = NULL;
	const unsigned char *pszStart;
	unsigned char *pszWhere, *pszTerminator;

	// Extension names should not have spaces
	pszWhere = (unsigned char *) strchr( extstr, ' ' );
	if( pszWhere || *extstr == '\0' )
		return 0;

	// Get Extensions String
	pszExtensions = glGetString( GL_EXTENSIONS );

	// Search The Extensions String For An Exact Copy
	pszStart = pszExtensions;
	for(;;)
	{
		pszWhere = (unsigned char *) strstr( (const char *) pszStart, extstr );
		if( !pszWhere )
			break;
		pszTerminator = pszWhere + strlen( extstr );
		if( pszWhere == pszStart || *( pszWhere - 1 ) == ' ' )
			if( *pszTerminator == ' ' || *pszTerminator == '\0' )
				return 1;
		pszStart = pszTerminator;
	}
	return 0;
}

// lifted straight from GLee!
void *load_extension(char *name)
{
	const char *extname=(const char *)name;
#if defined(WIN32)||defined(__WIN32__)
	return (void*)wglGetProcAddress(extname);
#elif defined(__APPLE__)||defined(__APPLE_CC__)
    CFBundleRef bundle;
    CFURLRef bundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/System/Library/Frameworks/OpenGL.framework"), kCFURLPOSIXPathStyle, true);

    CFStringRef functionName = CFStringCreateWithCString(kCFAllocatorDefault, extname, kCFStringEncodingASCII);

    void *function;

    bundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
    assert(bundle != NULL);

    function = CFBundleGetFunctionPointerForName(bundle, functionName);

    CFRelease(bundleURL);
    CFRelease(functionName);
    CFRelease(bundle);

    return function;
#else
	return (void*)glXGetProcAddressARB((const GLubyte *)extname);
#endif
}

