#include <xtl.h>
#include "app.h"
#include <stdio.h>
#include <direct.h>
#include <string>
using namespace std;
extern IDirect3DTexture8 *TexScreen;
extern IDirect3DTexture8 *TexScreenShot;
// Based on:

extern "C" int getPitch();
extern "C" void screenShotTexture();
extern int FileMenuSelected;
extern int screenShotSlot;
#include <vector>
using namespace std;
extern std::string ARTWORK_SHOTS_1_PATH;
extern std::string ARTWORK_SHOTS_2_PATH;
extern std::string ARTWORK_SHOTS_3_PATH;
extern std::string ARTWORK_SHOTS_4_PATH ;
extern std::string ARTWORK_SHOTS_5_PATH; 
extern std::string ARTWORK_SHOTS_6_PATH; 
extern std::string ARTWORK_SHOTS_7_PATH; 
extern std::string ARTWORK_SHOTS_8_PATH; 
struct fileDisplay {
	string name;
	string path;
	bool isAGame;
	bool isARoot;
	bool isADirectory;
	bool topLevel;
	int soundTrack;
	int song;
	int archive;

};
extern vector<fileDisplay> fileList;
extern void changePreview();
extern void updateZipFilename();
extern unsigned char leftAnalog;
extern unsigned char rightAnalog;
extern float scrollSpeed;
extern double slow;
extern unsigned char savePartition;


class FileMenu
{
public:
  FileMenu();
  int init();
  int scan();
  void exit();
  int render();
  int scroll(int amount);
  int getFilePath(char *name);

private:
  int nameReset();
  int nameFind(char *path);
  int nameAdd(char *entry);
  int nameSizeUp();
  int nameOffset(int index);

  char currentPath[260];
  char *nameList;
  int nameSize,nameMax;
  int nameCount;

  int choiceFocus;
};

extern FileMenu FileMenu;
/*---------------------------------------------------------------------------

   wpng - simple PNG-writing program                             writepng.c

  ---------------------------------------------------------------------------

      Copyright (c) 1998-2000 Greg Roelofs.  All rights reserved.

      This software is provided "as is," without warranty of any kind,
      express or implied.  In no event shall the author or contributors
      be held liable for any damages arising in any way from the use of
      this software.

      Permission is granted to anyone to use this software for any purpose,
      including commercial applications, and to alter it and redistribute
      it freely, subject to the following restrictions:

      1. Redistributions of source code must retain the above copyright
         notice, disclaimer, and this list of conditions.
      2. Redistributions in binary form must reproduce the above copyright
         notice, disclaimer, and this list of conditions in the documenta-
         tion and/or other materials provided with the distribution.
      3. All advertising materials mentioning features or use of this
         software must display the following acknowledgment:

            This product includes software developed by Greg Roelofs
            and contributors for the book, "PNG: The Definitive Guide,"
            published by O'Reilly and Associates.

  ---------------------------------------------------------------------------*/


#include <stdlib.h>     /* for exit() prototype */

#include "png.h"        /* libpng header; includes zlib.h and setjmp.h */
#include "SourceCode.h"   /* typedefs, common macros, public prototypes */


/* local prototype */

static void writepng_error_handler(png_structp png_ptr, png_const_charp msg) {}



void writepng_version_info(void)
{
  //fprintf(stderr, "   Compiled with libpng %s; using libpng %s.\n",
//    PNG_LIBPNG_VER_STRING, png_libpng_ver);
//  fprintf(stderr, "   Compiled with zlib %s; using zlib %s.\n",
    //ZLIB_VERSION, zlib_version);
}



static void
png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
   png_uint_32 check;

   check = fwrite(data, 1, length, (FILE *)(png_ptr->io_ptr));
   if (check != length)
   {
      png_error(png_ptr, "Write Error");
   }
}
/* returns 0 for success, 2 for libpng problem, 4 for out of memory, 11 for
 *  unexpected pnmtype; note that outfile might be stdout */

