/*******************************************************************************/

#include "PKR3EditorFrm.h"

////Header Include Start
#include "Images/Self_PKR3EditorFrm_XPM.xpm"
////Header Include End

/*******************************************************************************/

////Event Table Start
BEGIN_EVENT_TABLE(PKR3EditorFrm,wxFrame)
	////Manual Code Start
	////Manual Code End
	
	EVT_CLOSE(PKR3EditorFrm::OnClose)
	EVT_BUTTON(ID_BTNOPENDATA,PKR3EditorFrm::BTNOpenDataClick)
	EVT_BUTTON(ID_BTNSAVEFILE,PKR3EditorFrm::BTNSaveFileClick)
	EVT_BUTTON(ID_BTNDELETE,PKR3EditorFrm::BTNDeleteClick)
	EVT_BUTTON(ID_BTNADD,PKR3EditorFrm::BTNAddClick)
	EVT_BUTTON(ID_BTNEXPORT,PKR3EditorFrm::BTNExportClick)
	EVT_BUTTON(ID_BTNIMPORT,PKR3EditorFrm::BTNImportClick)
	EVT_BUTTON(ID_BTNPREVIEW,PKR3EditorFrm::BTNPreviewClick)
	EVT_LISTBOX(ID_LSTFILES,PKR3EditorFrm::LSTFilesSelected)
	EVT_LISTBOX_DCLICK(ID_LSTFILES,PKR3EditorFrm::LSTFilesDoubleClicked)
	EVT_LISTBOX(ID_LSTDIRS,PKR3EditorFrm::LSTDirsSelected)
END_EVENT_TABLE()
////Event Table End

/*******************************************************************************/

PKR3EditorFrm::PKR3EditorFrm(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)
: wxFrame(parent, id, title, position, size, style)
{
	CreateGUIControls();
	HTMLBmp -> Show(false);
	EDTTxt -> Show(false);
	BTNPreview -> Enable(false);
	dir = NULL;
	file = NULL;
	exfile = NULL;
	dirs_n = 0;
	files_n = 0;
	aux = 0;
	saux = 0;
	Str = "";
	EDTConsole -> AppendText("Program initialized...");
}

/*******************************************************************************/

PKR3EditorFrm::~PKR3EditorFrm()
{
	for(unsigned short x = 0; x < files_n; x++)
	{
        delete[] file[x].fdata;
        file[x].fdata = NULL;
    }
    delete[] dir;
    delete[] file;
}

/*******************************************************************************/

