/* Stereograph 0.16, 12/04/2000;
 * Graphics I/O functions;
 * Copyright (c) 2000 by Fabian Januszewski <fabian.linux@januszewski.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */


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

#include "renderer.h"
#include "gfxio.h"
#include "globals.h"

int Read_Gfx_File (char *file_name, struct GFX_DATA *gfx)
{
	int a;
	FILE *ifile = NULL;

	ifile = fopen(file_name, "r");

	if(ifile == NULL) {
		if(verbose) printf("FAILED;\n"); else fprintf(stderr, "loading gfx data...FAILED;\n");
		fprintf(stderr, "cannot open file '%s'!\n", file_name);
		return -1;
	} else {
		a = Read_TARGA(ifile, gfx);
	}
	fclose(ifile);
	ifile = NULL;
	return a;
}


int Write_Gfx_File (char *file_name, struct GFX_DATA *gfx)
{
	int a;
	FILE *ofile = NULL;

	if(verbose) printf("saving '%s' (%i*%i)...", file_name, gfx->Width, gfx->Height);
	if(!file_name)
		return Write_PIPE(stdout, gfx);
	else {
		ofile = fopen(file_name, "w+");

		if(ofile == NULL) {
			if(verbose) printf("FAILED;\n"); else fprintf(stderr, "writing gfx data...FAILED;\n");
			fprintf(stderr, "cannot create file %s!\n", file_name);
			return -1;
		} else
			a = Write_TARGA(ofile, gfx);
		fclose(ofile);
		ofile = NULL;
		return a;
	}
}


int Read_TARGA (FILE *ifile, struct GFX_DATA *gfx)
{
	/* TARGA uses the Intel format for integer coding (low byte first) */

	unsigned char header[20];
	int x, y, *palette, c, l, s, z;

	/* reading all header information */
	if(fread(header, sizeof(char), 18, ifile) != 18) {
		if(verbose) printf("FAILED!\n"); else fprintf(stderr, "reading gfx data...FAILED;\n");
		fprintf(stderr, "cannot read header! (file corrupt?)\n");
		return -2;
	}

	/* general measurements */
	gfx->Width = (int)header[12] + (int)header[13]*256;
	gfx->Height = (int)header[14] + (int)header[15]*256;
	gfx->Data = (int*)malloc(gfx->Width*gfx->Height*sizeof(int));
	if(!gfx->Data) {
		if(verbose) printf("FAILED;\n"); else fprintf(stderr, "reading gfx data...FAILED;\n");
		fprintf(stderr, "error allocating memory for image dimensions of %i * %i pixels in 32 bit\n", gfx->Width, gfx->Height);
		fprintf(stderr, "debug - header follows:\n");
		for(x = 0; x < 20; x += 4)
			fprintf(stderr, " %i, %i, %i, %i;\n", (int)header[x], (int)header[x + 1], (int)header[x + 2], (int)header[x + 3]);
		return -3;
	}

	/* reading image identification field */
	for(x = 0; x < header[0]; x++)
		getc(ifile);

	/* reading palette data */
	if((header[1] != 0) && ((header[5] + header[6]*256) > 0) && (((header[3] + header[4]*256) + (header[5] + header[6]*256)) <= 256)) {
		palette = (int*)malloc(((header[3] + header[4]*256) + (header[5] + header[6]*256)) * sizeof(int));
		for(x = header[3] + header[4]*256; (x < (header[5] + header[6]*256)); x++)
			Read_TARGA_RGB(ifile, (int)header[7], NULL, palette + x);
	} else
		palette = NULL;

	if(((header[2] == 2) && (header[16] >= 16)) || (((header[2] == 1) || header[2] == 3) && (header[16] == 8))) {
	/* type 1: 8 bit/palette, uncompressed; type 2: 16 bit++, uncompressed; type 3: 8 bit monocrome, uncompressed; */
		if(header[17] & 32) {
			for(y = 0; y < gfx->Height; y++) {
				if(header[17] & 16)
					for(x = gfx->Width - 1; x >= 0; x--)
						Read_TARGA_RGB(ifile, (int)header[16], palette, gfx->Data + (y * gfx->Width) + x);
				else
					for(x = 0; x < gfx->Width; x++)
						Read_TARGA_RGB(ifile, (int)header[16], palette, gfx->Data + (y * gfx->Width) + x);
			}
		} else {
			for(y = gfx->Height - 1; y >= 0; y--) {
				if(header[17] & 16)
					for(x = gfx->Width - 1; x >= 0; x--)
						Read_TARGA_RGB(ifile, (int)header[16], palette, gfx->Data + (y * gfx->Width) + x);
				else
					for(x = 0; x < gfx->Width; x++)
						Read_TARGA_RGB(ifile, (int)header[16], palette, gfx->Data + (y * gfx->Width) + x);
			}
		}
		if(verbose) printf("gfx data read (%i*%i);\n", gfx->Width, gfx->Height);
		free(palette);
		return 0;
	} else if(((header[2] == 10) && (header[16] >= 16)) || (((header[2] == 9) || header[2] == 11) && (header[16] == 8))) {
	/* type 9: 8 bit/palette RLE; type 10: 16 bit++, RLE; type 11: 8 bit monocrome, RLE; */
		for(z = 0; ((l = getc(ifile)) != EOF) && (z < (gfx->Height * gfx->Width)); ) {
			if(l & 128) { /* compressed data follows */
				l &= 127; /* extracting length */
				Read_TARGA_RGB(ifile, (int)header[16], palette, &c);
				for(s = 0; (s <= l); s++) {
					x = z % gfx->Width;
					y = (z - x) / gfx->Width;
					if(header[17] & 16)
						x = gfx->Width - 1 - x;
					if(!(header[17] & 32))
						y = gfx->Height - 1 - y;
					if((x < gfx->Width) && (y < gfx->Height) && (x >= 0) && (y >= 0))
						gfx->Data[(y * gfx->Width) + x] = c;
					else
						fprintf(stderr, "(%i, %i) => error\n", x, y);
					z++;
				}
			} else { /* uncompressed data follows */
				for(s = 0; (s <= l); s++) {
					x = z % gfx->Width;
					y = (z - x) / gfx->Width;
					if(header[17] & 16)
						x = gfx->Width - 1 - x;
					if(!(header[17] & 32))
						y = gfx->Height - 1 - y;
					if((x < gfx->Width) && (y < gfx->Height) && (x >= 0) && (y >= 0))
						Read_TARGA_RGB(ifile, (int)header[16], palette, gfx->Data + (y * gfx->Width) + x);
					else
						fprintf(stderr, "(%i, %i) => error\n", x, y);
					z++;
				}
			}
		}
		if(verbose) printf("gfx data read (%i*%i);\n", gfx->Width, gfx->Height);
		free(palette);
		return 0;
	} else {
		if(verbose) printf("FAILED;\n"); else fprintf(stderr, "reading gfx data...FAILED;\n");
		fprintf(stderr, "Unsupported Targa Data Format %i@%i;\nOnly TARGA types 1, 2, 3 (uncompressed) and 9, 10, 11 (RLE) are supported;\n", header[2], header[16]);
		free(palette);
		return -1;
	}
}