int writepng_init(mainprog_info *mainprog_ptr)
{
    png_structp  png_ptr;       /* note:  temporary variables! */
    png_infop  info_ptr;
    int color_type, interlace_type;


    /* could also replace libpng warning-handler (final NULL), but no need: */

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
      writepng_error_handler, NULL);
    if (!png_ptr)
        return 4;   /* out of memory */

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        png_destroy_write_struct(&png_ptr, NULL);
        return 4;   /* out of memory */
    }


    /* setjmp() must be called in every function that calls a PNG-writing
     * libpng function, unless an alternate error handler was installed--
     * but compatible error handlers must either use longjmp() themselves
     * (as in this program) or exit immediately, so here we go: */


    if (setjmp(mainprog_ptr->jmpbuf)) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        return 2;
    }


    /* make sure outfile is (re)opened in BINARY mode */

    //png_init_io(png_ptr, mainprog_ptr->outfile);

	png_ptr->io_ptr = (png_voidp)mainprog_ptr->outfile ;
	png_ptr->write_data_fn = png_default_write_data ;

    /* set the compression levels--in general, always want to leave filtering
     * turned on (except for palette images) and allow all of the filters,
     * which is the default; want 32K zlib window, unless entire image buffer
     * is 16K or smaller (unknown here)--also the default; usually want max
     * compression (NOT the default); and remaining compression flags should
     * be left alone */

    png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
    >> this is default for no filtering; Z_FILTERED is default otherwise:
    png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
    >> these are all defaults:
    png_set_compression_mem_level(png_ptr, 8);
    png_set_compression_window_bits(png_ptr, 15);
    png_set_compression_method(png_ptr, 8);
 */


    /* set the image parameters appropriately */

	if (mainprog_ptr->bpp == 24)
		color_type = PNG_COLOR_TYPE_RGB;
    else if (mainprog_ptr->bpp == 32)
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;
    else {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        return 11;
    }

    interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
                                               PNG_INTERLACE_NONE;

    png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
      mainprog_ptr->sample_depth, color_type, interlace_type,
      PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

    if (mainprog_ptr->gamma > 0.0)
        png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);

/*
    if (mainprog_ptr->have_bg) {   /* we know it's RGBA, not gray+alpha 
        png_color_16  background;

        background.red = mainprog_ptr->bg_red;
        background.green = mainprog_ptr->bg_green;
        background.blue = mainprog_ptr->bg_blue;
        png_set_bKGD(png_ptr, info_ptr, &background);
    }
    if (mainprog_ptr->have_time) {
        png_time  modtime;

        png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
        png_set_tIME(png_ptr, info_ptr, &modtime);
    }

    if (mainprog_ptr->have_text) {
        png_text  text[6];
        int  num_text = 0;

        if (mainprog_ptr->have_text & TEXT_TITLE) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "Title";
            text[num_text].text = mainprog_ptr->title;
            ++num_text;
        }
        if (mainprog_ptr->have_text & TEXT_AUTHOR) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "Author";
            text[num_text].text = mainprog_ptr->author;
            ++num_text;
        }
        if (mainprog_ptr->have_text & TEXT_DESC) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "Description";
            text[num_text].text = mainprog_ptr->desc;
            ++num_text;
        }
        if (mainprog_ptr->have_text & TEXT_COPY) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "Copyright";
            text[num_text].text = mainprog_ptr->copyright;
            ++num_text;
        }
        if (mainprog_ptr->have_text & TEXT_EMAIL) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "E-mail";
            text[num_text].text = mainprog_ptr->email;
            ++num_text;
        }
        if (mainprog_ptr->have_text & TEXT_URL) {
            text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
            text[num_text].key = "URL";
            text[num_text].text = mainprog_ptr->url;
            ++num_text;
        }
        png_set_text(png_ptr, info_ptr, text, num_text);
    }
*/

    /* write all chunks up to (but not including) first IDAT */

    png_write_info(png_ptr, info_ptr);


    /* if we wanted to write any more text info *after* the image data, we
     * would set up text struct(s) here and call png_set_text() again, with
     * just the new data; png_set_tIME() could also go here, but it would
     * have no effect since we already called it above (only one tIME chunk
     * allowed) */


    /* set up the transformations:  for now, just pack low-bit-depth pixels
     * into bytes (one, two or four pixels per byte) */

    png_set_packing(png_ptr);
