#include "xsimple.h"
#include <stdio.h>
#include <stdlib.h>


XImage *mkximage(int width, int height, int depth, int *pad)
{
   int bpl, padtmp;
   char *data;
   XImage *img;

   if (depth != 1 && depth != 16 && depth != 24) {
       fprintf(stderr, "mkximage(): Unsupported depth\n");
       exit(1);
   }

   if (depth == 1) {
       bpl = (width + 7) / 8;
       data = (char *)malloc(bpl * height);
       img = (XImage *)malloc(sizeof(XImage));

       img->width = width;
       img->height = height;
       img->xoffset = 0;
       img->format = XYBitmap;
       img->data = data;
       img->bitmap_unit = 8;
       img->bitmap_bit_order = MSBFirst;
       img->bitmap_pad = 8;
       img->depth = 1;
       img->bytes_per_line = 0;
       img->obdata = NULL;

       XInitImage(img);
       if (pad) *pad = 0;
       return img;
   }

   bpl = width * (depth == 24 ? 4 : 2);
   padtmp = (depth == 16 && (width * 2) % 4 ? 2 : 0);
   bpl += padtmp;
   data = (char *)malloc(bpl * height);
   img = XCreateImage(xv.d, xv.v, depth, ZPixmap, 0, data, width, height,
           32, 0);
   if (pad) *pad = padtmp;
   return img;
}

void rmximage(XImage *img)
{
   XDestroyImage(img);
}

void putximage(XImage *img, int src_x, int src_y, int dst_x, int dst_y,
       int width, int height)
{
   XPutImage(xv.d, xv.pmap, xv.gc, img, src_x, src_y, dst_x, dst_y,
           width, height);
}

unsigned long pgetximage(XImage *img, int x, int y)
{
   void *p = img->data + y * img->bytes_per_line;
   if (xv.depth == 24)
       return *((unsigned long *)p + x);
   else
       return *((unsigned short *)p + x);
}

void psetximage(XImage *img, int x, int y, unsigned long pixel)
{
   void *p = img->data + y * img->bytes_per_line;
   if (xv.depth == 24)
       *((unsigned long *)p + x) = pixel;
   else
       *((unsigned short *)p + x) = pixel;
}