/* Surface
 * (C) Copyright 1995 by Ashton Mason (amason@cs.uct.ac.za)
 *
 * Permission to use, modify, copy and distribute this source code for
 * any purpose and without fee is granted, provided that this copyright
 * notice appears in all copies and supporting documentation, and that
 * credit is given where due. This source code is provided "as is" with
 * no express or implied warranty.
 */


	// code to read and write TGA files.
        // (C) Copyright Ashton Mason 1995
	// based on the routines TGATOPPM.C and PPMTOTGA.C,
	// distributed with PBMPLUS by Jef Poskanzer.


#define MAXCOLORS 1024


/* Header definition. */

struct ImageHeader {
    unsigned char IDLength;		/* length of Identifier String */
    unsigned char CoMapType;		/* 0 = no map */
    unsigned char ImgType;		/* image type (see below for values) */
    unsigned char Index_lo, Index_hi;	/* index of first color map entry */
    unsigned char Length_lo, Length_hi;	/* number of entries in color map */
    unsigned char CoSize;		/* size of color map entry (15,16,24,32) */
    unsigned char X_org_lo, X_org_hi;	/* x origin of image */
    unsigned char Y_org_lo, Y_org_hi;	/* y origin of image */
    unsigned char Width_lo, Width_hi;	/* width of image */
    unsigned char Height_lo, Height_hi;	/* height of image */
    unsigned char PixelSize;		/* pixel size (8,16,24,32) */
    unsigned char AttBits;		/* 4 bits, number of attribute bits per pixel */
    unsigned char Rsrvd;		/* 1 bit, reserved */
    unsigned char OrgBit;		/* 1 bit, origin: 0=lower left, 1=upper left */
    unsigned char IntrLve;		/* 2 bits, interleaving flag */
};


typedef char ImageIDField[256];


/* Definitions for image types. */

#define TGA_Null 0
#define TGA_Map 1
#define TGA_RGB 2
#define TGA_Mono 3
#define TGA_RLEMap 9
#define TGA_RLERGB 10
#define TGA_RLEMono 11
#define TGA_CompMap 32
#define TGA_CompMap4 33

/* Definitions for interleave flag. */

#define TGA_IL_None 0
#define TGA_IL_Two 1
#define TGA_IL_Four 2


	// TGA reader and writer


class tga
{
  FILE *file;

  int openFile(char *name);
  int closeFile();

  	// from TGA.C

  int RLE_count, RLE_flag;

  unsigned char ColorMap[MAXCOLORS][3];

  void readHeader(FILE *ifp, struct ImageHeader *tgaP);
  void get_map_entry(FILE *ifp, int index, int Size);
  void get_pixel(FILE *ifp, unsigned char *dest, int Size);
  unsigned char getbyte(FILE *ifp);

public:

  tga(void);
  ~tga(void);

  unsigned char *data;			// storage area for pixel data
  int xsize, ysize;			// size of read image

  int mapped;				// is this file color-mapped
  int rlencoded;			// is this file RLE encoded

  int readTGA(char *name);		// read image from TGA file
  int writeTGA(char *name);		// write image to TGA file
  int destroyData();			// destroy the data in memory
};


