File: TGAFile.cpp

package info (click to toggle)
openmohaa 0.81.1%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: trixie
  • size: 29,124 kB
  • sloc: ansic: 270,865; cpp: 250,173; sh: 234; asm: 141; xml: 64; makefile: 7
file content (1574 lines) | stat: -rw-r--r-- 36,048 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
/*

	Modified by Chris Losinger for Smaller Animals Software's ImgLib/ImgDLL.
	Esp. RGB->BGR and row order switches. 9/98
*/
#include <stdio.h>
#include <io.h>

/*
	TGADefs.h - Tye and Constant declaration file
	This File defines the Types, and the Constant Values used by the 
	TGAFile Class.

	Created By: Timothy A. Bish
	Created On:	08/18/98
*/

#ifndef TGADEFSH
#define TGADEFSH

#include <windows.h>

#pragma pack(1) // Align the structure on byte boundries...

// Possible Image Types
#define TGA_NOIMAGETYPE    0	// No Image Data Included in Image
#define TGA_MAPRGBTYPE     1	// Colormapped Image Data - No Compression
#define TGA_RAWRGBTYPE     2	// Truecolor Image Data - No Compression
#define TGA_RAWMONOTYPE    3	// Monochrome Image Data - No Compression
#define TGA_MAPENCODETYPE  9	// Colormapped Image Data - Compressed RLE
#define TGA_RAWENCODETYPE  10	// Truecolor Image Data - Compressed RLE
#define TGA_MONOENCODETYPE 11	// Monochrome Image Data - Compressed RLE
// Version Macro
#define TGA_VERSIONONE 1		// Version 1 File Format
#define TGA_VERSIONTWO 2		// Version 2 File Format
// File Read Write Modes
const int GREYSC = 0;			// Image is Greyscale
const int COLOUR = 1;			// Image is Color
const int MAPPED = 2;			// Image has a Color Map
const int RLENCO = 4;			// Image is RLE Encoded

// 18 Byte Sturcture representin the basic definitions of
// the image
typedef struct _aTGAHEADER
{
	BYTE IDLength;			// 00h Size of ID Field
	BYTE ColorMapType;		// 01h Color Map Type
	BYTE ImageType;			// 02h Image Type Code
	WORD CMapStart;			// 03h Color Map Origin
	WORD CMapLength;		// 05h Color Map Length
	BYTE CMapDepth;			// 07h Color Map Depth
	WORD XOffset;			// 08h X origin of Image
	WORD YOffset;			// 0Ah Y origin of Image
	WORD Width;				// 0Ch Width of Image
	WORD Height;			// 0Eh Height of Image
	BYTE PixelDepth;		// 10h Image Pixel Size
	BYTE ImageDescriptor;	// 11h Image Description Byte
} TGAHEADER;

// The footer is 26 Bytes in length and is always at the end of a
// TGA v2.0 file.
typedef struct _aTGAFOOTER
{
	DWORD ExtensionOffset;		// Extension Area Offset
	DWORD DeveloperOffset;		// Developer Directory Offset
	CHAR Signature[18];			// TGA Signature
} TGAFOOTER;

typedef struct _aTGATAG
{
	WORD  TagNumber;		// ID Number of the Tag
	DWORD DataOffset;		// Offset Location of the Tag
	DWORD DataSize;			// Size of the Tag Data in Bytes
} TGATAG;

// The extension area is basically the second header in the TGA v2.0
// file format.
typedef struct _aTGAEXTENSION
{
	WORD  Size;					// Extension Size
	CHAR  AuthorName[41];		// Author Name
	CHAR  AuthorComment[324];	// Author Comment
	WORD  StampMonth;			// Date/Time Stamp: Month
	WORD  StampDay;				// Date/Time Stamp: Day
	WORD  StampYear;			// Date/Time Stamp: Year
	WORD  StampHour;			// Date/Time Stamp: Hour
	WORD  StampMinute;			// Date/Time Stamp: Minute
	WORD  StampSecond;			// Date/Time Stamp: Second
	CHAR  JobName[41];			// Job Name/ID
	WORD  JobHour;				// Job Time: Hours
	WORD  JobMinute;			// Job Time: Minutes
	WORD  JobSecond;			// Job Time: Seconds
	CHAR  SoftwareId[41];		// Software ID
	WORD  VersionNumber;		// Version Number of Software
	BYTE  VersionLetter;		// Version Letter of Software
	DWORD KeyColor;				// Key Color
	WORD  PixelNumerator;		// Pixel Aspect Ratio
	WORD  PixelDenominator;		// Pixel Aspect Ratio
	WORD  GammaNumerator;		// Gamma Value
	WORD  GammaDenominator;		// Gamma Value
	DWORD ColorOffset;			// Color Correction Offset
	DWORD StampOffset;			// Postage Stamp Offset
	DWORD ScanOffset;			// Scanline Table Offset
	BYTE  AttributesType;		// Attributes Type
} TGAEXTENSION;

// The Color Correction Table is an array of 2048 Bytes in length, which
// contians 256 entries used to store the values used for color remapping.
typedef struct _aTGACOLORCORRECTIONTABLE
{
	SHORT Alpha;	// Alpha Channel Seldom Used
	SHORT Red;		// Red Value of Correction
	SHORT Green;	// Green Value of Correction
	SHORT Blue;		// Green Value of Correction
} TGACOLORCORRECTIONTABLE;

#define TRIALVERSION	-1		// LIB was not initialized with a registered key

