//
// dbp_image.c -- funcs to use with GIMP C-Source dumps.
//
// (C)2001 Wauters Kris
//
// For more information, check out http://www.snoozys-dc-stuff.be.tf
//
// To KOS - 2010 Indiket

#include <kos.h>
#include "dbp_image.h"

#define RGB565(r, g, b) ((r >> 3) << 11) | ((g >> 2) << 5) | ((b >> 3) << 0);

struct dbp_hdr 
{
	char   version[2];        /* version code of DBP file, currently 1A */
	char   creationdate[8];   /* filecreationdate (format mmddyyyy)     */
	char   creator[48];       /* copyright notification                 */
	char   xmax1;             /* byte 1 of width of picture             */
	char   xmax2;             /* byte 2 of width of picture             */
	char   xmax3;             /* byte 3 of width of picture             */
	char   ymax1;             /* byte 1 of height of picture            */
	char   ymax2;             /* byte 2 of height of picture            */
	char   ymax3;             /* byte 3 of height of picture            */
};

//--- little routine to do some shifting of bytes ---
int shift_add(char c, int r)
{
  int result = r;
  result *= 10;
  result += (int)c - (int)'0';
  return result;
}

//--- this function will load and display DBP files on the screen.
//--- ARGUMENTS:
//--- fn = filename, path to file included
//--- xpos = most left position of the picture
//--- ypos = most top position of the picture
int dbp_load(char *fn, int xpos, int ypos)
{
	//NOTE 2010: Original function used malloc to read image data, but didn't use free...
	//One good solution is without dynamic allocation, just create the char :)
	int fd;
	int numbytes;
	int x;
	int y;
	int r;
	int g;
	int b;
	int xmax;
	int ymax;
	int pointer = 0;
	struct dbp_hdr dbphdr;

	//--- load file from disc ---
	fd = fs_open(fn,O_RDONLY);
	if (fd <0) {
		return -1;
	}

	fs_seek(fd,0,SEEK_END);
	numbytes = fs_tell(fd);
	//We know filesize, so just create the char array!
	unsigned char tmpfile[numbytes]; //Not dynamic allocation...
	fs_seek(fd,0,SEEK_SET);
	fs_read(fd,tmpfile,numbytes);
	fs_close(fd);

	//--- analyse picture header and do some calculations ---
	memcpy(&dbphdr, tmpfile, sizeof(dbphdr)); 
	pointer += sizeof(dbphdr);
	xmax=0;
	ymax=0;
	xmax = shift_add(dbphdr.xmax1,0);
	xmax = shift_add(dbphdr.xmax2,xmax);
	xmax = shift_add(dbphdr.xmax3,xmax);
	ymax = shift_add(dbphdr.ymax1,0);
	ymax = shift_add(dbphdr.ymax2,ymax);
	ymax = shift_add(dbphdr.ymax3,ymax);
	
	//--- display picture on specified location ---
	y = 0;
	while (y !=ymax) 
		{
		x = 0;
		y++;
		while (x !=xmax) 
			{
			x++;
			r = tmpfile[pointer++];
			g = tmpfile[pointer++];
			b = tmpfile[pointer++];
			if ((x!=1) && (x!=xmax) && (y!=1) && (y!=ymax))
				 {
				 vram_s[(x+xpos) + (640*(y+ypos))] = RGB565(r,g,b);
				 }
			}
		}
	return 0;
}