void PKR3EditorFrm::CreateGUIControls()
{
	////GUI Items Creation Start

	DLGAddBad =  new wxMessageDialog(this, wxT("Internal PKR3 file name must have 0 to 31 characters."), wxT("Invalid Name!"), wxICON_EXCLAMATION);

	DLGAddName =  new wxTextEntryDialog( this,wxT(""), wxT("Enter PKR3 file internal name:"), wxT("") ,wxOK | wxCANCEL | wxCENTRE);

	DLGSaveFile =  new wxFileDialog(this, wxT("Choose destination file:"), wxT(""), wxT(""), wxT("*.pkr"), wxSAVE);

	DLGImport =  new wxFileDialog(this, wxT("Choose a file to import:"), wxT(""), wxT(""), wxT("*.*"), wxOPEN);

	DLGExport =  new wxFileDialog(this, wxT("Choose destination file:"), wxT(""), wxT(""), wxT("*.*"), wxSAVE);

	DLGCaution =  new wxMessageDialog(this, wxT("You are going to overwrite a compressed file with an uncompressed file, do this at your own risk!\n(Note: this program can't import compressed files so this is the only way to overwrite this file)"), wxT("Caution!"), wxICON_EXCLAMATION);

	DLGOpenDataPkr =  new wxFileDialog(this, wxT("Choose a MHPB Pkr3 file:"), wxT(""), wxT(""), wxT("*.pkr"), wxOPEN);

	EDTTxt = new wxTextCtrl(this, ID_EDTTXT, wxT(""), wxPoint(267, 138), wxSize(524, 120), wxTE_READONLY | wxTE_MULTILINE, wxDefaultValidator, wxT("EDTTxt"));

	HTMLBmp = new wxHtmlWindow(this, ID_HTMLBMP, wxPoint(265, 0), wxSize(525, 402));

	CHKPreview = new wxCheckBox(this, ID_CHKPREVIEW, wxT("Always Preview Compressed BMP"), wxPoint(0, 555), wxSize(186, 17), 0, wxDefaultValidator, wxT("CHKPreview"));

	BTNOpenData = new wxButton(this, ID_BTNOPENDATA, wxT("Open PKR3"), wxPoint(0, 0), wxSize(120, 20), 0, wxDefaultValidator, wxT("BTNOpenData"));

	BTNSaveFile = new wxButton(this, ID_BTNSAVEFILE, wxT("Save PKR3"), wxPoint(0, 21), wxSize(120, 20), 0, wxDefaultValidator, wxT("BTNSaveFile"));
	BTNSaveFile->Enable(false);

	BTNDelete = new wxButton(this, ID_BTNDELETE, wxT("Delete File"), wxPoint(156, 526), wxSize(108, 25), 0, wxDefaultValidator, wxT("BTNDelete"));
	BTNDelete->Enable(false);

	BTNAdd = new wxButton(this, ID_BTNADD, wxT("Add File"), wxPoint(156, 499), wxSize(108, 25), 0, wxDefaultValidator, wxT("BTNAdd"));
	BTNAdd->Enable(false);

	BTNExport = new wxButton(this, ID_BTNEXPORT, wxT("Export File"), wxPoint(0, 499), wxSize(76, 25), 0, wxDefaultValidator, wxT("BTNExport"));
	BTNExport->Enable(false);

	BTNImport = new wxButton(this, ID_BTNIMPORT, wxT("Import File"), wxPoint(77, 499), wxSize(76, 25), 0, wxDefaultValidator, wxT("BTNImport"));
	BTNImport->Enable(false);

	BTNPreview = new wxButton(this, ID_BTNPREVIEW, wxT("Preview Compressed BMP File"), wxPoint(0, 526), wxSize(153, 25), 0, wxDefaultValidator, wxT("BTNPreview"));
	BTNPreview->Enable(false);

	wxArrayString arrayStringFor_LSTFiles;
	LSTFiles = new wxListBox(this, ID_LSTFILES, wxPoint(120, 0), wxSize(145, 497), arrayStringFor_LSTFiles, wxLB_SINGLE);

	wxArrayString arrayStringFor_LSTDirs;
	LSTDirs = new wxListBox(this, ID_LSTDIRS, wxPoint(0, 41), wxSize(120, 456), arrayStringFor_LSTDirs, wxLB_SINGLE);

	EDTConsole = new wxTextCtrl(this, ID_EDTCONSOLE, wxT(""), wxPoint(266, 403), wxSize(527, 170), wxTE_READONLY | wxTE_MULTILINE, wxDefaultValidator, wxT("EDTConsole"));
	EDTConsole->SetForegroundColour(wxColour(wxT("LIME GREEN")));
	EDTConsole->SetBackgroundColour(wxColour(wxT("BLACK")));

	SetTitle(wxT("Kamiloxnumetal's MHPB PKR3 Editor"));
	SetIcon(Self_PKR3EditorFrm_XPM);
	SetSize(8,8,800,600);
	Center();
	
	////GUI Items Creation End
}

/*******************************************************************************/

void PKR3EditorFrm::OnClose(wxCloseEvent& event)
{
	Destroy();
}

/*******************************************************************************/

