Imports System.IO
Imports Newtonsoft.Json
Imports System.Runtime.Remoting.Metadata.W3cXsd2001

Public Class StringsOffsetEditorvb

    Public files1 As List(Of fileInfo)
    Public files2 As List(Of fileInfo)
    Public files3 As List(Of fileInfo)
    Public files4 As List(Of fileInfo) 'KUDOS
    Public CurFile As Byte()
    Public EngFile As Byte()
    Public JapFile As Byte()
    Public KudosFile As Byte()

    Public MaximusSize As Integer
    Public OffsetsTableSize As Integer
    Public TextSize As Integer

    Public additionalsFilesToSave As List(Of FileToSave)


    Private Sub StringsOffsetEditorvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim cd = New ISOTools

        'Reading filetable and make array
        files1 = cd.makeFileList(UserPath.Text)
        files2 = cd.makeFileList(EngISOPath.Text)
        files3 = cd.makeFileList(JapISOPath.Text)
        files4 = cd.makeFileList(KUDOSpath.Text)

        additionalsFilesToSave = New List(Of FileToSave)

    End Sub

    Private Sub FindOffsetInJP_Click(sender As Object, e As EventArgs) Handles FindOffsetInJP.Click

        Dim cd = New ISOTools
        If Not IsNumeric(FileID.Text) Then MsgBox("FILE ID IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        If Not IsNumeric(EngOffset.Text) Then MsgBox("ENG OFFSET IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub

        If RadioFile.Checked Then
            CurFile = cd.getCDfile(UserPath.Text, files1(FileID.Text).Sector, files1(FileID.Text).Sizw).ToArray
            EngFile = cd.getCDfile(EngISOPath.Text, files2(FileID.Text).Sector, files2(FileID.Text).Sizw).ToArray
        Else
            CurFile = cd.getCDfile(UserPath.Text, 27, 1812408).ToArray
            EngFile = cd.getCDfile(EngISOPath.Text, 27, 1812408).ToArray
        End If

        Dim Off = BitConverter.ToInt32(EngFile, EngOffset.Text)
        If Off > 10000 Then MsgBox("Error in EngOffset (Kakaya-to Hnya)!", MsgBoxStyle.Critical) : Exit Sub

        Dim offsets = New List(Of Integer)

        For a = 0 To CurFile.Length - 1 Step 4
            If BitConverter.ToInt32(CurFile, a) = Off Then
                'Validate table with offsets
                If BitConverter.ToInt32(CurFile, a + 4) = Off * 4 + 4 Then offsets.Add(a)                  'First_offset * 4 + 4 == must be address after offsets table
            End If
        Next

        If offsets.Count = 0 Then MsgBox("Offsets not found in JAP ISO!", MsgBoxStyle.Critical) : Exit Sub
        If offsets.Count = 1 Then Offset.Text = offsets(0) : LoadBtn.PerformClick() : Exit Sub

        Dim txt = "Found " & offsets.Count & " offsets.Count" & vbCrLf
        For a = 0 To offsets.Count - 1
            txt &= offsets(a) & " : " & BitConverter.ToInt32(CurFile, offsets(a)).ToString("X8") & " "
            txt &= BitConverter.ToInt32(CurFile, offsets(a) + 4).ToString("X8") & " "
            txt &= BitConverter.ToInt32(CurFile, offsets(a) + 8).ToString("X8") & " "
            txt &= BitConverter.ToInt32(CurFile, offsets(a) + 12).ToString("X8") & vbCrLf
        Next



        Dim Input = InputBox(txt & vbCrLf & "Enter offset ID:", "More than 1", "0")
        If Not IsNumeric(Input) Then Exit Sub
        If Int(Input) > offsets.Count - 1 Then Exit Sub

        'Load offset and texts
        Offset.Text = offsets(Input) : LoadBtn.PerformClick()


    End Sub

    Private Sub LoadBtn_Click(sender As Object, e As EventArgs) Handles LoadBtn.Click

        Dim cd = New ISOTools


        If Not IsNumeric(FileID.Text) Then MsgBox("FILE ID IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        If Not IsNumeric(Offset.Text) Then MsgBox("FILE OFFSET IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        If RadioFile.Checked Then

            CurFile = cd.getCDfile(UserPath.Text, files1(FileID.Text).Sector, files1(FileID.Text).Sizw).ToArray
            EngFile = cd.getCDfile(EngISOPath.Text, files2(FileID.Text).Sector, files2(FileID.Text).Sizw).ToArray
            JapFile = cd.getCDfile(JapISOPath.Text, files3(FileID.Text).Sector, files3(FileID.Text).Sizw).ToArray

            KudosFile = cd.getCDfile(KUDOSpath.Text, files4(FileID.Text).Sector, files2(FileID.Text).Sizw).ToArray


        Else
            CurFile = cd.getCDfile(UserPath.Text, 27, 1812408).ToArray
            EngFile = cd.getCDfile(EngISOPath.Text, 27, 1812408).ToArray
            JapFile = cd.getCDfile(JapISOPath.Text, 27, 1812408).ToArray

            KudosFile = cd.getCDfile(KUDOSpath.Text, 27 + 26, 1812408).ToArray

        End If


        If BitConverter.ToInt32(CurFile, Offset.Text) > 10000 Then MsgBox("Error in MainfileOffset!", MsgBoxStyle.Critical) : Exit Sub
        'If BitConverter.ToInt32(EngFile, Offset.Text) > 1000 Then MsgBox("Error in ENGfileOffset!", MsgBoxStyle.Critical) : Exit Sub
        Dim rws As Integer = BitConverter.ToInt32(CurFile, Offset.Text)
        Dim reader = Offset.Text + 4
        Dim engReader = EngOffset.Text + 4
        Dim japRd = 0
        Dim engRd = 0
        Dim kudRd = 0
        Dim estr As String = ""
        Dim kstr As String = ""
        DataGridView1.Rows.Clear()
        For a = 0 To rws - 1
            If DontEnglish.Checked Then GoTo dontEnglish

            'READING ENG STRING

            Dim curAddr As Integer = BitConverter.ToInt32(EngFile, engReader) + EngOffset.Text
            estr = ""
            Do
                Dim chrr = BitConverter.ToUInt16(EngFile, curAddr)          'Reading 2 Bytes!
                If chrr = &H96E Then estr &= "[man]" : curAddr += 2 : Continue Do
                If chrr = &H96F Then estr &= "[woman]" : curAddr += 2 : Continue Do
                If (chrr And &H1000) Or OnlyCodes_Mode.Checked Then
                    If chrr = &H1101 And BitConverter.ToUInt16(EngFile, curAddr + 2) = &H1106 And
                           BitConverter.ToUInt16(EngFile, curAddr + 4) = &H1101 And
                           BitConverter.ToUInt16(EngFile, curAddr + 6) = &H1103 Then estr &= "[END]" : Exit Do
                    If chrr = &H1136 Then
                        curAddr += 2
                        Dim aaa = EngFile(curAddr)
                        Do Until aaa = 0
                            estr &= Chr(aaa)
                            curAddr += 1
                            aaa = EngFile(curAddr)
                        Loop
                        If curAddr And 1 Then curAddr += 1
                        Continue Do
                    End If
                    If chrr = &H1103 Then estr &= "[END311]" : Exit Do
                    If chrr = &H1101 And BitConverter.ToUInt16(EngFile, curAddr + 2) = &H1103 Then estr &= "[end]" : Exit Do
                    If chrr = &H1120 Then estr &= " " : curAddr += 2 : Continue Do
                    If chrr = &H1121 Then estr &= " " : curAddr += 2 : Continue Do
                    Dim c1 = EngFile(curAddr) : Dim c2 = EngFile(curAddr + 1)
                    Dim gg = c2 And 15
                    If OnlyCodes_Mode.Checked Then
                        estr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                        curAddr += 2
                    Else
                        For byteskip = 1 To gg
                            estr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                            curAddr += 2
                            c1 = EngFile(curAddr) : c2 = EngFile(curAddr + 1)
                        Next
                    End If
                    Continue Do
                End If
                chrr = chrr And 255 : If chrr < 32 Then chrr += 32
                estr &= Chr(chrr)
                curAddr += 2
            Loop


            'reading Kudos
            If Not KudosLoad.Checked Then GoTo dontEnglish
            kstr = ""
            curAddr = BitConverter.ToInt32(KudosFile, engReader) + EngOffset.Text
            Do

                Dim chrr = BitConverter.ToUInt16(KudosFile, curAddr)          'Reading 2 Bytes!

                If (chrr And &H1000) Or OnlyCodes_Mode.Checked Then
                    If chrr = &H1101 And BitConverter.ToUInt16(KudosFile, curAddr + 2) = &H1106 And
                           BitConverter.ToUInt16(KudosFile, curAddr + 4) = &H1101 And
                           BitConverter.ToUInt16(KudosFile, curAddr + 6) = &H1103 Then kstr &= "[END]" : Exit Do
                    If chrr = &H1136 Then
                        curAddr += 2
                        Dim aaa = KudosFile(curAddr)
                        Do Until aaa = 0
                            kstr &= Chr(aaa)
                            curAddr += 1
                            aaa = KudosFile(curAddr)
                        Loop
                        If curAddr And 1 Then curAddr += 1
                        Continue Do
                    End If
                    If chrr = &H1103 Then Exit Do
                    If chrr = &H1101 And BitConverter.ToUInt16(KudosFile, curAddr + 2) = &H1103 Then Exit Do
                    If chrr = &H1120 Then kstr &= " " : curAddr += 2 : Continue Do
                    If chrr = &H1121 Then kstr &= " " : curAddr += 2 : Continue Do
                    Dim c1 = KudosFile(curAddr) : Dim c2 = KudosFile(curAddr + 1)
                    Dim gg = c2 And 15
                    If OnlyCodes_Mode.Checked Then
                        kstr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                        curAddr += 2
                    Else
                        For byteskip = 1 To gg
                            kstr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                            curAddr += 2
                            c1 = KudosFile(curAddr) : c2 = KudosFile(curAddr + 1)
                        Next
                    End If
                    Continue Do
                End If




                chrr = chrr And 255 : If chrr < 32 Then chrr += 32
                kstr &= Chr(chrr)
                curAddr += 2
            Loop

            kstr = Unkudos(kstr)



dontEnglish:

            'READING JAP STRING
            Dim jstr As String = ""
            Dim curJAddr As Integer = BitConverter.ToInt32(CurFile, reader) + Offset.Text

            Do

                If BitConverter.ToInt16(CurFile, curJAddr) And &H2000 Then         'If its my rus text
                    curJAddr += 2
                    For x = 0 To CurFile(curJAddr - 2) - 1
                        jstr &= Chr(CurFile(curJAddr + x))
                    Next

                    curJAddr += CurFile(curJAddr - 2)
                    If curJAddr And 1 Then curJAddr += 1
                End If




                If LineModeSimple.Checked Then Exit Do
                If BitConverter.ToInt16(CurFile, curJAddr) And &H2000 Then Exit Do

                'If jstr.Length > 500 Then Exit Do

                Dim chrr = BitConverter.ToUInt16(CurFile, curJAddr)          'Reading 2 Bytes!

                If chrr = &H96E Then jstr &= "[man]" : curJAddr += 2 : Continue Do
                If chrr = &H96F Then jstr &= "[woman]" : curJAddr += 2 : Continue Do


                If (chrr And &H1000) Or OnlyCodes_Mode.Checked Then
                    If chrr = &H1101 And BitConverter.ToUInt16(CurFile, curJAddr + 2) = &H1106 And
                       BitConverter.ToUInt16(CurFile, curJAddr + 4) = &H1101 And
                       BitConverter.ToUInt16(CurFile, curJAddr + 6) = &H1103 Then jstr &= "[END]" : Exit Do


                    If chrr = &H1103 Then jstr &= "[END311]" : Exit Do

                    If chrr = &H1101 And BitConverter.ToUInt16(CurFile, curJAddr + 2) = &H1103 Then Exit Do 'jstr &= "[end]" : Exit Do

                    If chrr = &H1120 Then jstr &= " " : curJAddr += 2 : Continue Do
                    If chrr = &H1121 Then jstr &= " " : curJAddr += 2 : Continue Do

                    Dim c1 = CurFile(curJAddr) : Dim c2 = CurFile(curJAddr + 1)

                    Dim gg = c2 And 15
                    If OnlyCodes_Mode.Checked Then

                        jstr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                        curJAddr += 2

                    Else
                        For byteskip = 1 To gg
                            jstr &= "[" & c1.ToString("X2") & c2.ToString("X2") & "]"
                            curJAddr += 2
                            c1 = CurFile(curJAddr) : c2 = CurFile(curJAddr + 1)
                        Next
                    End If

                    Continue Do

                End If



                'chrr = chrr And 255 : If chrr < 32 Then chrr += 32
                'jstr &= CurFile(curJAddr).ToString("X2") & CurFile(curJAddr + 1).ToString("X2")
                jstr &= Form1.chars(CurFile(curJAddr) + CurFile(curJAddr + 1) * 256)
                curJAddr += 2

            Loop
Myscr:
            DataGridView1.Rows.Add(a, jstr, estr, kstr)
            reader += 4 'shift offset addr
            engReader += 4
        Next
        OffsetsTableSize = BitConverter.ToInt32(JapFile, Offset.Text) * 4 + 4
        Dim maxJapStrOffs = 4

        'we need to take MAXIMUM OFFSET from table (even its last or not)
        For bb = 4 To OffsetsTableSize - 4 Step 4
            Dim curOffs = BitConverter.ToInt32(JapFile, bb + Offset.Text)
            If curOffs >= maxJapStrOffs Then maxJapStrOffs = curOffs
        Next

        'Dim lastJapStrOffs As Integer = BitConverter.ToInt32(JapFile, OffsetsTableSize + Offset.Text - 4) + Offset.Text


        'reading japan table limit
        reader = maxJapStrOffs + Offset.Text
        Do
            If JapFile(reader) = 3 And JapFile(reader + 1) = &H11 Then
                TextSize = reader + 2 - Offset.Text - OffsetsTableSize
                MaximusSize = reader + 2 - Offset.Text
                Exit Do
            End If
            reader += 1
        Loop
        OffSz.Text = "Offset Table: " & OffsetsTableSize
        TxtSz.Text = "Text Size: " & TextSize
        Allsz.Text = "OverAll: " & MaximusSize
    End Sub

    Public Function CompileLine(ByRef str As String)
        Dim bts = New List(Of Byte)

        Dim c As Integer 'counter

        If str.Length = 0 Then Return bts

        'OLD JAP TEXT FORMAT
        If str(0) = "#" Then
            'xx += 1
            For xx = 1 To str.Length - 1
                bts.Add(Asc(str(xx)))
                bts.Add(0)

            Next
            bts.Add(0)
            bts.Add(16) 'Close string
            Return bts
        End If



        'NEW FORMAT
        For xx = 0 To str.Length - 1
            If str(xx) = "^" Then xx += 1



            If str(xx) = "[" Then
                Dim skRes As String = getFromSkobki(str, xx)

                Select Case skRes
                    Case "END"
                        bts.AddRange({1, 17, 6, 17, 1, 17, 3, 17}) : Exit For
                    Case "end"
                        bts.AddRange({1, 17, 3, 17}) : Exit For
                    Case "END311"
                        bts.AddRange({3, 17}) : Exit For
                    Case "man"
                        bts.AddRange({110, 9}) : Continue For
                    Case "woman"
                        bts.AddRange({111, 9}) : Continue For
                    Case "col=white"
                        bts.AddRange({&H2E, &H12, 1, 0}) : Continue For
                    Case "col=orange"
                        bts.AddRange({&H2E, &H12, &HD, 0}) : Continue For
                    Case "col=yellow"
                        bts.AddRange({&H2E, &H12, &HB, 0}) : Continue For
                    Case "END"
                End Select

                If skRes.Length = 4 Then
                    bts.AddRange(SoapHexBinary.Parse(skRes).Value.ToList)
                End If
                Continue For
            End If


            Dim SimpleTextAccum = New List(Of Byte)
            Dim readCounter As Byte = 1

            Do
                If xx = str.Length Then xx -= 1 : Exit Do
                If Asc(str(xx)) < 32 Or Asc(str(xx)) = 91 Then xx -= 1 : Exit Do
                SimpleTextAccum.Add(Asc(str(xx)))
                xx += 1
            Loop

            'if 1 or 2 bytes
            'If SimpleTextAccum.Count = 1 Then bts.AddRange({SimpleTextAccum(0), 0}) : Continue For
            'If SimpleTextAccum.Count = 2 Then bts.AddRange({SimpleTextAccum(0), 0, SimpleTextAccum(1), 0}) : Continue For


            bts.Add(SimpleTextAccum.Count)
            bts.Add(&H20)                     'command & length
            bts.AddRange(SimpleTextAccum)     'attach textline
            If SimpleTextAccum.Count And 1 Then bts.Add(0)        ' if and 1 - add empty byte



        Next

        Return bts

    End Function


    Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
        Dim FinalArr = New List(Of Byte)
        For a = 0 To OffsetsTableSize - 1
            FinalArr.Add(CurFile(a + Offset.Text))
        Next

        For Each row In DataGridView1.Rows
            Dim isSimilar As Boolean = False
            Dim curIndx = DataGridView1.Rows.IndexOf(row)
            Dim curOffset As Integer = FinalArr.Count

            'NEED TO SEARCH SIMILAR STRINGS!!! And MAKE INDEX without ADDING STRING!
            For xxx = 0 To curIndx - 1
                If DataGridView1.Rows(xxx).Cells(1).Value = row.Cells(1).Value Then
                    isSimilar = True
                    curOffset = BitConverter.ToInt32(FinalArr.ToArray, xxx * 4 + 4)
                    Exit For
                End If

            Next


            Dim offsetAddr As Integer = curIndx * 4 + 4

            FinalArr(offsetAddr) = BitConverter.GetBytes(curOffset)(0)
            FinalArr(offsetAddr + 1) = BitConverter.GetBytes(curOffset)(1)
            FinalArr(offsetAddr + 2) = BitConverter.GetBytes(curOffset)(2)

            If isSimilar Then Continue For   'Similar String

            Dim curStr = row.Cells(1).Value.ToString


            'TEXT ADDING PART

            If curStr = "" Then Continue For

            If LineModeSimple.Checked And curStr(0) <> "^" And curStr(0) <> "#" Then

                FinalArr.AddRange({curStr.Length, &H20})        'Length Of string
                For a = 0 To curStr.Length - 1
                    FinalArr.Add(Asc(curStr(a)))
                Next
                If FinalArr.Count And 1 Then FinalArr.Add(0)
            Else
                FinalArr.AddRange(CompileLine(curStr))
            End If

        Next

        'Saving & importing FIle
        If FinalArr.Count > MaximusSize Then MsgBox("SIZE EXCEED! " & FinalArr.Count) : Exit Sub
        For a = 0 To FinalArr.Count - 1
            CurFile(a + Offset.Text) = FinalArr(a)
        Next
        Dim cd = New ISOTools
        If RadioFile.Checked Then
            cd.saveCDfile(UserPath.Text, files1(FileID.Text).Sector, files1(FileID.Text).Sizw, CurFile)
        Else
            cd.saveCDfile(UserPath.Text, 27, 1812408, CurFile)
        End If

        'Multisaving to doubled info
        If additionalsFilesToSave.Count > 0 Then
            If MsgBox($"Wanna add this info into{vbCrLf}additional {additionalsFilesToSave.Count} files?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                For Each f In additionalsFilesToSave
                    Dim fff = cd.getCDfile(UserPath.Text, files1(f.id).Sector, files1(f.id).Sizw).ToArray()
                    For a = 0 To FinalArr.Count - 1
                        fff(a + f.offset) = FinalArr(a)
                    Next
                    cd.saveCDfile(UserPath.Text, files1(f.id).Sector, files1(f.id).Sizw, fff)
                Next
            End If
        End If

        MsgBox("Succesfully Saved!", MsgBoxStyle.Information)
        'Dim filnam As String = "D:\Games\PSX\Persona.2.Innocent.Sin\Export\0063_SHOPS_CODE\EDITOR\TESTOUTPUT"
        'My.Computer.FileSystem.WriteAllBytes(filnam, FinalArr.ToArray, False)


    End Sub


    Private Sub SaveSettings_Click(sender As Object, e As EventArgs) Handles SaveSettings.Click
        If SetName.Text.Count = 0 Then MsgBox("Enter name!") : Exit Sub
        Dim filnam As String = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\LINES_EDITOR\"
        If RadioFile.Checked Then filnam &= FileID.Text & "_" Else filnam &= "0000_"
        filnam &= Offset.Text & "_" & EngOffset.Text & "_" & SetName.Text & ".txt"

        My.Computer.FileSystem.WriteAllText(filnam, SetName.Text, False)

    End Sub

    Private Sub LoadSettings_Click(sender As Object, e As EventArgs) Handles LoadSettings.Click

        Form1.OpenFileDialog1.InitialDirectory = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\LINES_EDITOR\"
        If Form1.OpenFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
        Dim fileInfo = Split(Path.GetFileNameWithoutExtension(Form1.OpenFileDialog1.FileName), "_")
        Dim Settings() = Split(My.Computer.FileSystem.ReadAllText(Form1.OpenFileDialog1.FileName), vbCrLf)
        SetName.Text = Settings(0)
        LinkedFiles.Items.Clear()
        If Settings.Count > 1 Then
            additionalsFilesToSave = JsonConvert.DeserializeObject(Of List(Of FileToSave))(Settings(1))
            For Each f In additionalsFilesToSave
                LinkedFiles.Items.Add($"#{f.id} o: {f.offset}")
            Next
            MsgBox($"Found additional {additionalsFilesToSave.Count} links to files.{vbCrLf}Be careful.", MsgBoxStyle.Information)
        Else
            additionalsFilesToSave = New List(Of FileToSave)
        End If

        If fileInfo(0) = "0000" Then
            RadioFile.Checked = False : RadioSector.Checked = True
            FileID.Text = fileInfo(0)
            Offset.Text = fileInfo(1)
            EngOffset.Text = fileInfo(2)

            LoadBtn.PerformClick()
        Else
            RadioFile.Checked = True : RadioSector.Checked = False
            FileID.Text = fileInfo(0)
            Offset.Text = fileInfo(1)
            EngOffset.Text = fileInfo(2)

            LoadBtn.PerformClick()

        End If

    End Sub

    Public Sub CalcYourTextSize()
        Dim byteCount = 0

        If LineModeSimple.Checked Then

            For Each row In DataGridView1.Rows

                Dim rrr = row.Cells(1).Value
                If Not IsNothing(rrr) Then
                    If rrr.ToString.Length = 0 Then Continue For

                    'if jap insert

                    If rrr(0) = "#" Then
                        byteCount += (rrr.ToString.Length - 1) * 2 + 2
                    Else
                        byteCount += 2 + rrr.ToString.Length
                    End If
                End If
            Next

            If byteCount > TextSize Then
                YourTxtSz.ForeColor = Color.Red
            Else
                YourTxtSz.ForeColor = Color.Blue
            End If

            If byteCount And 1 Then byteCount += 1

        Else
            For Each row In DataGridView1.Rows
                Dim curIndx = DataGridView1.Rows.IndexOf(row)
                For xxx = 0 To curIndx - 1
                    If DataGridView1.Rows(xxx).Cells(1).Value = row.Cells(1).Value Then GoTo simil
                Next
                If Not IsNothing(row.Cells(1).Value) Then
                    Dim line As List(Of Byte) = CompileLine(row.Cells(1).Value.ToString)        'Check similar strings
                    byteCount += line.Count
                End If

simil:
            Next

        End If

        YourTxtSz.Text = "Your text sz: " & byteCount
        If byteCount > TextSize Then YourTxtSz.ForeColor = Color.Red Else YourTxtSz.ForeColor = Color.Blue

    End Sub

    Public Function getFromSkobki(ByRef tx As String, ByRef x As Integer)

        x = x + 1
        Dim accum = ""
        Do While tx(x) <> "]"
            accum &= tx(x)
            x += 1
        Loop
        Return accum

    End Function

    Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        If Not DisableCalc.Checked Then CalcYourTextSize()
    End Sub

    Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
        If LineModeComplex.Checked Then Exit Sub
        If DataGridView1.CurrentCell.ColumnIndex <> 1 Then Exit Sub
        Dim aaa = DataGridView1.CurrentCell
        If IsNothing(aaa.Value) Then Exit Sub
        Dim ddd = aaa.Value.ToString.Length
        CurLen.Text = "Cur. Len.: " & ddd
        If ddd > 19 Then CurLen.ForeColor = Color.Red Else CurLen.ForeColor = Color.Blue
    End Sub


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles tempSave.Click
        Dim filnam As String = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\LINES_EDITOR\TEMP_TEXT\"
        If RadioFile.Checked Then filnam &= FileID.Text & "_" Else filnam &= "0000_"
        filnam &= Offset.Text & "_" & SetName.Text & "_TEMP_TEXT.txt"

        Dim txt As String = ""

        For Each row In DataGridView1.Rows
            Dim aaa = DataGridView1.CurrentCell
            If IsNothing(row.Cells(1).Value) Then MsgBox("Error reading tgable! Pleasem, resave!") : Exit Sub
            txt += row.Cells(1).Value.ToString & vbCrLf
        Next

        My.Computer.FileSystem.WriteAllText(filnam, txt, False)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles tempLoad.Click
        Form1.OpenFileDialog1.InitialDirectory = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\LINES_EDITOR\TEMP_TEXT\"
        If Form1.OpenFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub

        Dim txt = Split(My.Computer.FileSystem.ReadAllText(Form1.OpenFileDialog1.FileName), vbCrLf)
        txt = txt.Where(Function(s) Not s.Contains("\\")).ToArray()

        ReDim Preserve txt(DataGridView1.Rows.Count - 1)

        For Each row In DataGridView1.Rows

            row.Cells(1).Value = txt(DataGridView1.Rows.IndexOf(row))
        Next

    End Sub

    Private Sub PatchFileBtn_Click(sender As Object, e As EventArgs) Handles PatchFileBtn.Click


        Dim cd = New ISOTools
        If Not IsNumeric(patchFileID.Text) Then MsgBox("FILE ID IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        If Not IsNumeric(patchOffset.Text) Then MsgBox("FILE OFFSET IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub

        Dim patchFile() As Byte
        If PatchFileRadio.Checked Then
            patchFile = cd.getCDfile(UserPath.Text, files1(patchFileID.Text).Sector, files1(patchFileID.Text).Sizw).ToArray
        Else
            patchFile = cd.getCDfile(UserPath.Text, 27, 1812408).ToArray
        End If

        Dim test = BitConverter.ToInt32(patchFile, patchOffset.Text)

        If test = 201474048 Then MsgBox("Already patched with 80090000! ;)", MsgBoxStyle.Information) : Exit Sub
        If test <> 201352384 Then MsgBox("Wrong 80019300 call!", MsgBoxStyle.Critical) : Exit Sub

        patchFile(patchOffset.Text) = 0
        patchFile(patchOffset.Text + 1) = &H40
        patchFile(patchOffset.Text + 2) = 2
        patchFile(patchOffset.Text + 3) = &HC

        If PatchFileRadio.Checked Then
            cd.saveCDfile(UserPath.Text, files1(patchFileID.Text).Sector, files1(patchFileID.Text).Sizw, patchFile)
        Else
            cd.saveCDfile(UserPath.Text, 27, 1812408, patchFile)
        End If
        MsgBox("Succesfull patched.", MsgBoxStyle.Information)

    End Sub


    Private Sub ReplaceAll_Click(sender As Object, e As EventArgs) Handles ReplaceAll.Click
        If Not IsNumeric(patchFileID.Text) Then MsgBox("FILE ID IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        If Not IsNumeric(patchOffset.Text) Then MsgBox("FILE OFFSET IS NOT NUMERIC!", MsgBoxStyle.Critical) : Exit Sub
        Dim cd = New ISOTools
        Dim patchFile() As Byte
        If PatchFileRadio.Checked Then
            patchFile = cd.getCDfile(UserPath.Text, files1(FileID.Text).Sector, files1(FileID.Text).Sizw).ToArray
        Else
            patchFile = cd.getCDfile(UserPath.Text, 27, 1812408).ToArray
        End If

        Dim overall = 0

        For a = 0 To patchFile.Length - 1 Step 4

            If a > 500000 Then Exit For                 'don't touch my code and jumps if in main EXE

            If BitConverter.ToInt32(patchFile, a) = 201353450 Then
                patchFile(a) = 0
                patchFile(a + 1) = &H40
                patchFile(a + 2) = 2
                patchFile(a + 3) = &HC
                overall += 1
            End If
        Next

        If PatchFileRadio.Checked Then
            cd.saveCDfile(UserPath.Text, files1(FileID.Text).Sector, files1(FileID.Text).Sizw, patchFile)
        Else
            cd.saveCDfile(UserPath.Text, 27, 1812408, patchFile)
        End If

        MsgBox("Patched " & overall & " text calls!", MsgBoxStyle.Information)



    End Sub

    Private Sub EngSave_Click(sender As Object, e As EventArgs) Handles EngSave.Click
        Dim filnam As String = "D:\Games\PSX\Persona 2 - Batsu (NTSC-J) [SLPS-02825]\Export\LINES_EDITOR\TEMP_TEXT\"
        If RadioFile.Checked Then filnam &= FileID.Text & "_" Else filnam &= "0000_"
        filnam &= Offset.Text & "_" & SetName.Text & "_ENG_TEXT.txt"

        Dim txt As String = ""

        For Each row In DataGridView1.Rows
            txt += row.Cells(2).Value.ToString & vbCrLf
        Next


        My.Computer.FileSystem.WriteAllText(filnam, txt, False)
    End Sub


    Public Function Unkudos(ByRef Str As String)
        Str = Str.Replace("V", "л")
        Str = Str.Replace("v", "ф")
        Str = Str.Replace("D", "Д")
        Str = Str.Replace("h", "н")
        Str = Str.Replace("j", "у")
        Str = Str.Replace("w", "ж")
        Str = Str.Replace("W", "Ж")
        Str = Str.Replace("z", "ч")
        Str = Str.Replace("O", "Ф")
        Str = Str.Replace("t", "т")
        Str = Str.Replace("Y", "У")
        Str = Str.Replace("u", "ю")
        Str = Str.Replace("Q", "Э")
        Str = Str.Replace("q", "з")
        Str = Str.Replace("x", "б")
        Str = Str.Replace("m", "м")
        Str = Str.Replace("f", "г")
        Str = Str.Replace("y", "п")
        Str = Str.Replace("n", "и")
        Str = Str.Replace("N", "И")
        Str = Str.Replace("J", "П")
        Str = Str.Replace("Z", "Г")
        Str = Str.Replace("g", "ш")
        Str = Str.Replace("G", "Ш")
        Str = Str.Replace("b", "в")
        Str = Str.Replace("d", "д")
        Str = Str.Replace("-", "ч")
        Str = Str.Replace("S", "б")
        Str = Str.Replace("r", "я")
        Str = Str.Replace("s", "ы")
        Str = Str.Replace("&", "О")
        Str = Str.Replace("R", "Я")
        Str = Str.Replace("L", "л")
        Str = Str.Replace("l", "x")

        Return Str


    End Function

    Private Sub CopyTable_Click(sender As Object, e As EventArgs) Handles CopyTable.Click
        Dim off = Convert.ToInt32(Offset.Text)
        If CurFile Is Nothing OrElse CurFile.Length < off + 31 Then Exit Sub

        Dim HexString As String = ""

        For a = off To off + 31
            If a > 0 Then HexString &= " "
            HexString &= CurFile(a).ToString("X2")
        Next

        Clipboard.SetText(HexString)
        MsgBox("32 bytes copied: " & HexString)
    End Sub

    Private Sub unlink_Click(sender As Object, e As EventArgs) Handles unlink.Click
        additionalsFilesToSave.Clear()
        LinkedFiles.Items.Clear()
    End Sub
End Class


Public Class FileToSave
    Public Property id As Integer
    Public Property offset As Integer
End Class