#define IMGOK			0		// no err
#define MEMERR			1		// out of mem
#define FILEOPENERR		2		// error on file open
#define FILEREADERR		3		// error on file read
#define FILEWRITEERR	4		// error on file write
#define BADPARAMERR		5		// bad user param
#define INVALIDBMPERR	6		// bad BMP file
#define BMPRLEERR		7		// we don't do compressed (RLE) BMP files
#define INVALIDGIFERR	8		// bad GIF file
#define INVALIDJPGERR	9		// bad JPG file
#define IMGDCERR		10		// error with device context
#define IMGDIBERR		11		// problem with a GetDIBits call
#define NOGIFERR		12		// GIF support disabled
#define IMGNORESOURCE	13		// resource not found
#define CALLBACKCANCEL	14		// callback returned FALSE - operation aborted
#define INVALIDPNGERR	15		// bad PNG file
#define PNGCREATEERR	16		// internal PNG lib behavior - contact smaller animals s.w.
#define IMGDLLINTERNAL	17		// misc unexpected behavior error - contact smaller animals s.w.
#define IMGFONTERR		18		// trouble creating a font object
#define INTTIFFERR		19		// misc internal TIFF error
#define INVALIDTIFFERR	20		// invalid TIFF file
#define TIFFLZWNOTSUPPORTED	21	// this will not read TIFF-LZW iamges
#define INVALIDPCXERR	22		// invalid PCX image
#define CREATEBMPERR		23		// a call to the fn CreateCompatibleBitmap failed
#define IMGNOLINES		24		// end of an image while using single-line de/compression
#define GETDIBERR			25		// error during a call to GetDIBits
#define DEVOPNOSUPPORT	26		// device does not support an operation required by this function
#define INVALIDWMF		27		// invalid windows metafile
#define DEPTHMISMATCHERR	28	// the file was not of the requested bit-depth
#define INVALIDTGAERR 35		// Invalid TGA File
#define NOTGATHUMBNAIL 36		// No TGA Thumbnail in the file 

#pragma pack()

#endif

class TGAFile
{

public:

	// parameters
	__int32  m_error;	

public:

	// operations

	TGAFile();

	BOOL		IsFileTGA(const char * fileName);
	
	LPVOID	 LoadTGA(	const char *fileName,		// Name of file
										UINT32 *width,			// Width in Pixel
										UINT32 *height);		// Height

	HGLOBAL LoadTGA8Bit(const char    *fileName,	// Name of File
							  UINT32  *width,		// Width in pixels
							  UINT32  *height,		// Height
							  RGBQUAD *pal);		// Palette of RGBQUADS

	BOOL GetTGADims(const char *fileName, 
						  UINT32 *width, 
						  UINT32 *height);

	BOOL SaveTGA32(const char * fileName,	// output path
						 BYTE *inBuf,		// RGB buffer
						 UINT32 width,		// size
						 UINT32 height);

	BOOL Save8BitTGA(const char * fileName, 	// output path
					 BYTE *colormappedbuffer,	// one BYTE per pixel colomapped image
					 UINT32 width,				// Width of image
					 UINT32 height,				// Height of image
					 __int32 colors,				// number of colors (number of RGBQUADs)
					 RGBQUAD *colormap);		// array of RGBQUADs 

	HGLOBAL LoadTGAThumbnail(const char *fileName,	// Name of file
								   UINT32 *width,	// Width in Pixel
								   UINT32 *height);	// Height

private:

	// Parameters

	char					TGA_ImageIDFeild[256];// Text in file
	BYTE					TGA_Attribute;	// Number of attribute bytes per pixel
											// i.e. 1 for T16 and 8 for T32
	UINT32 					mode;			// Mode of current Read or Write
	
	// RLE Decompression Variables
	BYTE					Red,			// Stores pixel value for
							Grn,			// RLE series of oixels
							Blu, 
							Alpha;
	UINT32 l;								// Used when 8 bit files use RLE 
	__int32 RLECount, RLEFlag;				// Indicates whether the RLE series
											// is still going or is finished

private:

	// Operations

	__int32 TGA_GetFileVersion(FILE *fp);		// Determines whether this is a V1.0
											// or V2.0 TGA File
	BOOL TGA_GetMapEntry(BYTE   *Red,		// Get the Color Values out of the 
											 BYTE   *Green,		// Color map in the TGA File
											 BYTE   *Blue,		// Return TRUE on Success
											 BYTE   *Alpha,
											 FILE   *fp,
											 UINT32 Depth);

	// version that takes a file ptr
	BOOL TGA_GetPixelValue(BYTE    *Red,	// Get and parse a single pixel value
											   BYTE    *Grn,	// from the TGA file. Handles Unencoding
											   BYTE    *Blu,	// of RLE encoded files.
											   BYTE    *Alp,	// plus Alpha (08jan00/bgw)
											   FILE    *fp,
											   UINT32  PixelDepth,
											   RGBQUAD *CMap);

	// version that takes a buffer ptr							   
	BOOL TGA_GetPixelValue(BYTE    *Red,	// Get and parse a single pixel value
											   BYTE    *Grn,	// from the TGA file. Handles Unencoding
											   BYTE    *Blu,	// of RLE encoded files.
											   BYTE    *Alp,	// plus Alpha (08jan00/bgw)
											   BYTE ** ppTGAData,
											   UINT32  PixelDepth,
											   RGBQUAD *CMap);
};

//#define MAX_IMAGEREAD_BUFFER 65535
//BYTE *	gpImageReadBuffer = NULL;
//long		glImageReadBufferSize = 0;
//BYTE *	gpImageReadBufPos = NULL;
//
//
//typedef struct tagTGAColorComponents
//    {
//    BYTE red;
//    BYTE green;
//    BYTE blue;
//    BYTE alpha;
//    }	TGAColorComponents;
    
/* TGA File REader Classs Implementation File
   This Implementation Allows the reading of TGA (Targa) Files
   into an RGB buffer. Also the class allows an RGB Buffer to be 
   written to a TGA File. There is also a function to determine 
   the dimensions of a TGA file.

  Created By: Timothy A. Bish
  Created On: 08/17/98

*/
////////////////////////////////////////////////////////////////////////////
//		No Much going on here
TGAFile::TGAFile()
	{
	m_error = IMGOK;
	}