void PKR3EditorFrm::BTNExportClick(wxCommandEvent& event)
{
    if(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].zip)
    {
        Str = file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fname;
        Str += ".zip";
        DLGExport -> SetFilename(Str);
        DLGExport -> SetWildcard("*.zip");
    }
    else
    {
        DLGExport -> SetFilename(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fname);
        DLGExport -> SetWildcard("*.*");
    }
    if(DLGExport -> ShowModal() == wxID_OK)
	{
        if(FHandler.Open(DLGExport -> GetPath(),wxFile::write))
        {
            Print("\nExporting File...");
            if(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].zip)
            {
                if(FHandler.IsOpened())
                    FHandler.Close();
                Print(", ");
                writezip(DLGExport -> GetPath(),LSTDirs -> GetSelection(),LSTFiles -> GetSelection(),file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fname);
            }
            else
            {
                FHandler.Write(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fdata,file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].csize);
                if(FHandler.IsOpened())
                    FHandler.Close();
            }
            Print(", File Exported!");
        }    
        else
        {
            Print("\nCan't open destination file...");
            if(FHandler.IsOpened())
                FHandler.Close();
        }
    }
}

/*******************************************************************************/

void PKR3EditorFrm::BTNImportClick(wxCommandEvent& event)
{
    unsigned short dindex = LSTDirs -> GetSelection();
	unsigned short findex = LSTFiles -> GetSelection();
    if(file[dir[dindex].dcount + findex].zip)
        DLGCaution -> ShowModal();
	if(DLGImport -> ShowModal() == wxID_OK)
	{
        Print("\nImporting File...Wait, ");
        if(FHandler.Open(DLGImport -> GetPath(),wxFile::read))
        {
	        unsigned char auxc = 0;
	        unsigned int hexcrc32 = 0;
	        char strcrc32[9];
	        char *finalptr;
	        while(!(AuxHandler.Open("crc32.bat",wxFile::write)))
	            Sleep(100);
	        Str = "\"crc32/Enfis_SFV.exe\" -f=\"crc32.bin\" -p=\"";
	        Str += DLGImport -> GetDirectory();
	        Str += "\" \"";
	        Str += DLGImport -> GetFilename();
	        Str += "\"\nexit";
	        AuxHandler.Write(Str);
	        AuxHandler.Close();
	        Str = DLGImport -> GetDirectory();
	        Str += "\\crc32.bin";
	        while(!(AuxHandler.Open(Str,wxFile::write)))
	           Sleep(100);
	        AuxHandler.Write(&auxc,1);
	        if(AuxHandler.IsOpened())
                AuxHandler.Close();
	        if(FHandler.IsOpened())
                FHandler.Close();
	        system("start crc32.bat");
	        while(true)
	        {
                if(AuxHandler.Open(Str,wxFile::read))
                {
                    if(AuxHandler.Length() > 1)
                    {
                        AuxHandler.Seek(50 + (DLGImport -> GetFilename()).Length(),wxFromStart);
                        AuxHandler.Read(strcrc32,8);
                        strcrc32[8] = '\0';
                        if(AuxHandler.IsOpened())
                            AuxHandler.Close(); 
                        Print("\nNew file CRC32: ");Print(strcrc32);
                        hexcrc32 = strtoul(strcrc32,&finalptr,16);
                        break;
                    }
                }
                if(AuxHandler.IsOpened())
                    AuxHandler.Close();
            }
            if(FHandler.Open(DLGImport -> GetPath(),wxFile::read))
            {
               delete[] file[dir[dindex].dcount + findex].fdata;
	           file[dir[dindex].dcount + findex].fdata = NULL;
	           file[dir[dindex].dcount + findex].zip = false;
	           file[dir[dindex].dcount + findex].csize = FHandler.Length();
	           file[dir[dindex].dcount + findex].usize = FHandler.Length();
	           file[dir[dindex].dcount + findex].crc32 = hexcrc32;
	           file[dir[dindex].dcount + findex].fdata = new unsigned char[file[dir[dindex].dcount + findex].csize];
               FHandler.Read(file[dir[dindex].dcount + findex].fdata,file[dir[dindex].dcount + findex].csize);
               Str = "del /f /q ";
	           Str += DLGImport -> GetDirectory();
	           Str += "\\crc32.bin";
	           system(Str);
	           Print(", File Imported!");
            }
            else
            {
                Print(", Can't open source file!");
            }
        }
        else
            Print(", Can't open source file!");
        if(FHandler.IsOpened())
            FHandler.Close();
    }
}

