/* entheh, Bob added OpenGL support */

#include <string.h>
#include "main.h"
#include "screen.h"
#include "log.h"

#undef set_gfx_mode /* See main.h. */


static BITMAP *scrbuf = NULL;



int create_screen(int w, int h) {

	BITMAP *newscrbuf;
	int r;

#ifndef ZIG_GL
	set_color_depth(8);
	#if (defined DEBUGMODE) && (defined ALLEGRO_WINDOWS)
		r = set_gfx_mode(GFX_DIRECTX_WIN, w, h, 0, 0);
	#else
		r = set_gfx_mode(GFX_AUTODETECT, w, h, 0, 0);
	#endif

#else
	set_color_depth(16);
	#if (defined DEBUGMODE)
		r = set_gfx_mode(GFX_OPENGL_WINDOWED, w, h, 0, 0);	
	#else
		r = set_gfx_mode(GFX_OPENGL, w, h, 0, 0);
	#endif
#endif

	if (r) goto fail;

#ifndef ZIG_GL
	newscrbuf = create_bitmap(w, h);
	if (newscrbuf == 0) {
		ustrcpy(allegro_error, "Out of memory");
		goto fail;
	}

	if (scrbuf)
		destroy_bitmap(scrbuf);
	scrbuf = newscrbuf;
#endif

	return 0;

fail:
	LOG("Failure to set screen mode!\n");
	if (scrbuf) {
		char first_error[256];
		ustrncpy(first_error, allegro_error, 255);

		if (set_gfx_mode(GFX_AUTODETECT, scrbuf->w, scrbuf->h, 0, 0)) {
            set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
			allegro_message("Unable to set graphics mode (%d x %d)\n"
                   "(%s)\n\n"
                   "Unable to restore old graphics mode (%d x %d)!!!\n"
                   "(%s)\n\n"
                   "Please take your computer to the vet.\n",
                   w, h, first_error, scrbuf->w, scrbuf->h, allegro_error);
			exit(1);
		}
	}
	return -1;
}



void destroy_screen() {
	if (scrbuf)
		destroy_bitmap(scrbuf);

	scrbuf = NULL;
	set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
}



BITMAP *get_screen_buffer() {
#ifdef ZIG_GL
	return screen;
#else
	return scrbuf;
#endif
}



void free_screen_buffer() {
#ifdef ZIG_GL
	glFlush();
	allegro_gl_flip();
#else
	blit(scrbuf, screen, 0, 0, 0, 0, scrbuf->w, scrbuf->h);
#endif
}

void SwitchCallback(void) {
#ifndef ZIG_GL
	blit(scrbuf, screen, 0, 0, 0, 0, scrbuf->w, scrbuf->h);
#endif
	return;
}
