Imports System.IO
Imports System.Text
Imports System.IO.Compression

Partial Class Form1

    Private Sub ImportCode_Click(sender As Object, e As EventArgs) Handles ImportCode.Click

        If Not UserRadio.Checked And Not CDExtraBtn.Checked Then MsgBox("YOU CAN IMPORT ONLY IN USER OR CDEXTRA ISO!!!") : Exit Sub

        Dim cd = New ISOTools

        'OpensFile

        OpenFileDialog1.Multiselect = True
        If OpenFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
        OpenFileDialog1.Multiselect = False

        For Each filee In OpenFileDialog1.FileNames

            Dim fileInfo = Path.GetFileName(filee)

            Dim f = File.ReadAllBytes(filee)

            If fileInfo.Contains("SLPS_028.25") And UserRadio.Checked Then
                cd.saveCDfile(UserPath.Text, 27, UBound(f) + 1, f)
            End If
            If fileInfo.Contains("SLPS_028.26") And CDExtraBtn.Checked Then
                cd.saveCDfile(CDEXTRApath.Text, 28, UBound(f) + 1, f)
            End If

        Next


        MsgBox(String.Format("Imported {0} files ", UBound(OpenFileDialog1.FileNames) + 1), MsgBoxStyle.Exclamation)

    End Sub


    Private Sub ExpMainExe_Click(sender As Object, e As EventArgs) Handles ExpMainExe.Click
        Dim iso = New ISOTools
        Dim targetSector = 27
        If CDExtraBtn.Checked Then targetSector = 28
        Dim fil = iso.getCDfile(getFilnam, targetSector, 1812408)
        Dim fn = ""
        If CDExtraBtn.Checked Then
            fn = "SLPS_028.26"
        Else
            fn = "SLPS_028.25"
        End If
        SaveFileDialog1.FileName = WorkDir.Text & fn
        If SaveFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub

        My.Computer.FileSystem.WriteAllBytes(SaveFileDialog1.FileName, fil.ToArray, False)
    End Sub

    Private Sub Export181RUS_Click(sender As Object, e As EventArgs) Handles Export181RUS.Click

        Dim files As New List(Of String)
        files = IO.Directory.GetFiles("D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0057_ALL_SCENERY\", "*.TRNSL").ToList
        Dim OutPut_Dir = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0057_ALL_SCENERY\TRANSLATED_RAW\"
        Dim iso = New ISOTools
        Dim filnam = getFilnam()
        Dim r = New rleTools

        For a = 57 To 397

            Dim fil = iso.getCDfile(filnam, files1(a).Sector, files1(a).Sizw)

            If a = 397 Then
                fil = iso.getCDfile(filnam, files1(390).Sector, files1(390).Sizw)           'заменяем последний файл...
                My.Computer.FileSystem.WriteAllBytes(OutPut_Dir & a.ToString("D4") & "_orig.bin", fil.ToArray, False) : Continue For
            End If

            Dim ind = files.FindIndex(Function(x) x.Contains(a.ToString("D4")))

            'If file withoout translation
            If ind = -1 Then
                My.Computer.FileSystem.WriteAllBytes(OutPut_Dir & a.ToString("D4") & "_orig.bin", fil.ToArray, False) : Continue For
            End If

            Debug.WriteLine("Working On......" & a.ToString("D4"))
            DeconstructFile(fil.ToArray)    'here is separated binfile

            Dim curfile As rleFile = binFile.Last
            Dim RusFile = My.Computer.FileSystem.ReadAllBytes(files(ind))

            binFile.Last.Bytes = r.decodeRLEnew(RusFile, curfile).ToArray         'Pack and replace 8th file

            'АРХИВИРУЕМ МАССИВ ФАЙЛОВ ДЛЯ ЗАПИСИ В ОДИН ФАЙЛ
            Dim lastSectorID As Integer = 0
            Dim finalPack = New List(Of Byte)

            For Each bin In binFile

                'filling sector to end (making sectorgap) in the middle of the file
                If bin.SectorID <> lastSectorID Then
                    Dim gap = 2048 - (finalPack.Count Mod 2048)
                    For g = 0 To gap - 1
                        finalPack.Add(0)
                    Next
                End If

                'Adding currentfile Sector Size (for at least 0004)
                bin.SectorSize = bin.Bytes.Count \ 2048
                If bin.Bytes.Count Mod 2048 > 0 Then bin.SectorSize += 1

                'adding currentfile and address for 0x0090
                finalPack.AddRange(bin.Bytes)

                'AddingBytesAfter
                For g = 0 To bin.BytesAfter - 1
                    finalPack.Add(0)
                Next

                lastSectorID = bin.SectorID
            Next

            'Fill file to END of Sector
            If finalPack.Count Mod 2048 > 0 Then
                For g = 1 To (2048 - (finalPack.Count Mod 2048))
                    finalPack.Add(0)
                Next g
            End If
            My.Computer.FileSystem.WriteAllBytes(OutPut_Dir & a.ToString("D4") & "_rus.bin", finalPack.ToArray, False)
        Next
        MsgBox("Export Done")
    End Sub



    Private Sub SceneryImport_Click(sender As Object, e As EventArgs) Handles SceneryImport.Click


        If Not UserRadio.Checked Then MsgBox("YOU CAN IMPORT ONLY IN USER ISO!!!") : Exit Sub
        If IsNothing(files1) Then MsgBox("PLEASE READ CD FILES FIRST!") : Exit Sub

        Dim files = IO.Directory.GetFiles("D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0057_ALL_SCENERY\TRANSLATED_RAW\", "*.bin").ToList
        Dim filesSize = 0
        'For Each f In files
        '    filesSize += My.Computer.FileSystem.GetFileInfo(f).Length
        'Next
        Dim curSector = files1(57).Sector
        Dim max = files1(398).Sector

        'MsgBox($"Sectors have - {max - curSector}" & vbCrLf & $"Sectors in files - {filesSize / 2048}") : Exit Sub
        Dim iso = New ISOTools
        Dim filnam = getFilnam()



        For a = 57 To 396
            'reading files
            Debug.WriteLine("Working On......" & a.ToString("D4"))
            Dim ind = files.FindIndex(Function(x) x.Contains(a.ToString("D4")))
            If ind = -1 Then Debug.WriteLine("NOT FOUND") : Continue For
            Dim impFile = My.Computer.FileSystem.ReadAllBytes(files(ind))

            Dim SectorSizw As Integer = (UBound(impFile) + 1) / 2048

            'Overload check
            If curSector + SectorSizw >= max Then MsgBox("!!!OVERLOAD at file " & a) : Exit For



            'debugfile move to end of disk
            ' If a = 570 Then curSector = 278100



            iso.saveCDfile(filnam, curSector, UBound(impFile) + 1, impFile)

            'Update SectorNumber and FileSize In FileArray
            files1(a).Sizw = UBound(impFile) + 1
            files1(a).Sector = curSector



            curSector += SectorSizw


        Next

        'Update FileTable In ISO
        iso.UpdateFileListTable(filnam, files1)

        MsgBox("Files Imported")

    End Sub


    Private Sub Export1112RUS_Click(sender As Object, e As EventArgs) Handles Export1112RUS.Click

        Dim files As New List(Of String)
        files = IO.Directory.GetFiles("D:\Games\PSX\Persona.2.Innocent.Sin\Export\UnRLE\1112_ALL_CITIES_SCRIPTS", "*.TRNSL").ToList
        Dim OutPut_Dir = "D:\Games\PSX\Persona.2.Innocent.Sin\Export\UnRLE\1112_ALL_CITIES_SCRIPTS\TRANSLATED_RAW\"
        Dim iso = New ISOTools
        Dim filnam = getFilnam()
        Dim r = New rleTools

        For a = 1112 To 1117

            Dim fil = iso.getCDfile(filnam, files1(a).Sector, files1(a).Sizw)

            Dim ind = files.FindIndex(Function(x) x.Contains(a.ToString("D4")))
            'If file withoout translation
            If ind = -1 Then
                My.Computer.FileSystem.WriteAllBytes(OutPut_Dir & a.ToString("D4") & "_orig.bin", fil.ToArray, False) : Continue For
            End If


            Debug.WriteLine("Working On......" & a.ToString("D4"))
            DeconstructFile(fil.ToArray)    'here is separated binfile

            Dim curfile As rleFile = binFile(binFile.Count - 1)
            Dim RusFile = My.Computer.FileSystem.ReadAllBytes(files(ind))

            binFile(binFile.Count - 1).Bytes = r.decodeRLEnew(RusFile, curfile).ToArray         'Pack and replace 8th file


            'АРХИВИРУЕМ МАССИВ ФАЙЛОВ ДЛЯ ЗАПИСИ В ОДИН ФАЙЛ
            Dim lastSectorID As Integer = 0
            Dim finalPack = New List(Of Byte)
            Dim addresses = New List(Of Integer) 'Start Addr for all files

            For Each bin In binFile

                'filling sector to end (making sectorgap) in the middle of the file
                If bin.SectorID <> lastSectorID Then
                    Dim gap = 2048 - (finalPack.Count Mod 2048)
                    For g = 0 To gap - 1
                        finalPack.Add(0)
                    Next
                End If

                'Adding currentfile Sector Size (for at least 0004)
                bin.SectorSize = bin.Bytes.Count \ 2048
                If bin.Bytes.Count Mod 2048 > 0 Then bin.SectorSize += 1


                'adding currentfile and address for 0x0090
                addresses.Add(finalPack.Count)
                finalPack.AddRange(bin.Bytes)

                'AddingBytesAfter
                For g = 0 To bin.BytesAfter - 1
                    finalPack.Add(0)
                Next

                lastSectorID = bin.SectorID


            Next

            'Fill file to END of Sector

            If finalPack.Count Mod 2048 > 0 Then
                For g = 1 To (2048 - (finalPack.Count Mod 2048))
                    finalPack.Add(0)
                Next g
            End If

            'SAVING POINTERS TABLE
            SavePointersTableToFile(addresses, OutPut_Dir & a.ToString("D4") & ".pointers", binFile)



            My.Computer.FileSystem.WriteAllBytes(OutPut_Dir & a.ToString("D4") & "_rus.bin", finalPack.ToArray, False)


        Next


        MsgBox("Export Done")



    End Sub

    Private Sub ConvertEventsForEditing_Click(sender As Object, e As EventArgs) Handles ConvertEventsForEditing.Click
        Dim srcDir = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0057_ALL_SCENERY"
        Dim destDir = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\P2EP_Editing\"
        Dim files As New List(Of String)
        files = IO.Directory.GetFiles(srcDir, "*.txt").ToList
        Dim s = New ScriptTools
        For Each f In files
            Dim a = Path.GetFileName(f)
            s.ConvertForEdit(f, destDir & Path.GetFileName(f))
        Next

        MsgBox("Done!")
    End Sub

    Private Sub MakePointers_Click(sender As Object, e As EventArgs) Handles MakePointers.Click

        If binFile.Count = 0 Or CDFileList.SelectedIndex = -1 Then Exit Sub
        Dim fil = MakePointersArray()
        If CreateBinDirCheck.Checked And CDFileList.SelectedIndex > -1 Then
            Dim cat = WorkDir.Text & Strings.Left(FilnamLabel.Text, 4) & "_" & files1(CDFileList.SelectedIndex).Descript
            If Not Directory.Exists(cat) Then
                Directory.CreateDirectory(cat)

            End If
            ExportBinPath.Text = cat & "\"
        End If
        Dim filename = ExportBinPath.Text & Strings.Left(FilnamLabel.Text, 4)
        If japRadio.Checked Then filename &= "_J"
        If EngRadio.Checked Then filename &= "_E"
        If UserRadio.Checked Then filename &= "_U"

        'SAVING POINTERS TABLE
        My.Computer.FileSystem.WriteAllBytes(filename & ".pointers", fil.ToArray, False)
        'SavePointersTableToFile(addresses, filename & ".pointers", binFile)
        'My.Computer.FileSystem.WriteAllBytes(filename & ".TEMPPACK", finalPack.ToArray, False)
        Savedlbl.Text = "SAVED TO " & filename


    End Sub

    Private Sub SearchPointers_Click(sender As Object, e As EventArgs) Handles SearchPointers.Click
        If CDFileList.Items.Count = 0 Or CDFileList.SelectedIndex = -1 Then Exit Sub
        If Not IsNumeric(CompareBTS.Text) Then Exit Sub
        Dim xxx = Convert.ToInt16(CompareBTS.Text)

        Dim fil As List(Of Byte) = MakePointersArray()
        Dim finfil = New List(Of Byte)



        For a = 0 To xxx
            If a > fil.Count - 1 Then Exit For
            finfil.Add(fil(a))
        Next


        Dim cd = New ISOTools
        Dim exeFile = cd.getCDfile(getFilnam, 27, 1812408)

        'search in exe
        Dim exeResults = ByteSearchAll(exeFile.ToArray, finfil.ToArray)
        For Each res In exeResults

            MsgBox("FOUND! IN SLPS!" & vbCrLf & "Offset: " & res) : Exit Sub
        Next


        'all files to video
        For a = 0 To 864
            Dim curFile = cd.getCDfile(getFilnam, files1(a).Sector, files1(a).Sizw)
            'If curFile(0) = 1 Or curFile(0) = 2 Then Continue For               'IF ARCHIVE
            'If curFile(1) = 1 Or curFile(1) = 2 Then Continue For
            Debug.WriteLine("Searching... " & a)
            Dim fileResults = ByteSearchAll(curFile.ToArray, finfil.ToArray)
            For Each res In fileResults
                MsgBox("FOUND! IN file #" & a & vbCrLf & "Offset: " & res) : Exit For
            Next
        Next



    End Sub



    Public Function MakePointersArray()

        'АРХИВИРУЕМ МАССИВ ФАЙЛОВ ДЛЯ ЗАПИСИ В ОДИН ФАЙЛ
        Dim lastSectorID As Integer = 0
        Dim finalPack = New List(Of Byte)
        Dim addresses = New List(Of Integer) 'Start Addr for all files

        For Each bin In binFile
            'filling sector to end (making sectorgap) in the middle of the file
            If bin.SectorID <> lastSectorID Then
                Dim gap = 2048 - (finalPack.Count Mod 2048)
                For g = 0 To gap - 1
                    finalPack.Add(0)
                Next
            End If
            'Adding currentfile Sector Size (for at least 0004)
            bin.SectorSize = bin.Bytes.Count \ 2048
            If bin.Bytes.Count Mod 2048 > 0 Then bin.SectorSize += 1

            addresses.Add(finalPack.Count)
            finalPack.AddRange(bin.Bytes)
            'AddingBytesAfter
            For g = 0 To bin.BytesAfter - 1
                finalPack.Add(0)
            Next
            lastSectorID = bin.SectorID
        Next
        'Fill file to END of Sector

        If finalPack.Count Mod 2048 > 0 Then
            For g = 1 To (2048 - (finalPack.Count Mod 2048))
                finalPack.Add(0)
            Next g
        End If

        'Making POINTERS TABLE
        Dim fil = New List(Of Byte)

        For a = 0 To binFile.Count - 1
            'Dim curAddr = a * 8 + offset
            Dim cursect As Int16 = addresses(a) \ 2048
            Dim modSect As Int16 = addresses(a) Mod 2048
            fil.Add(BitConverter.GetBytes(modSect)(0))
            fil.Add(BitConverter.GetBytes(modSect)(1)) 'BE or LE???
            fil.Add(BitConverter.GetBytes(cursect)(0))
            fil.Add(BitConverter.GetBytes(cursect)(1)) 'BE or LE???

            Dim bts As Integer = binFile(a).Bytes.Count
            If Tim8Shift.Checked And binFile(a).Compr = 0 Then bts -= 8               'Its Uncompressed TIM??

            fil.Add(BitConverter.GetBytes(bts)(0)) 'Saving Size of file
            fil.Add(BitConverter.GetBytes(bts)(1)) 'BE or LE???
            fil.Add(BitConverter.GetBytes(bts)(2))
            fil.Add(BitConverter.GetBytes(bts)(3))
        Next
        Return fil
    End Function

    Private Sub RelpaceTextExecs_Click(sender As Object, e As EventArgs) Handles RelpaceTextExecs.Click

        If CDFileList.Items.Count = 0 Or CDFileList.SelectedIndex = -1 Then Exit Sub

        Dim sb = New List(Of Byte) From {&HEA, &H68, 0, &HC}
        Dim cd = New ISOTools
        Dim curFile = cd.getCDfile(getFilnam, files1(CDFileList.SelectedIndex).Sector, files1(CDFileList.SelectedIndex).Sizw)
        Dim replaceCount As Integer = 0

        For a = 0 To curFile.Count - 1 Step 4
            If curFile(a) = sb(0) And curFile(a + 1) = sb(1) And curFile(a + 2) = sb(2) And curFile(a + 3) = sb(3) Then
                replaceCount += 1
                curFile(a) = 0 : curFile(a + 1) = &H40 : curFile(a + 2) = &H2 : curFile(a + 3) = &HC
            End If
        Next

        cd.saveCDfile(getFilnam, files1(CDFileList.SelectedIndex).Sector, files1(CDFileList.SelectedIndex).Sizw, curFile.ToArray)


        MsgBox("Found and replaced " & replaceCount & " text calls.")

    End Sub

    Private Sub ExportDUNGScripts_Click(sender As Object, e As EventArgs) Handles ExportDUNGScripts.Click

        Dim lengths = New List(Of Integer)
        lengths.AddRange({232, 228, 328, 336, 328, 336, 328, 336, 316, 332})
        Dim DungScr = New List(Of PointerAndSize)
        Dim initaddr = 114232
        For Each l In lengths
            DungScr.Add(New PointerAndSize With {.Addr = initaddr, .Sizw = l})
            initaddr += l
        Next



        DungScr.Add(New PointerAndSize With {.Addr = 119336, .Sizw = 240})
        DungScr.Add(New PointerAndSize With {.Addr = 119576, .Sizw = 240})

        Dim cd = New ISOTools
        Dim txt = New ScriptTools

        'Reading filetable and make array
        files1 = cd.makeFileList(UserPath.Text)
        'files2 = cd.makeFileList(EngISOPath.Text)
        Dim CurFile() As Byte = cd.getCDfile(UserPath.Text, files1(736).Sector, files1(736).Sizw).ToArray
        'Dim EngFile() As Byte = cd.getCDfile(EngISOPath.Text, files2(736).Sector, files2(736).Sizw).ToArray         'loading files
        Dim JRes = New ScriptFile
        Dim ERes = New ScriptFile

        For Each scr In DungScr

            Dim JapBytes(scr.Sizw - 1) As Byte : Dim EngBytes(scr.Sizw - 1) As Byte
            Array.Copy(CurFile, scr.Addr, JapBytes, 0, scr.Sizw)  'Array.Copy(EngFile, scr.Addr, EngBytes, 0, scr.Sizw)     'Copying Arrays

            txt.ParseResource(JapBytes, JRes) : txt.ParseText(JRes, False)
            'txt.ParseResource(EngBytes, ERes) : txt.ParseText(ERes, True)
            Dim combText = txt.CombineParsedText(ERes, JRes)
            Dim combResData = txt.compileData(JRes)

            Dim fil = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\0736_DUNG_SCRIPTS\" & DungScr.IndexOf(scr).ToString("D4") & ".txt"

            My.Computer.FileSystem.WriteAllText(fil, combResData & combText, False)
        Next

    End Sub

    Private Sub ConvertContact_Click(sender As Object, e As EventArgs) Handles ExportContact.Click

        Dim baseDir = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\"
        Dim Dir = baseDir & If(CharContact.Checked, "0863_CharCONTC", "0864_DemnCONTC")
        'Dim Dir = baseDir & If(CharContact.Checked, "   0862_PersCONTC", "0864_DemnCONTC")

        Dim Japfiles = IO.Directory.GetFiles(Dir & "\SRC\", "*_U").ToList
        Dim Engfiles = IO.Directory.GetFiles(Dir & "\SRC\", "*_E").ToList


        Dim scr = New ScriptTools
        Dim cnt = 0

        For Each fil In Japfiles

            Dim contact As String = scr.MakeContactExportFile(My.Computer.FileSystem.ReadAllBytes(fil), My.Computer.FileSystem.ReadAllBytes(Engfiles(Japfiles.IndexOf(fil))), cnt)

            Dim filename = Dir & "\" & Path.GetFileName(fil) & "_exp.txt"
            Debug.WriteLine("Saving " & filename)

            My.Computer.FileSystem.WriteAllText(filename, contact, False)
        Next


        MsgBox("Converted " & cnt & " dialogs!", MsgBoxStyle.Information)

    End Sub

    Private Sub Summon_Export_Click(sender As Object, e As EventArgs) Handles Summon_Export.Click

        Dim Japfiles = IO.Directory.GetFiles("D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0035_SUMMON_MSGS", "*_U").ToList
        Dim Engfiles = IO.Directory.GetFiles("D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0035_SUMMON_MSGS", "*_E").ToList
        Dim OutPut_Dir = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0035_SUMMON_MSGS\Processing\"

        Dim scr = New ScriptTools
        Dim cnt = 0

        For Each fil In Japfiles

            Dim contact As String = scr.MakeSummonExport(My.Computer.FileSystem.ReadAllBytes(fil), My.Computer.FileSystem.ReadAllBytes(Engfiles(Japfiles.IndexOf(fil))), cnt)

            Dim filename = OutPut_Dir & Path.GetFileName(fil) & "_CONV.txt"

            My.Computer.FileSystem.WriteAllText(filename, contact, False)
            cnt += 1
        Next


        MsgBox("Converted " & cnt & " dialogs!", MsgBoxStyle.Information)



    End Sub

    Private Sub Convert_Summon_Click(sender As Object, e As EventArgs) Handles Convert_Summon.Click

        Dim Japfiles = IO.Directory.GetFiles("D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\UnRLE\0035_SUMMON_MSGS\Processing", "*.txt").ToList

        DialogCounter = 0


        Dim txt = New ScriptTools


        For Each JFile In Japfiles
            Debug.WriteLine("Converting " & JFile)
            txt.convertSummonScript(JFile, DialogCounter)
        Next

        MsgBox("Success! Converted " & UBound(OpenFileDialog1.FileNames) + 1 & " file(s)" & vbCrLf & "Overall Dialogs Count: " & DialogCounter)



    End Sub

    Private Sub PSP_UNPACK_EVENT_BIN_Click(sender As Object, e As EventArgs) Handles PSP_UNPACK_EVENT_BIN.Click
        Dim zips = New List(Of Byte())

        Dim fil = My.Computer.FileSystem.ReadAllBytes("D:\Games\PSX\Persona 2 - Innocent Sin USA\PSP_GAME\USRDIR\pack\unpack\event.bin")
        Dim filenames = New List(Of String)

        For a = 0 To 396
            Dim a1 = BitConverter.ToInt32(fil, a * 8)
            Dim a2 = BitConverter.ToInt32(fil, a * 8 + 4)
            Dim zzz(a2 - a1) As Byte
            Array.Copy(fil, a1, zzz, 0, a2 - a1)
            Dim fn = ""
            For bbb = 0 To 8
                fn &= Chr(zzz(bbb + 10))
            Next
            filenames.Add(fn)
            Dim Decomp = DecompressGZip(zzz)
            zips.Add(Decomp)
            'My.Computer.FileSystem.WriteAllBytes("D:\Games\PSX\Persona 2 - Innocent Sin USA\PSP_GAME\USRDIR\pack\unpack\Event\" & a.ToString("D4") & "_" & (a + 181).ToString("D3") & "_" & fn, Decomp, False)

        Next

        Dim scr = New ScriptTools

        For Each zip In zips
            Dim filePack = New List(Of Byte())
            Dim startRead As Integer = 48

            For a = 0 To 8
                Dim a1 = BitConverter.ToInt32(zip, a * 4 + 4)
                Dim curFil(a1 - 1) As Byte
                Array.Copy(zip, startRead, curFil, 0, a1)

                startRead += a1
                Dim BA = startRead Mod 16
                If BA > 0 Then startRead += 16 - BA

                filePack.Add(curFil)

            Next
            Dim b = zips.IndexOf(zip)
            Dim fn = "D:\Games\PSX\Persona 2 - Innocent Sin USA\PSP_GAME\USRDIR\pack\unpack\Event\" & b.ToString("D4") & "_" & (b + 181).ToString("D3") & "_" & filenames(b)
            'SAVING 8th LAST FILE!!!
            Dim txt = scr.ConvertPSPTextFile(filePack.Last)
            ' My.Computer.FileSystem.WriteAllBytes(fn & ".txt", filePack.Last, False)
            My.Computer.FileSystem.WriteAllText(fn & ".txt", txt, False, Encoding.GetEncoding(1251))

        Next


        'For Each z In 


        MsgBox("EXPORTED")
    End Sub

    Public Function DecompressGZip(bytesToDecompress As Byte()) As Byte()
        Using stream As New GZipStream(New MemoryStream(bytesToDecompress), CompressionMode.Decompress)
            Const size As Integer = 4096
            Dim buffer As Byte() = New Byte(size - 1) {}
            Using memoryStream As New MemoryStream()
                Dim count As Integer
                Do
                    count = stream.Read(buffer, 0, size)
                    If count > 0 Then
                        memoryStream.Write(buffer, 0, count)
                    End If
                Loop While count > 0
                Return memoryStream.ToArray()
            End Using
        End Using
    End Function


End Class

Public Class PointerAndSize
    Public Addr As Integer
    Public Sizw As Integer
End Class