/*  png_set_shift(png_ptr, &sig_bit);  to scale low-bit-depth values */


    /* make sure we save our pointers for use in writepng_encode_image() */

    mainprog_ptr->png_ptr = png_ptr;
    mainprog_ptr->info_ptr = info_ptr;


    /* OK, that's all we need to do for now; return happy */

    return 0;
}





/* returns 0 for success, 2 for libpng (longjmp) problem */

int writepng_encode_image(mainprog_info *mainprog_ptr)
{
    png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
    png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;


    /* as always, setjmp() must be called in every function that calls a
     * PNG-writing libpng function */

    if (setjmp(mainprog_ptr->jmpbuf)) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        mainprog_ptr->png_ptr = NULL;
        mainprog_ptr->info_ptr = NULL;
        return 2;
    }


    /* and now we just write the whole image; libpng takes care of interlacing
     * for us */

    png_write_image(png_ptr, mainprog_ptr->row_pointers);


    /* since that's it, we also close out the end of the PNG file now--if we
     * had any text or time info to write after the IDATs, second argument
     * would be info_ptr, but we optimize slightly by sending NULL pointer: */

    png_write_end(png_ptr, NULL);

    return 0;
}





/* returns 0 if succeeds, 2 if libpng problem */

int writepng_encode_row(mainprog_info *mainprog_ptr)  /* NON-interlaced only! */
{
    png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
    png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;


    /* as always, setjmp() must be called in every function that calls a
     * PNG-writing libpng function */

    if (setjmp(mainprog_ptr->jmpbuf)) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        mainprog_ptr->png_ptr = NULL;
        mainprog_ptr->info_ptr = NULL;
        return 2;
    }


    /* image_data points at our one row of image data */

    png_write_row(png_ptr, mainprog_ptr->image_data);

    return 0;
}





/* returns 0 if succeeds, 2 if libpng problem */

int writepng_encode_finish(mainprog_info *mainprog_ptr)   /* NON-interlaced! */
{
    png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
    png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;


    /* as always, setjmp() must be called in every function that calls a
     * PNG-writing libpng function */

    if (setjmp(mainprog_ptr->jmpbuf)) {
        png_destroy_write_struct(&png_ptr, &info_ptr);
        mainprog_ptr->png_ptr = NULL;
        mainprog_ptr->info_ptr = NULL;
        return 2;
    }


    /* close out PNG file; if we had any text or time info to write after
     * the IDATs, second argument would be info_ptr: */

    png_write_end(png_ptr, NULL);

    return 0;
}

void writepng_cleanup(mainprog_info *mainprog_ptr)
{
    png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr;
    png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;
  
    if (png_ptr && info_ptr)
        png_destroy_write_struct(&png_ptr, &info_ptr);
}

#define unsigned char unsigned char;

int HighRes = 0;
extern int commandLineLaunch;

extern char commandLinePath[1024];