/*******************************************************************************/

void PKR3EditorFrm::BTNPreviewClick(wxCommandEvent& event)
{
    PreviewCBMP();
}

/*******************************************************************************/

void PKR3EditorFrm::BTNAddClick(wxCommandEvent& event)
{
    bool nsizeok = false;
    bool okpush = false;
    bool readpass = true;
    unsigned short dindex = LSTDirs -> GetSelection();
    if(DLGImport -> ShowModal() == wxID_OK)
    {
        DLGAddName -> SetValue(DLGImport -> GetFilename());
        filenamecheck:
        if(DLGAddName -> ShowModal() == wxID_OK)
        {
            okpush = true;
            if(DLGAddName -> GetValue().Length() > 0 && DLGAddName -> GetValue().Length() < 32)
                nsizeok = true;
        }
        else
            okpush = false;
        if(!nsizeok && okpush)
        {
            DLGAddBad -> ShowModal();
            goto filenamecheck;
        }
    }
    if(okpush)
    {
        Print("\nLoading file...wait, ");
        if(FHandler.Open(DLGImport -> GetPath(),wxFile::read))
        {
	        unsigned char auxc = 0;
	        unsigned int hexcrc32 = 0;
	        char strcrc32[9];
	        char *finalptr;
	        while(!(AuxHandler.Open("crc32.bat",wxFile::write)))
	            Sleep(100);
	        Str = "\"crc32/Enfis_SFV.exe\" -f=\"crc32.bin\" -p=\"";
	        Str += DLGImport -> GetDirectory();
	        Str += "\" \"";
	        Str += DLGImport -> GetFilename();
	        Str += "\"\nexit";
	        AuxHandler.Write(Str);
	        AuxHandler.Close();
	        Str = DLGImport -> GetDirectory();
	        Str += "\\crc32.bin";
	        while(!(AuxHandler.Open(Str,wxFile::write)))
                Sleep(100);
	        AuxHandler.Write(&auxc,1);
	        if(AuxHandler.IsOpened())
                AuxHandler.Close();
	        if(FHandler.IsOpened())
                FHandler.Close();
	        system("start crc32.bat");
	        while(true)
	        {
                if(AuxHandler.Open(Str,wxFile::read))
                {
                    if(AuxHandler.Length() > 1)
                    {
                        AuxHandler.Seek(50 + (DLGImport -> GetFilename()).Length(),wxFromStart);
                        AuxHandler.Read(strcrc32,8);
                        strcrc32[8] = '\0';
                        if(AuxHandler.IsOpened())
                            AuxHandler.Close(); 
                        Print("\nNew file CRC32: ");Print(strcrc32);
                        hexcrc32 = strtoul(strcrc32,&finalptr,16);
                        break;
                    }
                }
                if(AuxHandler.IsOpened())
                    AuxHandler.Close();
            }
            if(FHandler.Open(DLGImport -> GetPath(),wxFile::read))
            {
               exfile = file;
               file = NULL;
               file = new pkr3file[files_n + 1];
               strcpy(file[dir[dindex].dcount].fname,DLGAddName -> GetValue());
	           file[dir[dindex].dcount].zip = false;
	           file[dir[dindex].dcount].csize = FHandler.Length();
	           file[dir[dindex].dcount].usize = FHandler.Length();
	           file[dir[dindex].dcount].crc32 = hexcrc32;
	           file[dir[dindex].dcount].fdata = new unsigned char[file[dir[dindex].dcount].csize];
               FHandler.Read(file[dir[dindex].dcount].fdata,file[dir[dindex].dcount].csize);
               Str = "del /f /q ";
	           Str += DLGImport -> GetDirectory();
	           Str += "\\crc32.bin";
	           system(Str);
	           Print(", File loaded!");
            }
            else
            {
                Print(", Can't open source file!");
                readpass = false;
            }
        }
        else
        {
            Print(", Can't open source file!");
            readpass = false;
        }
        if(FHandler.IsOpened())
            FHandler.Close();
            
            
    }
    else
        readpass = false;
    if(readpass)
    {
        Print(", Adding file ... wait");
        for(unsigned short z,y,x = 0; x <= files_n; x++)
        {
            y = x;
            if(x == dir[dindex].dcount)
                continue;
            if(x > dir[dindex].dcount)
                y--;
            for(z = 0; z < 32; z++)
                file[x].fname[z] = exfile[y].fname[z];
            file[x].zip = exfile[y].zip;
            file[x].crc32 = exfile[y].crc32;
            file[x].usize = exfile[y].usize;
            file[x].csize = exfile[y].csize;
            file[x].foffset = exfile[y].foffset;
            file[x].fdata = exfile[y].fdata;
            exfile[y].fdata = NULL;
        }
        dir[dindex].dfiles++;
        for(unsigned short x = dindex + 1; x < dirs_n; x++)
            dir[x].dcount++;
        delete[] exfile;
        exfile = NULL;
	    files_n++;
	    MakeFileList(LSTDirs -> GetSelection());
	    Print(", File added!");
    }
}

