// Compatibility layer with allegro

#include <SDL.h>
#include "raine.h"
#include <sys/stat.h>

int mouse_x,mouse_y,mouse_b;

void sdl_init() {
  /* Initialize the SDL library */
  if ( SDL_Init(/* SDL_INIT_AUDIO| */SDL_INIT_VIDEO) < 0 ) {
    fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
    exit(2);
  }
  atexit(SDL_Quit);
}

void sdl_done() {
  // This should also save the sdl specific params... Later !
  SDL_Quit(0);
}

void setup_gfx_modes() {
  // Prepare datas to setup the gfx mode... Nothing for now
}

struct BITMAP *surface_to_bmp(SDL_Surface *s) {
  int a;
  BITMAP *bmp;

  bmp = malloc( sizeof(struct BITMAP) );
  bmp->extra = (void*)s;
  bmp->w = w; bmp->h = h;
  bmp->x_ofs = bmp->y_ofs = 0;
  bmp->line = malloc( sizeof(void*)*h );
  for (a=0; a < h; a++)
    bmp->line[a] = (UINT8 *)s->pixels+a*s->pitch;
  return bmp;
}

struct BITMAP *sdl_create_bitmap_ex(int bpp, int w, int h) {
  // Init a fake bitmap to point to a newly created sdl_surface
  int r,g,b,a; // masks if necessary...
  SDL_Surface *s;

  if (bpp == 8) {
    r = g = b = a = 0; // Useless
  } else {
    SLD_VideoInfo *inf = SDL_GetVideoInfo();
    SDL_PixelFormat *fmt = inf->vfmt;
    if (fmt->BitsPerPixel != bpp) {
      fprintf(stderr,"Something went wrong in bitmap creation\n");
      SDL_Quit(-1);
    }
    r = fmt->Rmask;
    g = fmt->GMask;
    b = fmt->Bmask;
    a = fmt->Amask;
  }

  s = SDL_CreateRGBSurface(SDL_SWSURFACE, // these bitmaps are ALWAYS in ram
			   w,h,bpp,r,g,b,a);
  if ( SDL_MUSTLOCK(screen) ) {
    fprintf(stderr,"Locing problem !\n");
    SDL_Quit(-1);
  }

  return surface_to_bmp(s);
}

void sdl_destroy_bitmap(struct BITMAP *bmp) {
  if (bmp) {
    if (bmp->extra) { // real bitmap (not sub bitmap)
      free(bmp->line);
      SDL_FreeSurface((SDL_Surface*)bmp->extra);
    }
    free(bmp);
  }
}

void set_mouse_range(int x1, int y1, int x2, int y2) {
}

// Strings...

// Return the filename without the path... / and \\ accepted (lovely dos !)
char *get_filename(char *f) {
  char *s = strrchr(f,'/');
  if (!s)
    s = strrchr(f,'\\');
  if (s)
    return s+1;
  return f;
}

void put_backslash(char *s) {
  int l = strlen(s)-1;
  s += l;
  if (*s != '/' && *s != '\\')
    strcat(s,SLASH);
}

// Todo...

int wants_switch_res = 0;
void init_joys() {}

void StartGUI() {}

int exists(char *filename) {
  struct stat buf;
  return !stat(filename,&buf); // stat returns 0 on success...
}

int  save_pcx(const char *filename, BITMAP *bmp, const RGB
	      *pal) {
  // This could be the save_pcx taken from allegro,
  // another saving function eventually to another format
  // or nothing. For now : nothing.
}
