#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <graphics.h>
typedef unsigned int uint16_t;
typedef unsigned long uint32_t;
typedef struct bmpfile_magic {
  unsigned char magic[2];
}bmpfile_magic;

typedef struct bmpfile_header {
  uint32_t filesz;
  uint16_t creator1;
  uint16_t creator2;
  uint32_t bmp_offset;
}bmpfile_header;

typedef struct bmp_dib_v3_header_t{
  uint32_t header_sz;
  uint32_t width;
  uint32_t height;
  uint16_t nplanes;
  uint16_t bitspp;
  uint32_t compress_type;
  uint32_t bmp_bytesz;
  uint32_t hres;
  uint32_t vres;
  uint32_t ncolors;
  uint32_t nimpcolors;
}bmp_dib_v3_header_t;
void printscreen(char *filename,int xs,int ys,int width, int height)
{FILE *out = fopen(filename, "wb");
 bmpfile_magic a;
 int bpp = 16;
 bmpfile_header b;
 uint16_t palette[16]={0,7,96,103,(1<<13)|(1<<12)|(1<<11),(1<<13)|(1<<12)|(1<<11) | 103,(1<<13)|(1<<12)|(1<<11)|32,(1<<13)|(1<<12)|(1<<11)|96,(1<<11)|32|1,(1<<11) | 32 | 31,(1<<11)|((1<<11) - 32) | 1,(1<<11) | (1<<11 - 1) , (1<<16  - 1<<11) | 33,(1<<16  - 1<<11) | 31 | 32,(1<<16-1) ^ 30, 0xffff};
 bmp_dib_v3_header_t c;
 int paddedwidth = width * bpp / 8;
 int i, j, k;
 uint16_t *aux = (uint16_t *)malloc(paddedwidth * sizeof(char));
 if(out == NULL)
	{printf("Eroare! - Nu s-a putut deschide fisierul %s\n",filename);
	 return;
	 }
 a.magic[0] = 'B';
 a.magic[1] = 'M';
 fwrite(&a, sizeof(a), 1, out);
 c.bmp_bytesz = height * paddedwidth ;
 b.filesz = c.bmp_bytesz + 54;
 b.creator1 = 666;
 b.creator2 = 13;
 b.bmp_offset = 54;
 c.header_sz = 40;
 c.width = width ;
 c.height = height;
 c.nplanes = 1;
 c.bitspp = bpp;
 c.compress_type = 0;
 c.hres = 1000;
 c.vres = 1000;
 c.ncolors = 0;
 c.nimpcolors = 0;
 fwrite(&b, sizeof(bmpfile_header), 1, out);
 fwrite(&c, sizeof(bmp_dib_v3_header_t), 1, out);
 memset(aux, 0, paddedwidth);
 for(j = ys + height - 1 ; j >= ys ; j--)
 {for(i = xs, k = 0; i < width ;i++, k++)
	aux[k] = palette[getpixel(i,j) % 16];
  fwrite(aux, 2, paddedwidth / 2, out);
 }
 free(aux);
 fclose(out);
}