/*******************************************************************************/

void PKR3EditorFrm::BTNDeleteClick(wxCommandEvent& event)
{
    unsigned short indexf = dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection();
    unsigned short indexd = LSTDirs -> GetSelection();
    Print("\nDeleting file wait...");
    exfile = file;
    file = NULL;
    delete exfile[indexf].fdata;
    exfile[indexf].fdata = NULL;
    if(files_n > 1)
    {
       file = new pkr3file[files_n - 1];
       for(unsigned short z,y,x = 0; x < files_n; x++)
       {
            y = x;
            if(x == indexf)
                continue;
            else if(x > indexf)
                y--;
            for(z = 0; z < 32; z++)
                file[y].fname[z] = exfile[x].fname[z];
            file[y].zip = exfile[x].zip;
            file[y].crc32 = exfile[x].crc32;
            file[y].usize = exfile[x].usize;
            file[y].csize = exfile[x].csize;
            file[y].foffset = exfile[x].foffset;
            file[y].fdata = exfile[x].fdata;
            exfile[x].fdata = NULL;
       }
    }
    dir[indexd].dfiles--;
    for(unsigned short x = indexd + 1; x < dirs_n; x++)
        dir[x].dcount--;
    delete[] exfile;
    exfile = NULL;
	files_n--;
	MakeFileList(LSTDirs -> GetSelection());
	Print(", File deleted!");
}

/*******************************************************************************/