void xboxScreenshot() 
{
	////dprintf("ScreenShot Start\n");
	mainprog_info wpng_info;
//	int maxnum = 0 ;
	memset( &wpng_info, 0, sizeof( wpng_info ) ) ;

	long w = 256;
	long h = 224;
	if(HighRes == 1) {
		w = 512;
		h = 448;
	}
	wpng_info.width =  w;
	wpng_info.height = h;

	wpng_info.sample_depth = 8;

	wpng_info.bpp = 24 ;

	wpng_info.outfile = NULL;
	wpng_info.image_data = NULL;
	wpng_info.row_pointers = NULL;
	wpng_info.interlaced = false;
	wpng_info.have_bg = false;
	wpng_info.have_time = false;
	wpng_info.have_text = 0;
	wpng_info.gamma = 1.0;


	/*
	std::string t = "E:\\ZsnexBox\\prev";
	t[0] = savePartition;
	mkdir(t.c_str());
	
	
	if(commandLineLaunch == 1) {
		for(int i = 0; i < 1024; i++) {
			if(commandLinePath[i] == '\0') {
				fileList[FileMenuSelected].path[i] = '\0';
				break;
			}
			else {
				fileList[FileMenuSelected].path[i] = commandLinePath[i];
			}
		}
	}
	else {
		
	}
	uch gfnames[260];
	gfnames[0] = savePartition;
	gfnames[1] = savePartition;
	gfnames[2] = ':';
	gfnames[3] = '\\';
	gfnames[4] = 'Z';
	gfnames[5] = 's';
	gfnames[6] = 'n';
	gfnames[7] = 'e';
	gfnames[8] = 'x';
	gfnames[9] = 'B';
	gfnames[10] = 'o';
	gfnames[11] = 'x';

	gfnames[12] = '\\';
	gfnames[13] = 'p';
	gfnames[14] = 'r';
	gfnames[15] = 'e';
	gfnames[16] = 'v';
	gfnames[17] = '\\';

	//D:\Games\Game.zip
	//D:Game.zip
	int lastB = 0;
	int i0 = 0;
	for(i0 = 0; i0 < 260; i0++) {
		if(fileList[FileMenuSelected].path[i0] == '\0') {
			if(lastB == 0) {
				for(int q = 18; q < 260; q++) {
					gfnames[q] = fileList[FileMenuSelected].path[(q - 18) + 2];

					if(fileList[FileMenuSelected].path[(q - 18) + 2] == '\0') {
						gfnames[q] = '\0';
						gfnames[q-1] = 'g';
						gfnames[q-2] = 'n';
						gfnames[q-3] = 'p';
						break;
					}
				}
				break;
			}
			else {
				for(int q = 18; q < 260; q++) {
					gfnames[q] = fileList[FileMenuSelected].path[lastB + 1 + (q - 18)];

					//D:\Games\a.zip
					if(fileList[FileMenuSelected].path[lastB + 1 + (q - 18)] == '\0') {
						gfnames[q] = '\0';
						gfnames[q-1] = 'g';
						gfnames[q-2] = 'n';
						gfnames[q-3] = 'p';
						////dprintf("gfnames First: %s\n", gfnames);
						break;
					}
				}
				break;
			}
		}

		if(fileList[FileMenuSelected].path[i0] == '\\') lastB = i0;
	}
	*/

	std::string a =  fileList[FileMenuSelected].name;
	////dprintf("Original name: %s\n", a.c_str());
	std::string ext = ".zip"; 
	int r = a.find(".zip", 0);
	if(r == string::npos) { ext = ".smc"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".sfc"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".swc"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".fig"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".mgd"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".ufo"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".bin"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".058"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".078"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".usa"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".eur"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".jap"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".SMC"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".SFC"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".SWC"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".FIG"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".MGD"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".UFO"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".BIN"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".058"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".078"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".USA"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".EUR"; r = a.find(ext, 0);}
	if(r == string::npos) { ext = ".JAP"; r = a.find(ext, 0);}
	if(r == string::npos) return;
	
	std::string b = a.substr(0, r);
	std::string c;
	std::string imagePath;

	ext = ".png";
	if(screenShotSlot == 1) { 
		c = b + ext ;
		imagePath = ARTWORK_SHOTS_1_PATH + c;
	}
	else if(screenShotSlot == 2) { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_2_PATH + c;
	}
	else if(screenShotSlot == 3) { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_3_PATH + c;
	}
	else if(screenShotSlot == 4) { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_4_PATH + c;
	}
	else if(screenShotSlot == 5) { 
	    c = b + ext ; 
		imagePath = ARTWORK_SHOTS_5_PATH + c;
	}
	else if(screenShotSlot == 6) { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_6_PATH + c;
	}
	else if(screenShotSlot == 7) { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_7_PATH + c;
	}
	else { 
		c = b + ext ; 
		imagePath = ARTWORK_SHOTS_8_PATH + c;
	}


    /* open the output file, or register an error and abort */
	if ((wpng_info.outfile = fopen( imagePath.c_str(), "wb") ) == NULL)
	{
		////dprintf("Error creating screenshot.png\n");
		return ;
    }
	
	// allocate libpng stuff, initialize transformations, write pre-IDAT data
	int rc ;
	if ((rc=writepng_init(&wpng_info)) != 0)
	{
		////dprintf("Error creating rc\n");
		fclose( wpng_info.outfile )  ;
		return ; 
    }
	
//	long j;
	
	wpng_info.image_data = (uch*)malloc( (wpng_info.bpp/8) * wpng_info.width);
		
	if (wpng_info.image_data == NULL)
	{
		//writepng_cleanup(&wpng_info);
		////dprintf("Image data = NULL\n");
		fclose( wpng_info.outfile )  ;
		return ; 
	}
		
	ush* data;
	RECT rectSource;
	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = 480-1 ;
	rectSource.right  = 640-1 ;

	if(HighRes == 0) {
		screenShotTexture();
	}

   D3DLOCKED_RECT d3dlr;
	if(HighRes == 0) {
	   TexScreenShot->LockRect(0, &d3dlr, &rectSource, 0);
	}
	else {
	   TexScreen->LockRect(0, &d3dlr, &rectSource, 0);
	}
		
	// Lock the rect in our texture
	
	//TexScreen->LockRect( 0, &d3dlr, 0, 0L );

	data = (ush*)d3dlr.pBits;
	
	
	if(HighRes == 0) {
		data += (((getPitch())/2) * (8+4));
	}
	else {
		data += (((getPitch())/2) * (16+6));
	}

	ush pixel ;
		
	for (int j = 0; j < wpng_info.height;  j++)
	{
		//////dprintf("%d, "j);
		uch* img_data = (uch*)wpng_info.image_data;
		ush *wdata = data;

		int i=0;

		for ( i = 0 ; i < wpng_info.width; i++ )
		{
			if(HighRes == 0) {
				pixel = wdata[i+32] ;//r5g6b5  r1111 1000 0000 0000, g0000 0111 1110 0000
			}
			else {
				pixel = wdata[i+64] ;
			}
			img_data[2] = (pixel<<3) & 0xFF ;
			img_data[1] = ((pixel>>5)<<2) & 0xFF ;
			img_data[0] = ((pixel>>11)<<3) & 0xFF ;

			img_data += 3 ;
		}

		data += ((getPitch())/2);// xbox_get_pitch();
			
		if( writepng_encode_row(&wpng_info) != 0)
		{
			//writepng_cleanup(&wpng_info);
			free(wpng_info.image_data) ;
			fclose( wpng_info.outfile )  ;
			if(HighRes == 0) {
			   TexScreenShot->UnlockRect(0) ;
			}
			else {
			   TexScreen->UnlockRect(0) ;
			}
			   return ; 
		}
	}
	if(HighRes == 0) {
		TexScreenShot->UnlockRect(0) ;
	}
	else {
	    TexScreen->UnlockRect(0) ;
	}
	
	if (writepng_encode_finish(&wpng_info) != 0)
	{
		//writepng_cleanup(&wpng_info);
		free(wpng_info.image_data) ;
		fclose( wpng_info.outfile )  ;
		return ;
	}
	
	/* OK, we're done (successfully):  clean up all resources and quit */

	writepng_cleanup(&wpng_info);
	free(wpng_info.image_data) ;
	fclose( wpng_info.outfile )  ;
	////dprintf("End of screenShot save\n");

	
	//sprintf( global_error_message, "%s", scr_filename) ;
	//m_msgDelay = 120 ;
}