int Read_TARGA_RGB(FILE *ifile, int bits, int *palette, int *c) {
	static int a, r, g, b, z1, z2;
	a = 0;
	if(bits == 8) {
		if(palette)
			(*c) = palette[(int)getc(ifile)];
		else
			(*c) = (int)getc(ifile) * 65793;  /* 65793 = (1+256+65536) */
	} else if(bits == 16) {
			z1 = getc(ifile);
			z2 = getc(ifile);
			r = (int)((255.0/31.0) * (float)((z1 & 124) >> 2) );  /* 124 = 64 + 32 + 16 + 8 + 4 */
			g = (int)((255.0/31.0) * (float)(((z1 & 3) << 3) | ((z2 & 224) >> 5)) );  /* 224 = 128 + 64 + 32 */
			b = (int)((255.0/31.0) * (float)(z2 & 31) );
			(*c) = r + (g << 8) + (b << 16);
			a = z1 & 128;
		} else {
			r = getc(ifile);
			g = getc(ifile);
			b = getc(ifile);
			(*c) = r + (g << 8) + (b << 16);
			if(bits == 32)
				a = getc(ifile);
		}
	return a; /* attribute (alpha/transparency information, 32 bit only) */
}

/* writes all gfx data to stdout, preceded by the resolution of gfx data - everything 32 bit wide */
int Write_PIPE (FILE *pp, struct GFX_DATA *gfx)
{
	fwrite(&(gfx->Width), sizeof(int), 1, pp);
	fwrite(&(gfx->Height), sizeof(int), 1, pp);
	fwrite(gfx->Data, sizeof(int), (gfx->Width) * (gfx->Height), pp);
	return 0;
}

int Write_TARGA (FILE *ofile, struct GFX_DATA *gfx)
{
	int a, x, y;
	/* standard TARGA header consists of 18 bytes */
	/* id tag length */
	putc(strlen("created by stereograph"), ofile);
	/* color pallette, yes/no */
	putc(0, ofile);
	/* TARGA type 2: RGB 24 bit, no pallette */
	putc(2, ofile);
	/* 5 following bytes contain only pallette information */
	putc(0, ofile);
	putc(0, ofile);
	putc(0, ofile);
	putc(0, ofile);
	putc(0, ofile);
	/* x offset */
	putc(0, ofile);
	putc(0, ofile);
	/* y offset */
	putc(0, ofile);
	putc(0, ofile);
	/* width, low byte first */
	putc(gfx->Width & 255, ofile);
	putc((gfx->Width >> 8) & 255, ofile);
	/* height */
	putc(gfx->Height & 255, ofile);
	putc((gfx->Height >> 8) & 255, ofile);
	/* bits per pixel */
	putc(32-8, ofile);
	/* Image Descriptor Flags */
	putc(0, ofile);
	fwrite("created by stereograph", sizeof(char), strlen("created by stereograph"), ofile);
	/* data follows */
	a = 0;
	for(y = gfx->Height - 1; (y >= 0) && (a != EOF); y--)
		for(x = 0; (x < gfx->Width) && (a != EOF); x++)	{
			putc(gfx->Data[y * gfx->Width + x] & 255, ofile);
			putc((gfx->Data[y * gfx->Width + x] >> 8) & 255, ofile);
			a = putc((gfx->Data[y * gfx->Width + x] >> 16) & 255, ofile);
		}
	if(a != EOF) {
		if(verbose) printf("completed;\n");
		return 0;
	} else {
		if(verbose) printf("FAILED;\n"); else fprintf(stderr, "writing gfx data...FAILED;\n");
			fprintf(stderr, "cannot write to file! (disk full?)\n");
		return -1;
	}
}