void PKR3EditorFrm::BTNOpenDataClick(wxCommandEvent& event)
{
    if(DLGOpenDataPkr -> ShowModal() == wxID_OK)
    {
        if(FHandler.Open(DLGOpenDataPkr -> GetPath(),wxFile::read))
        {
            FHandler.Read(&aux,4);
            if(aux == 0x33524b50)
            {
                FHandler.Read(&aux,4); // Read master header offset
                FHandler.Seek(aux,wxFromStart); // Jump to master header zone
                FHandler.Read(&aux,4);
                FHandler.Read(&dirs_n,4); // Read total dirs
                dir = new pkr3dir[dirs_n];
                FHandler.Read(&files_n,4); // Read total files
                file = new pkr3file[files_n];
                for(unsigned short x = 0; x < files_n; x++)
                    file[x].fdata = NULL;
                Print("\nMHPB PKR3, found ");Print(dirs_n);Print(" folders and ");Print(files_n);Print(" files");
                BTNOpenData -> Enable(false);
                Print("\nReading Directory Header...");
                // Read Directory Header
                for(unsigned short x = 0; x < dirs_n; x++)
                {
                    FHandler.Read(dir[x].dname,32); // Dir name
                    FHandler.Read(&(dir[x].dcount),4); // Files count
                    FHandler.Read(&(dir[x].dfiles),4); // Files amount
                    LSTDirs -> Append(dir[x].dname);
                }
                LSTDirs -> SetSelection(0);
                Print("\nReading Files Header...");
                // Read Files Header
                for(unsigned short x = 0; x < files_n;x++)
                {
                    FHandler.Read(file[x].fname,32); // File name
                    FHandler.Read(&(file[x].crc32),4); // File CRC32
                    FHandler.Read(&aux,4); // File compression flag
                    if(aux == 0xfffffffe)
                        file[x].zip = false; // Uncompressed 0xfffffffe
                    else
                        file[x].zip = true; // Compressed 0x00000002
                    FHandler.Read(&(file[x].foffset),4); // File offset
                    FHandler.Read(&(file[x].usize),4); // Uncompressed size
                    FHandler.Read(&(file[x].csize),4); // Compressed size
                }
                Print("\nReading Files Data...");
                // Read Files Data
                for(unsigned short x = 0; x < files_n; x++)
                {
                    FHandler.Seek(file[x].foffset,wxFromStart);
                    file[x].fdata = new unsigned char[file[x].csize];
                    FHandler.Read(file[x].fdata,file[x].csize);
                }
                MakeFileList(0);
                Print("\nPKR3 File succesfully readed and loaded to memory");
                BTNSaveFile -> Enable();
                BTNAdd -> Enable();
            }
            else
            {
                Print("\nFile isn't a MHPB PKR3 file...");
            }   
        }
        else
        {
            Print("\nCan't open file...");
        }
        if(FHandler.IsOpened())
            FHandler.Close();
    }
}

/*******************************************************************************/

void PKR3EditorFrm::BTNSaveFileClick(wxCommandEvent& event)
{
	if(DLGSaveFile -> ShowModal() == wxID_OK)
	{
        Print("\nSaving File...");
        if(FHandler.Open(DLGSaveFile -> GetPath(),wxFile::write))
        {
            unsigned int offset = 0;
            Print("\nWriting Master PKR3 Header...");
            aux = 0x33524b50;
            FHandler.Write(&aux,4);
            offset += 8;
            FHandler.Write(&offset,4);
            aux = 0x00000004;
            FHandler.Write(&aux,4);
            FHandler.Write(&dirs_n,4);
            FHandler.Write(&files_n,4);
            offset += 12;
            Print("\nWriting Directory Header...");
            for(unsigned short x = 0; x < dirs_n; x++)
            {
                FHandler.Write(dir[x].dname,32);
                FHandler.Write(&(dir[x].dcount),4);
                FHandler.Write(&(dir[x].dfiles),4);
                offset += 40;
            }
            offset += 52*files_n;
            Print("\nWriting Files Header...");
            for(unsigned short x = 0; x < files_n; x++)
            {
                
                FHandler.Write(file[x].fname,32);
                FHandler.Write(&(file[x].crc32),4);
                if(file[x].zip)
                    aux = 0x00000002;
                else
                    aux = 0xfffffffe;
                FHandler.Write(&aux,4);
                FHandler.Write(&offset,4);
                FHandler.Write(&(file[x].usize),4);
                FHandler.Write(&(file[x].csize),4);
                offset += file[x].csize;
            }
            Print("\nWriting Files Data...");
            for(unsigned short x = 0; x < files_n; x++)
            {
                FHandler.Write(file[x].fdata,file[x].csize);
            }
            Print("\nMHPB PKR3 File Saved Successfully!");
        }
        else
        {
            Print("\nCan't open the destination file!");
        }
        if(FHandler.IsOpened())
            FHandler.Close();
    }
}

/*******************************************************************************/

void PKR3EditorFrm::LSTDirsSelected(wxCommandEvent& event)
{
	MakeFileList(LSTDirs -> GetSelection());
}

/*******************************************************************************/

