/*
 *  libpipi       Proper image processing implementation library
 *  Copyright (c) 2004-2008 Sam Hocevar <sam@zoy.org>
 *                All Rights Reserved
 *
 *  $Id$
 *
 *  This library is free software. It comes without any warranty, to
 *  the extent permitted by applicable law. You can redistribute it
 *  and/or modify it under the terms of the Do What The Fuck You Want
 *  To Public License, Version 2, as published by Sam Hocevar. See
 *  http://sam.zoy.org/wtfpl/COPYING for more details.
 */

/*
 * sdl.c: SDL_image I/O functions
 */

#include "config.h"
#include "common.h"

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

#include <SDL_image.h>

#include "pipi.h"
#include "pipi_internals.h"

pipi_image_t *pipi_load_sdl(const char *name)
{
    pipi_image_t *img;
    SDL_Surface *priv = IMG_Load(name);

    if(!priv)
        return NULL;

    if(priv->format->BytesPerPixel == 1)
    {
        img = pipi_new(priv->w, priv->h);
        SDL_BlitSurface(priv, NULL, img->priv, NULL);
        SDL_FreeSurface(priv);
        return img;
    }

    img = (pipi_image_t *)malloc(sizeof(pipi_image_t));
    img->width = priv->w;
    img->height = priv->h;
    img->pitch = priv->pitch;
    img->channels = priv->format->BytesPerPixel;
    img->pixels = priv->pixels;
    img->priv = (void *)priv;

    return img;
}

pipi_image_t *pipi_new_sdl(int width, int height)
{
    pipi_image_t *img;
    SDL_Surface *priv;
    Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x00000000;
#else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0x00000000;
#endif
    priv = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32,
                                rmask, gmask, bmask, amask);

    if(!priv)
        return NULL;

    img = (pipi_image_t *)malloc(sizeof(pipi_image_t));
    img->width = priv->w;
    img->height = priv->h;
    img->pitch = priv->pitch;
    img->channels = priv->format->BytesPerPixel;
    img->pixels = priv->pixels;
    img->priv = (void *)priv;

    return img;
}

void pipi_free_sdl(pipi_image_t *img)
{
    SDL_FreeSurface(img->priv);

    free(img);
}

void pipi_save_sdl(pipi_image_t *img, const char *name)
{
    SDL_SaveBMP(img->priv, name);
}