#include <gfx/gfx.h>
#include <gfx/port.h>
#include <sdl-1.2/gfx/private.h>
#include <stddef.h>
#include <stdlib.h>

int quad_from_sprite(const struct gfx_sprite *const s, struct quad *const q)
{
    q->s = s->s;
    q->s_x = s->s_x;
    q->u0 = q->u2 = s->u;
    q->v0 = q->v1 = s->v;
    q->u1 = q->u3 = s->u + s->w - 1;
    q->v2 = q->v3 = s->v + s->h - 1;
    q->w = s->w;
    q->h = s->h;
    return 0;
}

void quad_sort(struct quad *const q)
{
    const bool xflip = q->x0 > q->x1;

    SDL_Rect r =
    {
        .x = xflip ? q->x1 : q->x0,
        .y = q->y0
    };

    const short w = q->u1 - q->u0 + 1, h = q->v2 - q->v0 + 1;

    SDL_Rect clip =
    {
        .x = xflip ? q->w - q->u0 - w: q->u0,
        .y = q->v0,
        .w = w,
        .h = h
    };

    SDL_Surface *const s = xflip ? q->s_x : q->s;

    if (SDL_BlitSurface(s, &clip, gfx_screen(), &r))
        fprintf(stderr, "SDL_BlitSurface: %s\n", SDL_GetError());
}