void PKR3EditorFrm::LSTFilesSelected(wxCommandEvent& event)
{
	LSTFilesAction();
}

/*******************************************************************************/

void PKR3EditorFrm::LSTFilesDoubleClicked(wxCommandEvent& event)
{
	LSTFilesAction();
}

/*******************************************************************************/

void PKR3EditorFrm::Print(const wxChar* txt)
{
    EDTConsole -> AppendText(txt);
}

/*******************************************************************************/

void PKR3EditorFrm::Print(unsigned int num)
{
    char totext[13];
    itoa(num,totext,10);
    EDTConsole -> AppendText(totext);
}

/*******************************************************************************/

void PKR3EditorFrm::PreviewCBMP()
{
    BTNPreview -> Enable(false);
    HTMLBmp -> Show(false);
	EDTTxt -> Show(false);
	unsigned char temp = 0;
	Print("\n");
	writezip("unzip/Temp.Zip",LSTDirs -> GetSelection(),LSTFiles -> GetSelection(),"Temp.Bmp");
    while(!(FHandler.Open("unzip.bin",wxFile::write)))
        Sleep(100);
    FHandler.Write(&temp,1);
    if(FHandler.IsOpened())
        FHandler.Close();
    while(!(FHandler.Open("unzip.bat",wxFile::write)))
        Sleep(100);
    FHandler.Write("@echo off\ndel /f /q \"Temp.Bmp\"\n\"unzip/unzip.exe\" \"unzip/Temp.Zip\"\necho EXTRACTED >> Unzip.bin\nexit");
    if(FHandler.IsOpened())
        FHandler.Close();
    system("start unzip.bat");
    while(true)
    {
        if(FHandler.Open("unzip.bin",wxFile::read))
        {
            if(FHandler.Length() > 1)
            {
                if(FHandler.IsOpened())
                    FHandler.Close(); 
                break;
            }
        }
        if(FHandler.IsOpened())
            FHandler.Close();  
        Sleep(100);
    }
    HTMLBmp -> SetPage("<HTML><BODY BgColor=\"Grey\"><IMG SRC=\"Temp.Bmp\"></IMG></BODY></HTML>");
    HTMLBmp -> Show();
    Print("\nCompressed File Opened!");
}

/*******************************************************************************/

void PKR3EditorFrm::MakeFileList(unsigned short index)
{
    LSTFiles -> Clear();
    for(unsigned short x = dir[index].dcount; x < dir[index].dcount + dir[index].dfiles; x++)
    {
        LSTFiles -> Append(file[x].fname);
    }
    if(dir[index].dfiles == 0)
    {
        BTNExport -> Enable(false);
        BTNImport -> Enable(false);
        BTNDelete -> Enable(false);
    }
    else
    {
        BTNExport -> Enable();
        BTNImport -> Enable();
        BTNDelete -> Enable();
    }
    BTNPreview -> Enable(false);
    HTMLBmp -> Show(false);
	EDTTxt -> Show(false);
    LSTFiles -> SetSelection(0);
}

/*******************************************************************************/

void PKR3EditorFrm::LSTFilesAction()
{
    BTNPreview -> Enable(false);
    HTMLBmp -> Show(false);
	EDTTxt -> Show(false);
    switch(GetExtension(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fname))
    {
        case 1: 
            if(!file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].zip)
            {
                while(!(FHandler.Open("Temp.Wav",wxFile::write)))
                    Sleep(100);
                FHandler.Write(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fdata,file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].csize);
                if(FHandler.IsOpened())
                    FHandler.Close();
                PlaySound((LPCSTR)"Temp.Wav", NULL, SND_FILENAME | SND_ASYNC); 
            }
        break;
        case 2: 
            if(!file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].zip)
            {
                while(!(FHandler.Open("Temp.Bmp",wxFile::write)))
                    Sleep(100);
                FHandler.Write(file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].fdata,file[dir[LSTDirs -> GetSelection()].dcount + LSTFiles -> GetSelection()].csize);
                if(FHandler.IsOpened())
                    FHandler.Close();
                HTMLBmp -> SetPage("<HTML><BODY Bgcolor=\"Grey\"><IMG SRC=\"Temp.Bmp\"></IMG></BODY></HTML>");
                HTMLBmp -> Show();
            }
            else
            {
                if(CHKPreview -> GetValue())
                    PreviewCBMP();
                else
                {
                    EDTTxt -> SetValue("THE *.BMP FILE IS COMPRESSED!\nUSE: \"Preview a Compressed *.BMP File\" BUTTON TO VIEW THE FILE");
                    EDTTxt -> Show();
                    BTNPreview -> Enable(); 
                }
            }
        break;
        default:
                EDTTxt -> SetValue("UNSUPPORTED FILE FORMAT CAN'T PREVIEW...");
                EDTTxt -> Show();
        break;
    }
}

