/*
  JPEG reading and writing by Eric Vannier.
  -------------------------------------------
*/

#include"allegro.h"
#include"jpeg.h"
#include"seal.h"


#ifndef NEW_ALLEGRO
BITMAP *jpeg_load(char *filename, RGB *pal);
int     jpeg_save(char *filename, BITMAP *bmp, RGB *pal);
#else
BITMAP *jpeg_load(AL_CONST char *filename, RGB *pal);
int     jpeg_save(AL_CONST char *filename, BITMAP *bmp, AL_CONST RGB *pal);
#endif
BITMAP *jpeg_load_ex(char *filename, RGB *pal, jpeg_decode_param *jpeg) {
  return load_jpeg_ex(filename, pal, jpeg);
};
int     jpeg_save_ex(char *filename, BITMAP *bmp, RGB *pal,jpeg_code_param *jpeg) {
  return save_jpeg_ex(filename, bmp, pal, jpeg);
};


#ifndef NEW_ALLEGRO
BITMAP *jpeg_load(char *filename, RGB *pal) {
  BITMAP *p;
  //fprintf(stderr,"loading %s\n",filename);
  p=load_jpeg(filename, pal);
  //if(p) fprintf(stderr,"succeeds w=%d h=%d d=%ld id=%lx\n",p->w,p->h,(unsigned long)(p->vtable->color_depth),p->id);
  //else fprintf(stderr,"failed %d\n",errno); /* why? */
  return p;
};
#else
extern int _color_depth;
BITMAP *jpeg_load(AL_CONST char *filename, RGB *pal) {
  BITMAP *p;
  int x,y;
  long cd=_color_depth;
  _color_depth=24; /* force loading to 24bit let fixup_loaded_bitmap handle dithering later */
  set_color_depth(24);
  p=load_jpeg(filename, pal);
  set_color_depth(cd);
  /* strange this seems to get the colors right if screen is 24 bit mode, anything else and
     you get bgr out instead of rgb - we need to fix it.
  */
  if(cd != 24) {
   for(y=0 ; y < p->h ; y++) {
    for(x=0; x < p->w ; x++) {
     long r,g,b,c=getpixel(p,x,y);
     r=getb24(c);g=getg24(c);b=getr24(c);
     putpixel(p,x,y,makecol24(r, g, b));
    }
   }
  }
  //fprintf(stderr,"jpeg_loading depth=%ld\n",cd);
  return p;
};
#endif

#ifndef NEW_ALLEGRO
int     jpeg_save(char *filename, BITMAP *bmp, RGB *pal) {
#else
int     jpeg_save(AL_CONST char *filename, BITMAP *bmp, AL_CONST RGB *pal) {
#endif
  return save_jpeg(filename, bmp, pal);
};

#include"jpegsup.exp"

lib_begin ( void )
{
        if ( ap_process == AP_ALLOC ) { /* first call of library */
          AP_EXPORTLIB(); /* export table in jpegsup.exp */
          register_bitmap_file_type("jpg", &jpeg_load, &jpeg_save);
        } else
        if ( ap_process == AP_INIT ) {
          AP_SETNUMOFCALLS(1); /* set max num of calls */
        } else
        if ( ap_process == AP_FREE ) { /* last call of library */
          register_bitmap_file_type("jpg", NULL, NULL);
        };

} lib_end;