void xboxScreenshotState(const char* filename) 
{
	////dprintf("State ScreenShot Start: %s\n", filename);
	mainprog_info wpng_info;
//	int maxnum = 0 ;
	memset( &wpng_info, 0, sizeof( wpng_info ) ) ;

	long w = 256;
	long h = 224;
	
	w = 512;
	h = 448;
	
	wpng_info.width =  w;
	wpng_info.height = h;

	wpng_info.sample_depth = 8;

	wpng_info.bpp = 24 ;

	wpng_info.outfile = NULL;
	wpng_info.image_data = NULL;
	wpng_info.row_pointers = NULL;
	wpng_info.interlaced = false;
	wpng_info.have_bg = false;
	wpng_info.have_time = false;
	wpng_info.have_text = 0;
	wpng_info.gamma = 1.0;


    /* open the output file, or register an error and abort */
	if ((wpng_info.outfile = fopen( (const char*)filename, "wb") ) == NULL)
	{
		////dprintf("Error creating State screenshot.png\n");
		return ;
    }
	
	// allocate libpng stuff, initialize transformations, write pre-IDAT data
	int rc ;
	if ((rc=writepng_init(&wpng_info)) != 0)
	{
		////dprintf("Error creating rc\n");
		fclose( wpng_info.outfile )  ;
		return ; 
    }
	
//	long j;
	
	wpng_info.image_data = (uch*)malloc( (wpng_info.bpp/8) * wpng_info.width);
		
	if (wpng_info.image_data == NULL)
	{
		//writepng_cleanup(&wpng_info);
		////dprintf("Image data = NULL\n");
		fclose( wpng_info.outfile )  ;
		return ; 
	}
		
	ush* data;
	RECT rectSource;
	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = 480-1 ;
	rectSource.right  = 640-1 ;

    D3DLOCKED_RECT d3dlr;
	TexScreen->LockRect(0, &d3dlr, &rectSource, 0);

	data = (ush*)d3dlr.pBits;
	
	data += (((getPitch())/2) * (16+6));
	

	ush pixel ;
		
	for (int j = 0; j < wpng_info.height;  j++)
	{
		//////dprintf("%d, "j);
		uch* img_data = (uch*)wpng_info.image_data;
		ush *wdata = data;

		int i=0;

		for ( i = 0 ; i < wpng_info.width; i++ )
		{
			
			pixel = wdata[i+64] ;
			
			img_data[2] = (pixel<<3) & 0xFF ;
			img_data[1] = ((pixel>>5)<<2) & 0xFF ;
			img_data[0] = ((pixel>>11)<<3) & 0xFF ;

			img_data += 3 ;
		}

		data += ((getPitch())/2);// xbox_get_pitch();
			
		if( writepng_encode_row(&wpng_info) != 0)
		{
			//writepng_cleanup(&wpng_info);
			free(wpng_info.image_data) ;
			fclose( wpng_info.outfile )  ;
			if(HighRes == 0) {
			   TexScreenShot->UnlockRect(0) ;
			}
			else {
			   TexScreen->UnlockRect(0) ;
			}
			   return ; 
		}
	}
	
	TexScreen->UnlockRect(0) ;
	
	
	if (writepng_encode_finish(&wpng_info) != 0)
	{
		//writepng_cleanup(&wpng_info);
		free(wpng_info.image_data) ;
		fclose( wpng_info.outfile )  ;
		return ;
	}
	
	writepng_cleanup(&wpng_info);
	free(wpng_info.image_data) ;
	fclose( wpng_info.outfile )  ;
	////dprintf("End of screenShot save\n");
}