////////////////////////////////////////////////////////////////////////////
//		GetTGADimns
//		Find dims of the image in a TGA file
//		Returns - TRUE on success
BOOL
TGAFile::GetTGADims(const char * fileName, UINT32 * width, UINT32 * height)
	{
	// for safety
	*width = 0;
	*height = 0;
	FILE * fp;
	TGAHEADER tgahd;

	// Init the file Header to all zeros
	ZeroMemory(&tgahd, sizeof(tgahd));

	// init
	m_error = IMGOK;
	fp = fopen(fileName, "rb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}

	// Get the Header
	if(fread(&tgahd, 1, sizeof(TGAHEADER), fp) != sizeof(TGAHEADER))
		{
		m_error = FILEREADERR;
		fclose(fp);
		return FALSE;
		}

	// Check fo valid data in structure
	if(tgahd.PixelDepth > 32)
		{
		// I don't do Pixel Depths Bigger than 32
		m_error = INVALIDTGAERR;
		fclose(fp);
		return NULL;
		}

	// Anything other than the standard TGA types
	// and I quit
	switch(tgahd.ImageType)
		{
		case TGA_MAPRGBTYPE:
		case TGA_RAWRGBTYPE:
		case TGA_RAWMONOTYPE:
		case TGA_MAPENCODETYPE:
		case TGA_RAWENCODETYPE:
		case TGA_MONOENCODETYPE:
			break;

		default:
			m_error = INVALIDTGAERR;
			fclose(fp);
			return NULL;
		}

	// Grab the Image dimensions	
	*width = tgahd.Width;
	*height = tgahd.Height;
	fclose(fp);
	return TRUE;
	}

/*****************************************************************************
* NAME: 
*  TGAFile::IsFileTGA
* 
* DESCRIPTION: 
*  Description goes here...
* 
*******************************************************************************/
BOOL
TGAFile::IsFileTGA(const char * fileName)
	{
	TGAHEADER		tgahd;
	FILE *			fp;

	ZeroMemory(&tgahd, sizeof(tgahd));
	fp = fopen(fileName, "rb");
	long  rc = fread(&tgahd, 1, sizeof(TGAHEADER), fp);
	fclose(fp);

	if(	(rc == sizeof(TGAHEADER)) &&							// must be big enough for a header...
			(tgahd.PixelDepth == 32) &&								// 32-bit TGAs only
			(tgahd.ImageType == TGA_RAWRGBTYPE) )			// Raw RGBA format only
		return(TRUE);

	return(FALSE);
	}

////////////////////////////////////////////////////////////////////////////
//		LoadTGA
//		load a .TGA file - 1,4,8,24,32 bit
//		allocates and returns an RGB buffer containing the image.
//		modifies width and height accordingly - NULL, 0, 0 on error
LPVOID
TGAFile::LoadTGA(const char * fileName, UINT32 * width, UINT32 * height)
	{
	LPVOID		pNew = NULL;
	BYTE *		pRGB = NULL;
	BYTE			Alpha;

	TGAHEADER tgahd;

	BYTE  TGA_Origin = 0;

	RGBQUAD CColMap[256];

	// for safety
	*width = 0;
	*height = 0;

	// init
	m_error = IMGOK;

	// Init the file Header to all zeros
	ZeroMemory(&tgahd, sizeof(tgahd));
	FILE * fp;
	fp = fopen(fileName, "rb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}

	// Read the TGA Header
	long  rc = fread(&tgahd, 1, sizeof(TGAHEADER), fp);

	if(rc != sizeof(TGAHEADER))
		{
		m_error = FILEREADERR;
		fclose(fp);
		return NULL;
		}

	// Check fo valid data in structure
	if((tgahd.PixelDepth> 32) || (tgahd.PixelDepth<8))
		{
		// I don't do Pixel Depths Bigger than 32
		m_error = INVALIDTGAERR;
		fclose(fp);
		return NULL;
		}

	// Anything other than the standard TGA types
	// and I quit
	switch(tgahd.ImageType)
		{
		case TGA_MAPRGBTYPE:
		case TGA_RAWRGBTYPE:
		case TGA_RAWMONOTYPE:
		case TGA_MAPENCODETYPE:
		case TGA_RAWENCODETYPE:
		case TGA_MONOENCODETYPE:
			break;

		default:
			m_error = INVALIDTGAERR;
			fclose(fp);
			return NULL;
		}

	// Set the number of Color Planes
	if(tgahd.ImageType == TGA_RAWMONOTYPE)
		{
		mode = GREYSC;
		}
	else
		{
		mode = COLOUR;
		}

	// Read the ID Descriptor if present
	if(tgahd.IDLength != 0)
		{
		// Read the TGA Comments
		long  rc = fread(&TGA_ImageIDFeild, 1, tgahd.IDLength, fp);

		if(rc != tgahd.IDLength)
			{
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}
		}

	// Parse the Image Descriptor
	TGA_Attribute = (BYTE)(tgahd.ImageDescriptor & 0x0f);
	TGA_Origin    = (BYTE)((tgahd.ImageDescriptor & 0x20) / 32);

	// If present read the color map
	if(tgahd.ColorMapType != 0)
		{
		// Get the color map
		for(__int32 i = 0; i < (tgahd.CMapStart + tgahd.CMapLength); i++)
			{
			TGA_GetMapEntry(&CColMap[i].rgbRed, &CColMap[i].rgbGreen, &CColMap[i].rgbBlue, &Alpha, fp, tgahd.CMapDepth);
			}

		// If the TGA file actually needs the color map
		// Set the mode to show this
		if((tgahd.ImageType != TGA_RAWRGBTYPE) && (tgahd.ImageType != TGA_RAWMONOTYPE) && (tgahd.ImageType != TGA_RAWENCODETYPE))
			mode = mode | MAPPED;
		}

	// Check Run Length Encoding
	if((tgahd.ImageType == TGA_MAPENCODETYPE) || (tgahd.ImageType == TGA_RAWENCODETYPE) || (tgahd.ImageType == TGA_MONOENCODETYPE))
		mode = mode | RLENCO;

	long lImgDataSize = (tgahd.Height * tgahd.Width) * (tgahd.PixelDepth / 8);

	// Allocate the memory buffers
	pNew = malloc(lImgDataSize);
//	pNew = (LPVOID) theApp.m_TGABuffer.GetBuffer((size_t)(tgahd.Width * tgahd.Height * 4));

	if(pNew == NULL)
		{
		m_error = MEMERR;
		fclose(fp);
		return NULL;
		}
	else
		pRGB = (BYTE *)pNew;

	// RGB from image Data
	//DWORD  destOffset = 0;

	RLECount = 0;
	RLEFlag = 0;

//	//
//	// (re-)alocate a local image buffer to read the TGA formatted
//	// data into. this avoids the huge critical-section delays in
//	// every call to getc().
//	//
//	long lBufSize = lImgDataSize + 16; // slop
//	if(lBufSize < MAX_IMAGEREAD_BUFFER)
//		lBufSize = MAX_IMAGEREAD_BUFFER;
//	if(glImageReadBufferSize < lBufSize) 
//		{
//		if(gpImageReadBuffer)
//			{
//			free(gpImageReadBuffer);
//			gpImageReadBuffer = NULL; // tidy
//			gpImageReadBufPos = NULL;
//			}
//			
//		glImageReadBufferSize = lBufSize;
//		gpImageReadBuffer = (BYTE *) malloc(glImageReadBufferSize);
//		
//		if(!gpImageReadBuffer)
//			{
//			glImageReadBufferSize = 0;
//			return NULL; // v. bad news.
//			}
//		TRACE("* (Re-)Allocated local TGA data buffer: %d bytes\n", glImageReadBufferSize);
//		}

	//
	// Read the TGA format data into the local buffer
	//
	long lTGABytesRead = fread(pRGB, 1, lImgDataSize, fp);
	if(lTGABytesRead != lImgDataSize)
		{
//		ASSERT(0);
		//free(pNew);
		return NULL;
		}
		
	// Grab the image dimensions
	*width = tgahd.Width;
	*height = tgahd.Height;

	// Clean Up
	fclose(fp);
	m_error = IMGOK;
	return pNew;

///////////////
// all out...dorks didn't realize that TGA's memory format == DIBSections!
//////////////
#if 0 
	//
	// Read the TGA format data into the local buffer
	//
	long lTGABytesRead = fread(gpImageReadBuffer, 1, lImgDataSize, fp);
	if(lTGABytesRead != lImgDataSize)
		{
		ASSERT(0);
		return NULL;
		}

	gpImageReadBufPos = gpImageReadBuffer;

	// copy DWORDs instead of bytes...
	UINT32 * pPixel = (UINT32 *) pRGB; 
	UINT32 * pReadBufPixel = (UINT32 *) gpImageReadBufPos;
	
	for(UINT32 row = 0; row < tgahd.Height; row++)
		{
		for(UINT32 col = 0; col < tgahd.Width; col++)
			{

			// Reset RLE Counters
			BYTE  Red, Grn, Blu, Alp;
			TGA_GetPixelValue(&Red, &Grn, &Blu, &Alp, &gpImageReadBufPos, tgahd.PixelDepth, CColMap);
			
			// Invert if the image origin is in Bottom left
			if(TGA_Origin != 0)
				{  // Bottom Left Origin
				destOffset = ((tgahd.Height -1) -row) * tgahd.Width * 4 + col * 4;
				*(pRGB + destOffset + 0) = Red;
				*(pRGB + destOffset + 1) = Grn;
				*(pRGB + destOffset + 2) = Blu;
				*(pRGB + destOffset + 3) = Alp;
				}
			else
				{  // Top Left Origin
				*(pRGB + destOffset + 0) = Red;
				*(pRGB + destOffset + 1) = Grn;
				*(pRGB + destOffset + 2) = Blu;
				*(pRGB + destOffset + 3) = Alp;
				destOffset += 4;
				}
	#if 0 // even faster!
	//				Red = *(gpImageReadBufPos++);
	//				Grn = *(gpImageReadBufPos++);
	//				Blu = *(gpImageReadBufPos++);
	//				Alp = *(gpImageReadBufPos++);
	//				
	//				*(pRGB + destOffset + 0) = Red;
	//				*(pRGB + destOffset + 1) = Grn;
	//				*(pRGB + destOffset + 2) = Blu;
	//				*(pRGB + destOffset + 3) = Alp;
	//				destOffset += 4;

					//	TGAColorComponents	rgbaPixel;

					*(pPixel++) = *(pReadBufPixel++);
					
	//				BYTE * p = pRGB + destOffset;
	//				*(p++) = *(gpImageReadBufPos++);
	//				*(p++) = *(gpImageReadBufPos++);
	//				*(p++) = *(gpImageReadBufPos++);
	//				*(p++) = *(gpImageReadBufPos++); 
	//				destOffset += 4;
	#endif
			} // loop col
		} // loop row

	// Grab the image dimensions
	*width = tgahd.Width;
	*height = tgahd.Height;

	// Clean Up
	fclose(fp);
	m_error = IMGOK;
	return pNew;
#endif
	}


///////////////////////////////////////////////////////////////////////////////////
//		LoadTGA8Bit
//		Loads in an 8 Bit buffer and the color palette that is
//		associated with that buffer, if the image is 8 Bit, else
//		it sets global error to DEPTHMISMATCHERR
HGLOBAL
TGAFile::LoadTGA8Bit(const char * fileName, // Name of File
UINT32 * width, // Width in pixels
UINT32 * height, // Height
RGBQUAD * pal) // Palette of RGBQUADS
	{
	HGLOBAL  hNew = NULL;
	BYTE *    pRGB = NULL;
	BYTE     Alpha;

	TGAHEADER tgahd;

	BYTE  TGA_Origin = 0;

	// for safety
	*width = 0;
	*height = 0;

	// init
	m_error = IMGOK;

	// Init the file Header to all zeros
	ZeroMemory(&tgahd, sizeof(tgahd));

	// Init the Palette to all zeros
	ZeroMemory(pal, sizeof(pal));
	FILE * fp;
	fp = fopen(fileName, "rb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}
	else
		{
		// Read the TGA Header
		long  rc = fread(&tgahd, 1, sizeof(TGAHEADER), fp);

		if(rc != sizeof(TGAHEADER))
			{
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Check fo valid data in structure
		if(tgahd.PixelDepth> 8)
			{
			// Not an 8bit Image
			m_error = DEPTHMISMATCHERR;
			fclose(fp);
			return NULL;
			}

		// Anything other than the standard TGA types
		// and I quit
		switch(tgahd.ImageType)
			{
			case TGA_MAPRGBTYPE:
			case TGA_MAPENCODETYPE:
				break;

			default:
				m_error = DEPTHMISMATCHERR;
				fclose(fp);
				return NULL;
			}

		// Set the Color Mode
		if(tgahd.ImageType == TGA_RAWMONOTYPE)
			{
			mode = GREYSC;
			}
		else
			{
			mode = COLOUR;
			}

		// Read the ID Descriptor if present
		if(tgahd.IDLength != 0)
			{
			// Read the TGA Comments
			long  rc = fread(&TGA_ImageIDFeild, 1, tgahd.IDLength, fp);

			if(rc != tgahd.IDLength)
				{
				m_error = FILEREADERR;
				fclose(fp);
				return NULL;
				}
			}

		// Parse the Image Descriptor
		TGA_Attribute = (BYTE)(tgahd.ImageDescriptor & 0x0f);
		TGA_Origin    = (BYTE)((tgahd.ImageDescriptor & 0x20) / 32);

		// If present read the color map
		if(tgahd.ColorMapType != 0)
			{
			// Get the color map
			for(__int32 i = 0; i < (tgahd.CMapStart + tgahd.CMapLength); i++)
				{
				TGA_GetMapEntry(&pal[i].rgbRed, &pal[i].rgbGreen, &pal[i].rgbBlue, &Alpha, fp, tgahd.CMapDepth);
				}
			}
		else
			{
			m_error = INVALIDTGAERR;
			fclose(fp);
			return NULL;
			}

		// Check Run Length Encoding
		if((tgahd.ImageType == TGA_MAPENCODETYPE) || (tgahd.ImageType == TGA_RAWENCODETYPE) || (tgahd.ImageType == TGA_MONOENCODETYPE))
			mode = mode | RLENCO;

		// Allocate the memory buffers
		hNew = GlobalAlloc(GHND, tgahd.Width * tgahd.Height);

		if(hNew == NULL)
			{
			m_error = MEMERR;
			fclose(fp);
			return NULL;
			}
		else
			{
			pRGB = (BYTE *)GlobalLock(hNew);

			if(pRGB == NULL)
				{
				m_error = MEMERR;
				fclose(fp);
				return NULL;
				}
			}

		// RGB from image Data
		DWORD  destOffset = 0;

		RLECount = 0;
		RLEFlag = 0;

		for(UINT32 row = 0; row < tgahd.Height; row++)
			{
			for(UINT32 col = 0; col < tgahd.Width; col++)
				{
				BYTE  Red, Grn, Blu, Alp;

				// Reset RLE Counters
				TGA_GetPixelValue(&Red, &Grn, &Blu, &Alp, fp, tgahd.PixelDepth, pal);

				// Invert if the image origin is in Bottom left
				if(TGA_Origin == 0)
					{  // Bottom Left Origin
					*(pRGB + destOffset) = Red;
					destOffset = ((tgahd.Height -1) -row) * tgahd.Width + col;
					}
				else
					{  // Top Left Origin
					*(pRGB + destOffset) = Red;
					destOffset++;
					}
				}
			}
		}

	// Grab the image dimensions
	*width = tgahd.Width;
	*height = tgahd.Height;

	// Clean Up
	GlobalUnlock(hNew);
	fclose(fp);
	m_error = IMGOK;
	return hNew;
	}


///////////////////////////////////////////////////////////////////////////////////
//		LoadTGAThumbNail
//		Checks the TGA file for the existance of a thumbnail image
//		Reads and returns it in a 24 Bit RGB Buffer if a thumbnail
//		exists. Returns NULL if there isn't one sets TGANOTHUMBNAIL
HGLOBAL
TGAFile::LoadTGAThumbnail
	(
	const char * fileName,	// Name of file
	UINT32 * width,					// Width in Pixel
	UINT32 * height					// Height
	)
	{
	HGLOBAL  hNew = NULL;

	TGAHEADER tgahd;
	TGAFOOTER tgaft;
	TGAEXTENSION tgaext;

	BYTE  stampWidth = 0, stampHeight = 0;
	long  lResult;

	// for safety
	*width = 0;
	*height = 0;

	// init
	m_error = IMGOK;

	// Init the file structs
	ZeroMemory(&tgahd, sizeof(tgahd));
	ZeroMemory(&tgaft, sizeof(tgaft));
	ZeroMemory(&tgaext, sizeof(tgaext));
	FILE * fp;
	fp = fopen(fileName, "rb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}
	else
		{
		// Read the TGA Header
		long  rc = fread(&tgahd, 1, sizeof(TGAHEADER), fp);

		if(rc != sizeof(TGAHEADER))
			{
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Check fo valid data in structure
		if((tgahd.PixelDepth> 32) || (tgahd.PixelDepth<8))
			{
			// I don't do Pixel Depths Bigger than 32
			m_error = INVALIDTGAERR;
			fclose(fp);
			return NULL;
			}

		// Anything other than the standard TGA types
		// and I quit
		switch(tgahd.ImageType)
			{
			case TGA_MAPRGBTYPE:
			case TGA_RAWRGBTYPE:
			case TGA_RAWMONOTYPE:
			case TGA_MAPENCODETYPE:
			case TGA_RAWENCODETYPE:
			case TGA_MONOENCODETYPE:
				break;

			default:
				m_error = INVALIDTGAERR;
				fclose(fp);
				return NULL;
			}

		// Set the number of Color Planes
		if(tgahd.ImageType == TGA_RAWMONOTYPE)
			{
			mode = GREYSC;
			}
		else
			{
			mode = COLOUR;
			}

		// Check for file Version		
		// Seek the last 26 bytes of the file
		if(fseek(fp, -26, SEEK_END))
			{
			// Error Quit
			fclose(fp);
			return NULL;
			}

		// Read in the last 26 Bytes of the File
		lResult = fread(&tgaft, 1, sizeof(TGAFOOTER), fp);

		if(lResult != sizeof(TGAFOOTER))
			{
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Check for the Marker at the end of the file	
		lResult = strcmp(tgaft.Signature, "TRUEVISION-XFILE.");

		if(lResult != 0)
			{
			// Not V2.0 File no Thumbnail
			m_error = NOTGATHUMBNAIL;
			fclose(fp);
			return NULL;
			}

		// Check for the existance of an extension area
		if(tgaft.ExtensionOffset == 0)
			{
			// No Thumbnail in this file
			m_error = NOTGATHUMBNAIL;
			fclose(fp);
			return NULL;
			}

		// Seek the extension area
		if(fseek(fp, tgaft.ExtensionOffset, SEEK_SET))
			{
			// Error Quit
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Read in the last 26 Bytes of the File
		lResult = fread(&tgaext, 1, sizeof(TGAEXTENSION), fp);

		if(lResult != sizeof(TGAEXTENSION))
			{
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Seek the thumbnail image
		if(fseek(fp, tgaext.StampOffset, SEEK_SET))
			{
			// Error Quit
			m_error = FILEREADERR;
			fclose(fp);
			return NULL;
			}

		// Read the Width and Height from the first two bytes
		// of the postage stamp data.
		fread(&stampWidth, 1, 1, fp);
		fread(&stampHeight, 1, 1, fp);

		if((stampWidth <= 0) || (stampWidth> 64) || (stampHeight <= 0) || (stampHeight> 64))
			{
			m_error = INVALIDTGAERR;
			fclose(fp);
			return NULL;
			}
		}

	// Clean Up
	*width = stampWidth;
	*height = stampHeight;
	fclose(fp);

	// Return Okay Image
	return hNew;
	}


///////////////////////////////////////////////////////////////////////////////////
//		SaveTGA32
//		Saves the buffer as a 32 bit True Color Image in TGA format
BOOL
TGAFile::SaveTGA32
	(
	const char *	fileName, // output path
	BYTE *				inBuf,		// BGR buffer
	UINT32				width,		// size in pixels
	UINT32				height
	)
	{
	long  lResult = 0;

	TGAHEADER tgahd;
	m_error = IMGOK;

	// Init the file Header to all zeros
	ZeroMemory(&tgahd, sizeof(tgahd));

	if(inBuf == NULL)
		{
		m_error = BADPARAMERR;
		return FALSE;
		}

	if((width == 0) || (height == 0))
		{
		m_error = BADPARAMERR;
		return FALSE;
		}

	// Initialize the Header for the File
	tgahd.IDLength = 0;
	tgahd.ColorMapType = 0;
	tgahd.ImageType = TGA_RAWRGBTYPE;
	tgahd.CMapStart = 0;
	tgahd.CMapLength = 0;
	tgahd.CMapDepth = 0;
	tgahd.XOffset = 0;
	tgahd.YOffset = 0;
	tgahd.Width   = (WORD)width;
	tgahd.Height  = (WORD)height;
	tgahd.PixelDepth = 32;
	tgahd.ImageDescriptor = 0;

	// Open a file to write
	FILE * fp = fopen(fileName, "wb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}

	// Write the Header to File.
	if((lResult = fwrite(&tgahd, 1, sizeof(TGAHEADER), fp)) != 18)
		{
		fclose(fp);
		m_error = FILEWRITEERR;
		return FALSE;
		}

	// Wrte the Bytes to file
	DWORD  destOffset = 0;
	BYTE   temp = 0;
	DWORD  rowStride = tgahd.Width * 4;

	for(UINT32 row = 0; row < tgahd.Height; row++)
		{
		//DWORD rowOffset = rowStride * row;
		DWORD  rowOffset = rowStride *((tgahd.Height -1) -row);

		for(UINT32 col = 0; col < tgahd.Width; col++)
			{
			destOffset = rowOffset + 4 * col;
			temp = *(inBuf + destOffset + 2);

			if(fwrite(&temp, 1, 1, fp) != 1)
				{
				m_error = FILEWRITEERR;
				fclose(fp);
				return FALSE;
				}
			temp = *(inBuf + destOffset + 1);

			if(fwrite(&temp, 1, 1, fp) != 1)
				{
				m_error = FILEWRITEERR;
				fclose(fp);
				return FALSE;
				}
			temp = *(inBuf + destOffset + 0);

			if(fwrite(&temp, 1, 1, fp) != 1)
				{
				m_error = FILEWRITEERR;
				fclose(fp);
				return FALSE;
				}
				
			if(fwrite(&temp, 1, 1, fp) != 1)
				{
				m_error = FILEWRITEERR;
				fclose(fp);
				return FALSE;
				}
			}
		}

	// Cleanup
	fclose(fp);
	m_error = IMGOK;
	return TRUE;
	}


///////////////////////////////////////////////////////////////////////////////////
//		Save8BitTGA
//		Save's to an 8 Bit Color mapped file using the Palette 
//		passed in to the function.
BOOL
TGAFile::Save8BitTGA(const char * fileName, // output path
BYTE * inBuf, // one BYTE per pixel colomapped image
UINT32 width, // Width of Image
UINT32 height, // Height of Image
__int32 colors, // number of colors (number of RGBQUADs)
RGBQUAD * colormap) // array of RGBQUADs 
	{
	long  lResult = 0;

	TGAHEADER tgahd;

	// Init
	m_error = IMGOK;

	// Init the file Header to all zeros
	ZeroMemory(&tgahd, sizeof(tgahd));

	if(inBuf == NULL)
		{
		m_error = BADPARAMERR;
		return FALSE;
		}

	if((width == 0) || (height == 0))
		{
		m_error = BADPARAMERR;
		return FALSE;
		}

	if(colormap == NULL)
		{
		m_error = BADPARAMERR;
		return FALSE;
		}

	// Initialize the Header for the File
	tgahd.IDLength = 0;
	tgahd.ColorMapType = 1;
	tgahd.ImageType = TGA_MAPRGBTYPE;
	tgahd.CMapStart = 0;
	tgahd.CMapLength = (SHORT)colors;
	tgahd.CMapDepth = 24;
	tgahd.XOffset = 0;
	tgahd.YOffset = 0;
	tgahd.Width   = (WORD)width;
	tgahd.Height  = (WORD)height;
	tgahd.PixelDepth = 8;
	tgahd.ImageDescriptor = 0x28;

	// Open a file to write
	FILE * fp = fopen(fileName, "wb");

	if(fp == NULL)
		{
		m_error = FILEOPENERR;
		return FALSE;
		}

	// Write the Header to File.
	if((lResult = fwrite(&tgahd, 1, sizeof(TGAHEADER), fp)) != 18)
		{
		m_error = FILEWRITEERR;
		fclose(fp);
		return FALSE;
		}

	// Write out the Colormap
	for(__int32 i = 0; i < colors; i++)
		{
		putc(colormap[i].rgbBlue, fp);
		putc(colormap[i].rgbGreen, fp);
		putc(colormap[i].rgbRed, fp);
		}

	// Wrte the Bytes to file
	DWORD  destOffset = 0;
	BYTE   temp = 0;

	for(UINT32 row = 0; row < tgahd.Height; row++)
		{
		for(UINT32 col = 0; col < tgahd.Width; col++)
			{
			temp = *(inBuf + destOffset + 0);

			if(fwrite(&temp, 1, 1, fp) != 1)
				{
				m_error = FILEWRITEERR;
				fclose(fp);
				return FALSE;
				}
			destOffset += 1;
			}
		}

	// Cleanup
	fclose(fp);
	m_error = IMGOK;
	return TRUE;
	}


////////////////////////////////////////////////////////////////////////////////////
//		TGA_GetMapEntry
//		Get the Color Values out of the
//		Color map in the TGA File
//		Return 0 on Success
BOOL
TGAFile::TGA_GetMapEntry(BYTE * Red, BYTE * Green, BYTE * Blue, BYTE * Alpha, FILE * fp, UINT32 Depth)
	{
	UINT32  j, k, l;
	BYTE    i, r, g, b, a = 0;
	long    lResult;

	switch(Depth)
		{
		case 8:  // Greyscale Read and Triplicate
			lResult = fread(&i, 1, 1, fp);

			// Check for error
			if(lResult != 1)
				{
				m_error = FILEREADERR;
				return FALSE;
				}

			// Set RGB Values
			r = i;
			g = i;
			b = i;
			break;

		case 16:  // 5 bits each of Red, Green, and Blue

		case 15:  // Watch for the Byte order
			lResult = fread(&j, 1, 1, fp);
			lResult = lResult + fread(&k, 1, 1, fp);

			// Check for error
			if(lResult != 2)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			l = j + k * 256;
			b = (BYTE)(((l >> 10) & 31) << 3);
			g = (BYTE)(((l >> 5) & 31) << 3);
			r = (BYTE)((l & 31) << 3);
			break;

		case 32:  // Read the Alpha bit a Throw it away

		case 24:  // Eight bits for each Red, Green and Blue
			lResult = fread(&i, 1, 1, fp);
			r = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			g = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			b = i;

			// Check for error
			if(lResult != 3)
				{
				m_error = FILEREADERR;
				return FALSE;
				}

			if(Depth == 32)
				{
				lResult = fread(&i, 1, 1, fp);

				if(lResult != 1)
					{
					m_error = FILEREADERR;
					return FALSE;
					}

				// Stroe Alpha bit
				a = i;
				}
			break;

		default:
			// Some Other Pixel Depth Which I don't support
			return FALSE;
		}
	*Red = r;
	*Green = g;
	*Blue = b;
	*Alpha = a;

	// Reutrn No Error
	return TRUE;
	}


////////////////////////////////////////////////////////////////////////////////////
//		TGA_GetFileVersion
//		Retrieves the Version of the TGA File
//		BYTES 8-23 of a Version 2.0 Footer will be equal 
//		to "TRUEVISION-XFILE" as ASCII
//		Returns - Version number 1 or 2
__int32
TGAFile::TGA_GetFileVersion(FILE * fp)
	{
	long    result;
	fpos_t  pos;

	TGAFOOTER tgaft;

	// Save the Current position of the File Stream
	if(fgetpos(fp, &pos))
		{
		// Error Quit
		return FILEREADERR;
		}

	// Seek the last 26 bytes of the file
	if(fseek(fp, -26, SEEK_END))
		{
		// Error Quit
		return FILEREADERR;
		}

	// Read in the last 26 Bytes of the File
	result = fread(&tgaft, 1, sizeof(TGAFOOTER), fp);

	if(result != sizeof(TGAFOOTER))
		{
		m_error = FILEREADERR;
		return FILEREADERR;
		}

	// Return the File Stream to its initial position
	if(fsetpos(fp, &pos))
		{
		// Error Quit
		return FILEREADERR;
		}

	// Check for the Marker at the end of the file	
	if(!strcspn(tgaft.Signature, "TRUEVISION-XFILE"))
		{
		// Marker found its V2.0 TGA
		return TGA_VERSIONTWO;
		}

	// No Marker was found Assume V1.0 TGA
	return TGA_VERSIONONE;
	}


////////////////////////////////////////////////////////////////////////////////////
//		TGA_getPixelValue
//		Retreve a pixel value from the buffer and parse
//		the value if its RLE encoded. Returns the RGB
//		value of the pixel.
//		Retruns - TRUE on success
BOOL
TGAFile::TGA_GetPixelValue
	(
	BYTE * rRed, 
	BYTE * rGrn, 
	BYTE * rBlu, 
	BYTE * rAlp, 
	BYTE ** ppTGAData, 
	UINT32 PixelDepth, 
	RGBQUAD * CColMap
	)
	{
	//
	// Buffered TGAs are always 32-bit,
	// so go direct from file to RGBA
	//
	*rRed = *((*ppTGAData)++);
	*rGrn = *((*ppTGAData)++);
	*rBlu = *((*ppTGAData)++);
	*rAlp = *((*ppTGAData)++);
	
	return TRUE;
	}

////////////////////////////////////////////////////////////////////////////////////
//		TGA_getPixelValue
//		Retreve a pixel value from the file and parse
//		the value if its RLE encoded. Returns the RGB
//		value of the pixel.
//		Retruns - TRUE on success
BOOL
TGAFile::TGA_GetPixelValue(BYTE * rRed, BYTE * rGrn, BYTE * rBlu, BYTE * rAlp, FILE * fp, UINT32 PixelDepth, RGBQUAD * CColMap)
	{
	BYTE  i, j, k;
	long  lResult;

	// Check for Run Length Encoding
	if((mode & RLENCO) != 0)
		{
		if(RLECount == 0)
			{  // Restrat the rum
			lResult = fread(&i, 1, 1, fp);

			if(lResult != 1)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			RLEFlag = (i & 0x80) >> 7;

			if(RLEFlag == 0)
				{  // Stream of unencoded pixels
				RLECount = i + 1;
				}
			else
				{  // Single Pixel Replicated
				RLECount = i-127;
				}
			RLECount--;  // ecrement count and get pixel
			}
		else
			{
			// I have already read the count and at least the first pixel
			RLECount--;

			if(RLEFlag != 0)
				{
				// Replicated Pixels
				goto PixelEncode;
				}
			}
		}

	// Rea the appropiate number of BYTES and break into RGB
	switch(PixelDepth)
		{
		case 8:  // Greyscale Read 1 Byte and Triplicate
			lResult = fread(&i, 1, 1, fp);

			if(lResult != 1)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			Red = i;
			Grn = i;
			Blu = i;
			l = i;
			break;

		case 16:  // 1 Bit alpha not used

		case 15:  // Five bits each for RGB watch byte ordering
			lResult = fread(&j, 1, 1, fp);
			lResult = lResult + fread(&k, 1, 1, fp);

			// Check for error
			if(lResult != 2)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			l = j + k * 256;
			Blu = (BYTE)(((l >> 10) & 31) << 3);
			Grn = (BYTE)(((l >> 5) & 31) << 3);
			Red = (BYTE)((l & 31) << 3);
			break;

		case 24:  // Eight bits each for RGB
			lResult = fread(&i, 1, 1, fp);
			Red = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			Grn = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			Blu = i;

			// opaque alpha (08jan00/bgw)
			Alpha = 0xFF;

			// Check for error
			if(lResult != 3)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			break;
			
		case 32:  // With alpha (08jan00/bgw)
			lResult = fread(&i, 1, 1, fp);
			Red = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			Grn = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			Blu = i;
			lResult = lResult + fread(&i, 1, 1, fp);
			Alpha = i;

			// Check for error
			if(lResult != 4)
				{
				m_error = FILEREADERR;
				return FALSE;
				}
			break;

		default:  // Unknown number of bis per pixel
			m_error = INVALIDTGAERR;
			return NULL;
		}
		
PixelEncode:  // Set the actual pixel values

	if((mode & MAPPED) == MAPPED)
		{
		// Remap Color Mapped Pixels
		*rRed =	CColMap[l].rgbRed;
		*rGrn = CColMap[l].rgbGreen;
		*rBlu = CColMap[l].rgbBlue;
		*rAlp = 0xFF; // opaque always (08jan00/bgw)
		}
	else
		{
		// Set Unmapped Values
		*rRed = Red;
		*rGrn = Grn;
		*rBlu = Blu;
		*rAlp = Alpha;
		}
	return TRUE;
	}

extern "C" unsigned char * LoadTGAFile
(
	const char * filename,
	int * width,
	int * height
)
{
	TGAFile tgaFile;
	return (unsigned char *)tgaFile.LoadTGA(filename, (UINT32 *)width, (UINT32 *)height);
}