#include <allegro.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#ifdef ALLEGROGL
#include <alleggl.h>
#endif
#include <fudgefont.h>

/* Helper function to use either Allegro or AllegroGL. */
static inline FONT *my_load_font(char const *name, int size)
{
    PALETTE pal;
    FONT *f = load_font(name, pal, &size);
    select_palette(pal);
#ifdef ALLEGROGL
    FONT *temp = f;
    f = fudgefont_make_agl_font(temp);
    destroy_font(temp);
#endif
    return f;
}

/* Helper function to use either Allegro or AllegroGL. */
static inline void my_color(int r, int g, int b)
{
#ifdef ALLEGROGL
    glColor3ub(r, g, b);
#else
    fudgefont_color_range(255, 255, 255, r, g, b);
#endif
}

/* Helper function to use either Allegro or AllegroGL. */
static inline void my_print(FONT *f, int x, int y, int centered, char const *format, ...)
{
    char str[1024];
    va_list args;
    va_start(args, format);
    uvszprintf(str, sizeof str, format, args);
    va_end(args);

#ifdef ALLEGROGL
    int texture_2d, blend;
    glGetIntegerv(GL_TEXTURE_2D, &texture_2d);
    glGetIntegerv(GL_BLEND, &blend);
    if (!blend) glEnable(GL_BLEND);
    if (!texture_2d) glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    int tl = centered ? text_length(f, str) : 0;
    (fudgefont_font_has_kerning(f) ?
        allegro_gl_printf_ex_kerning : allegro_gl_printf_ex)
        (f, x - tl / 2, y, 0, "%s", str);
#else
    (centered ? textprintf_centre_ex : textprintf_ex)(screen, f, x, y, -1, -1, str);
#endif
    if (!texture_2d) glDisable(GL_TEXTURE_2D);
    if (!blend) glDisable(GL_BLEND);
}

/* Helper function to use either Allegro or AllegroGL. */
static inline void my_setup_screen(void)
{
    set_color_depth(32);
#ifdef ALLEGROGL
    install_allegro_gl();
    set_gfx_mode(GFX_OPENGL_WINDOWED, 640, 480, 0, 0);

    /* Set up projection to match Allegro coordinates. */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, SCREEN_W, SCREEN_H, 0, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

#else
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
#endif
}

static inline void my_flip(void)
{
#ifdef ALLEGROGL
    allegro_gl_flip();
#endif
}