/*******************************************************************************/

void PKR3EditorFrm::writezip(const wxChar* path,unsigned short dindex,unsigned short findex,const wxChar* name)
{
    Print("Opening Compressed File...Wait");
    while(!(FHandler.Open(path,wxFile::write)))
        Sleep(100);
    unsigned int dhoffset = 0;
    // Generate Initial Zip Header
    aux = 0x04034b50;
    FHandler.Write(&aux,4);
    dhoffset+=4;
    saux = 0x0014;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    saux = 0x0000;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    saux = 0x0008;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    saux = 0x0000;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    FHandler.Write(&(file[dir[dindex].dcount + findex].crc32),4);
    dhoffset+=4;
    FHandler.Write(&(file[dir[dindex].dcount + findex].csize),4);
    dhoffset+=4;
    FHandler.Write(&(file[dir[dindex].dcount + findex].usize),4);
    dhoffset+=4;
    Str = name;
    saux = Str.Length();
    FHandler.Write(&saux,2);
    dhoffset+=2;
    saux = 0x0000;
    FHandler.Write(&saux,2);
    dhoffset+=2;
    FHandler.Write(Str,Str.Length());
    dhoffset+=Str.Length();
    // Write File Data
    FHandler.Write(&(file[dir[dindex].dcount + findex].fdata[2]),file[dir[dindex].dcount + findex].csize - 6);
    dhoffset+=(file[dir[dindex].dcount + findex].csize - 6);
    // Generate Ending Zip Header
    aux = 0x02014b50;
    FHandler.Write(&aux,4);
    saux = 0x0014;
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    saux = 0x0000;
    FHandler.Write(&saux,2);
    saux = 0x0008;
    FHandler.Write(&saux,2);
    saux = 0x0000;
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    FHandler.Write(&(file[dir[dindex].dcount + findex].crc32),4);
    FHandler.Write(&(file[dir[dindex].dcount + findex].csize),4);
    FHandler.Write(&(file[dir[dindex].dcount + findex].usize),4);
    saux = Str.Length();
    FHandler.Write(&saux,2);
    saux = 0x0000;
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    aux = 0x00000020;
    FHandler.Write(&aux,4);
    aux = 0x00000000;
    FHandler.Write(&aux,4);
    FHandler.Write(Str,Str.Length());
    aux = 0x06054b50;
    FHandler.Write(&aux,4);
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    saux = 0x0001;
    FHandler.Write(&saux,2);
    FHandler.Write(&saux,2);
    aux = 46 + Str.Length();
    FHandler.Write(&aux,4);
    FHandler.Write(&dhoffset,4);
    saux = 0x0000;
    FHandler.Write(&saux,2);
    FHandler.Close();
}

/*******************************************************************************/

unsigned short PKR3EditorFrm::GetExtension(char* text)
{
    Str = text;
    Str = Str.SubString(Str.Length() - 3,Str.Length() - 1);
    if(Str.MakeUpper() == "WAV")
        return 1;
    else if(Str.MakeUpper() == "BMP")
        return 2;
    else
        return 0;
}

/*******************************************************************************/
