''dsmplayer.wxb''

Dim convertFiles As wxArrayString = New wxArrayString()
Dim convertCmd As String
Dim convertPid As Integer
Dim isConvert As Integer = FALSE

'create convert dialog
Sub onConvert(event As wxCommandEvent)
  Dim explorerMedia As wxGenericDirCtrl = DynamicCast("wxGenericDirCtrl", musicFrame.FindWindowByName("explorermedia"))

  Dim cfg As wxFileConfig = wxFileConfig("", "", playerIni)
  cfg.SetPath("/Convert")

  Dim sd = wxDialog(musicframe, -1, _("Convert"), wxDefaultPosition, wxSize(1080, 900), wxCAPTION|wxSYSTEM_MENU|wxMINIMIZE_BOX)
  Dim x, y As Integer
  x, y = wxDisplaySize()
  sd.SetPosition(wxPoint((x - sd.GetSizeWidth())/ 2, (y - sd.GetSizeHeight())/ 2))
  sd.SetName("convertdlg")
  Dim sizeX = sd.GetClientSizeWidth()
  Dim sizeY = sd.GetClientSizeHeight()
  Dim cfilter = "all Music files|*.aac;*.flac;*.mp3;*.m4a;*.ogg;*.opus;*.wav|" &
  "aac files (*.aac)|*.aac|flac files (*.flac)|*.flac|mp3 files (*.mp3)|*.mp3|m4a files (*.m4a)|*.m4a|ogg files (*.ogg)|*.ogg|opus files (*.opus)|*.opus|wav files (*.wav)|*.wav"

  Dim plPanel As wxPanel = wxPanel(sd, -1)
  Dim font As wxFont = wxFont(IIf(ppiH > 100, 8, 9), wxDEFAULT, wxNORMAL, wxNORMAL)
  plPanel.SetFont(font)

  Dim path As String = cfg.Read("SourcePath", "")
  Dim filePath As String = IIf(path <> "", path, explorerMedia.GetPath())

  Dim gb As wxGridBagSizer = wxGridBagSizer(3, 3)

  'left side
  Dim filectrl As wxGenericFileCtrl = wxGenericFileCtrl(plPanel, -1, "..", "..", cFilter, wxFC_OPEN|wxFC_MULTIPLE, wxDefaultPosition, wxSize((sizeX - 190)/ 2, 300), "batchFileCtrl")
  fileCtrl.SetFilterIndex(0)
  fileCtrl.SetDirectory(filePath&DELIMITER_CHAR)
  gb.AddSpacer(5, 10, wxGBPosition(1, 0))
  gb.AddWindow(fileCtrl, wxGBPosition(1, 1), wxGBSpan(13, 1), wxEXPAND)

  'controls in the middle
  Dim btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_FOLDER_OPEN, wxART_OTHER, wxSize(16 * ps, 16 * ps)), wxDefaultPosition, wxSize(50, 30))
  btn.SetToolTip(_("Open a directory"))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onChangeFilePath")
  gb.AddWindow(btn, wxGBPosition(1, 2), wxDefaultSpan, 0)

  Dim cb00 = wxCheckBox(plPanel, -1, _("Report Mode"))
  Dim mode = Val(cfg.Read("ReportMode", FALSE))
  cb00.SetValue(mode) 
  setReportMode(mode)
  Connect(cb00, -1, wxEVT_COMMAND_CHECKBOX_CLICKED, "onReportMode")
  gb.AddWindow(cb00, wxGBPosition(2, 2), wxDefaultSpan, 0)

  Dim cb01 = wxCheckBox(plPanel, -1, _("Subdirs"))
  cb01.SetValue(cfg.Read("IncludeSubs", FALSE)) 
  cb01.SetName("includeCb")
  gb.AddWindow(cb01, wxGBPosition(3, 2), wxDefaultSpan, 0)
  gb.AddSpacer(1, 3, wxGBPosition(4, 2))

  'buttons in the middle
  btn = wxButton(plPanel, -1, _("Add"), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onAddSelectedFiles")
  gb.AddWindow(btn, wxGBPosition(5, 2), wxDefaultSpan, 0)

  btn = wxButton(plPanel, -1, _("Add all"), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onAddAllFiles")
  gb.AddWindow(btn, wxGBPosition(6, 2), wxDefaultSpan, 0)

  btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_GO_UP), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onMoveFilesUp")
  gb.AddWindow(btn, wxGBPosition(7, 2), wxDefaultSpan, 0)

  btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_GO_DOWN), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onMoveFilesDown")
  gb.AddWindow(btn, wxGBPosition(8, 2), wxDefaultSpan, 0)

  btn = wxButton(plPanel, -1, _("Remove"), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onRemoveSelectedFiles")
  gb.AddWindow(btn, wxGBPosition(9, 2), wxDefaultSpan, 0)

  btn = wxButton(plPanel, -1, _("Remove all"), wxDefaultPosition, wxSize(150, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onRemoveAllFiles")
  gb.AddWindow(btn, wxGBPosition(10, 2), wxDefaultSpan, wxEXPAND)
  gb.AddSpacer(1, 3, wxGBPosition(11, 2))

  Dim cb1 = wxCheckBox(plPanel, -1, _("Rename only"))
  cb1.SetName("renameCb")
  cb1.SetValue(cfg.Read("RenameOnly", FALSE))
  Connect(cb1, -1, wxEVT_COMMAND_CHECKBOX_CLICKED, "onRenameMode")
  gb.AddWindow(cb1, wxGBPosition(12, 2), wxDefaultSpan, 0)

  Dim cb2 = wxCheckBox(plPanel, -1, _("Delete Source"))
  cb2.SetValue(cfg.Read("DeleteSource", FALSE))
  cb2.SetName("deleteCb")
  cb2.Enable(FALSE)
  gb.AddWindow(cb2, wxGBPosition(13, 2), wxDefaultSpan, 0)

  'create the file list window
  Dim fileList As wxListBox = wxListBox(plPanel, -1, wxDefaultPosition, wxSize((sizeX - 190)/ 2, 300), 0, [], wxLB_MULTIPLE|wxLB_EXTENDED|wxLB_HSCROLL)
  fileList.SetName("batchFileList")
  gb.AddWindow(filelist, wxGBPosition(1, 3), wxGBSpan(13, 1), 0)
  gb.AddSpacer(10, 10, wxGBPosition(14, 1))

  'path options
  Dim text = wxStaticText(plPanel, -1, _("Destination folder:"))
  gb.AddWindow(text, wxGBPosition(15, 1), wxDefaultSpan, wxEXPAND)

  Dim bSizer0 As wxBoxSizer = wxBoxSizer(wxHORIZONTAL)
  Dim convPath As wxDirPickerCtrl = wxDirPickerCtrl(plPanel, -1, fileCtrl.GetShownDirectory(), "...")', wxPoint(10, rect.GetBottom()+ 5), wxSize(580, -1), wxDIRP_DEFAULT_STYLE)
  convPath.SetName("browseButton")
  path = cfg.Read("ConvPath", "")
  convPath.SetPath(IIf(path = "", filepath, path))
  bsizer0.AddWindow(convPath, wxEXPAND, wxEXPAND)
  bSizer0.AddSpacer(10)

  Dim btn1 = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_GO_BACK, wxART_OTHER, wxSize(24, 24)), wxDefaultPosition, wxSize(35, 25))
  btn1.SetToolTip(_("Current selected directory"))
  btn1.SetName("curDirButton")
  Connect(btn1, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onSetCurDir")
  bsizer0.AddWindow(btn1, 0, wxEXPAND)
  gb.AddSizer(bSizer0, wxGBPosition(16, 1), wxGBSpan(0, 3), wxEXPAND)

  Dim st As wxStaticBox = wxStaticBox(plPanel, -1, _("Options"), wxDefaultPosition, wxSize(-1, 75))
  Dim cb3 As wxCheckBox = wxCheckBox(st, -1, _("Overwrite existing files"), wxPoint(10, 20))
  cb3.SetName("ov")
  cb3.SetValue(cfg.Read("Overwrite", FALSE))

  Dim cb4 As wxCheckBox = wxCheckBox(st, -1, _("Adopt original modifikation time"), wxPoint(10, 45))
  cb4.SetName("pd")
  cb4.SetValue(cfg.Read("AdoptData", FALSE))

  Dim stx As wxStaticText = wxStaticText(st, -1, _("Output name:"), wxPoint(350, 15))
  Dim outName As wxTextCtrl = wxTextCtrl(st, -1, cfg.Read("FileName", "@f"), wxPoint(350, 35), wxSize(200, 25))
  outName.SetName("outname")

  stx = wxStaticText(st, -1, "@f = " &_("current filename"), wxPoint(570, 15))
  stx = wxStaticText(st, -1, "@d = " &_("current date"), wxPoint(570, 33))
  stx = wxStaticText(st, -1, "@t = " &_("current time"), wxPoint(570, 51))
  stx = wxStaticText(st, -1, "@c = " &_("counter"), wxPoint(750, 15))
  stx = wxStaticText(st, -1, _("Start Counter with:"), wxPoint(750, 33))
  Dim outNum As wxSpinCtrl = wxSpinCtrl(st, -1, "", wxPoint(stx.GetPositionX()+ stx.GetSizeWidth()+ 10, 30), wxSize(100, 21), wxSP_ARROW_KEYS, 0, 10000, cfg.Read("AddCounter", 1))
  outNum.SetName("counter")
  gb.AddSpacer(10, 10, wxGBPosition(17, 4))
  gb.AddWindow(st, wxGBPosition(17, 1), wxGBSpan(1, 3), wxEXPAND)


  Dim bSizer As wxBoxSizer = wxBoxSizer(wxHORIZONTAL)
  Dim ars1 As wxArrayString = wxArrayString()
  ars1.Add("PCM (.wav)")
  ars1.Add("FLAC (.flac)")
  ars1.Add("AAC (.m4a)")
  ars1.Add("AAC (.aac)")
  ars1.Add("Opus (.opus)")
  ars1.Add("Vorbis (.ogg)")
  ars1.Add("Mp3 (.mp3)")

  Dim rB1 As wxRadioBox = wxRadioBoxWithArray(plPanel, -1, _("Output format"), wxDefaultPosition, wxDefaultSize, ars1, 2, wxRA_HORIZONTAL|wxRA_SPECIFY_COLS)
  Connect(rB1, -1, wxEVT_COMMAND_RADIOBOX_SELECTED, "onSelectFormat")
  rb1.SetName("format")
  Dim outFormat = cfg.Read("Output", 0)
  rb1.SetSelection(outFormat)
  bsizer.AddWindow(rb1, 0, wxEXPAND)
  bSizer.AddSpacer(10)

  Dim ars2 As wxArrayString = wxArrayString()
  ars2.Add(_("default"))
  ars2.Add("1 (VBR / Q)")
  ars2.Add("2 (VBR / Q)")
  ars2.Add("3 (VBR / Q)")
  ars2.Add("4 (VBR / Q)")
  ars2.Add("5 (VBR / Q)")
  ars2.Add("6 (VBR / Q)")
  ars2.Add("7 (VBR / Q)")
  ars2.Add("8 (VBR / CBR / Q)")
  ars2.Add("9 (VBR / CBR / Q)")
  ars2.Add("10 (VBR / CBR / Q)")
  ars2.Add("64 (VBR / CBR)")
  ars2.Add("96 (VBR / CBR)")
  ars2.Add("128 (VBR / CBR)")
  ars2.Add("192 (VBR / CBR)")
  ars2.Add("256 (VBR / CBR)")
  ars2.Add("320 (VBR / CBR)")
  ars2.Add("510 (VBR / CBR)")
  ars2.Add("800 (CBR)")

  Dim rB2 As wxRadioBox = wxRadioBoxWithArray(plPanel, -1, "VBR / CBR / Quality (Q)", wxDefaultPosition, wxDefaultSize, ars2, 5, wxRA_VERTICAL|wxRA_SPECIFY_ROWS)
  rb2.SetName("quality")
  rb2.SetSelection(cfg.Read("Quality", 0))
  bsizer.AddWindow(rb2, wxEXPAND, wxEXPAND)
  bSizer.AddSpacer(10)

  For i = 1 To 5
    rb2.SetItemToolTip(i, _("VBR Quality in aac and mp3, Quality in ogg"))
  Next
  For i = 6 To 7
    rb2.SetItemToolTip(i, _("VBR Bitrate in opus, Quality in ogg"))
  Next
  For i = 8 To 10
    rb2.SetItemToolTip(i, _("VBR Bitrate in opus, CBR in aac, Quality in ogg"))
  Next
  For i = 11 To 17
    rb2.SetItemToolTip(i, _("VBR Bitrate in opus, CBR Bitrate in aac"))
  Next
  rb2.SetItemToolTip(18, _("CBR Bitrate in aac"))

  Dim ars3 As wxArrayString = wxArrayString()
  ars3.Add(_("default"))
  ars3.Add("8-bit")                 'uint8
  ars3.Add("16-bit")                'int16
  ars3.Add("32-bit")                'int32
  ars3.Add("32-bit float")          'float32
  Dim rB3 As wxRadioBox = wxRadioBoxWithArray(plPanel, -1, _("Bit Depth"), wxDefaultPosition, wxDefaultSize, ars3, 1, wxRA_HORIZONTAL|wxRA_SPECIFY_COLS)
  rb3.SetName("encoding")
  rb3.SetSelection(cfg.Read("Depht", 0))
  bsizer.AddWindow(rb3, 0, wxEXPAND)
  bSizer.AddSpacer(10)

  Dim ars4 As wxArrayString = wxArrayString()
  ars4.Add(_("default"))
  ars4.Add("20 kHz")
  ars4.Add("44.1 kHz (CD)")
  ars4.Add("48.0 kHz (Movie)")
  ars4.Add("96.0 kHz (Studio)")
  Dim rB4 As wxRadioBox = wxRadioBoxWithArray(plPanel, -1, _("Sample Rate"), wxDefaultPosition, wxDefaultSize, ars4, 1, wxRA_HORIZONTAL|wxRA_SPECIFY_COLS)
  rb4.SetName("samplerate")
  rb4.SetSelection(cfg.Read("Samplerate", 0))
  bsizer.AddWindow(rb4, 0, wxEXPAND)

  gb.AddSizer(bSizer, wxGBPosition(18, 1), wxGBSpan(0, 3), wxEXPAND)
  gb.AddSpacer(5, 5, wxGBPosition(19, 0))

  'create convert button
  Dim bSizer1 As wxBoxSizer = wxBoxSizer(wxHORIZONTAL)
  Dim convertButton = wxBitmapButton(plPanel, -1, iList["convert"])
  Connect(convertButton, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onConvertButtonClick")
  convertButton.SetName("convert")
  convertButton.SetToolTip(_("Start convert process"))
  bsizer1.AddWindow(convertbutton, 0, wxEXPAND)

  Dim txt As wxTextCtrl = wxTextCtrl(plPanel, -1, "", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL)
  txt.SetFont(wxNORMAL_FONT)
  txt.SetName("outctrl")
  bsizer1.AddWindow(txt, wxEXPAND, wxEXPAND)

  gb.AddSizer(bSizer1, wxGBPosition(20, 1), wxGBSpan(0, 3), wxEXPAND)
  gb.AddSpacer(5, 5, wxGBPosition(21, 0))

  Dim Ok As wxButton = wxButton(plPanel, wxID_OK, _("Close"), wxDefaultPosition, wxSize(-1, 30))
  Ok.SetName("closebtn")
  gb.AddWindow(Ok, wxGBPosition(22, 0), wxGBSpan(1, 5), wxEXPAND)

  plPanel.SetAutoLayout(TRUE)
  plPanel.SetSizerAndFit(gb)

  'set the output format
  selectFormat(outFormat)
  
  'enable or disable controls
  selectControls(cb1.GetValue())

  isConvert = FALSE

  'ShowModal don't send an event, if a large file is convert,
  'so I can't break the process and an error is occurs
  'the convert process must terminated with the button and then the dialog can be closed
  sd.ShowModal()

  cfg.Write("ReportMode", cb00.GetValue())
  cfg.Write("IncludeSubs", cb01.GetValue())
  cfg.Write("SourcePath", fileCtrl.GetDirectory())
  cfg.Write("RenameOnly", cb1.GetValue())
  cfg.Write("DeleteSource", cb2.GetValue())
  cfg.Write("Overwrite", cb3.GetValue())
  cfg.Write("AdoptData", cb4.GetValue())
  cfg.Write("Output", rb1.GetSelection())
  cfg.Write("Quality", rb2.GetSelection())
  cfg.Write("Depht", rb3.GetSelection())
  cfg.Write("Samplerate", rb4.GetSelection())
  cfg.Write("AddCounter", outNum.GetValue())
  cfg.Write("FileName", outName.GetValue())
  cfg.Write("ConvPath", convPath.GetPath())

  ars1.Clear()
  ars2.Clear()
  ars3.Clear()
  ars4.Clear()
  sd.Destroy()
End Sub


Sub onSelectFormat(event As wxCommandEvent)
  selectFormat(event.GetSelection())
End Sub


Sub selectFormat(selection As Integer)
  Dim rb2 = DynamicCast("wxRadioBox", wxFindWindowByName("quality"))
  rb2.Enable(TRUE)
  Dim rb3 = DynamicCast("wxRadioBox", wxFindWindowByName("encoding"))
  rb3.Enable(TRUE)
  Dim rb4 = DynamicCast("wxRadioBox", wxFindWindowByName("samplerate"))
  rb4.Enable(TRUE)

  For i = 0 To 19
    rb2.ShowItem(i, TRUE)
  Next

  Select Case selection
  Case 0 'wav
    rb2.Enable(FALSE)

  Case 1: 'flac
    rb2.Enable(FALSE)
    rb3.Enable(TRUE)
    rb4.Enable(TRUE)

  Case 2: 'm4a
    For i = 6 To 7
      rb2.ShowItem(i, FALSE)
    Next
    rb3.Enable(FALSE)

  Case 3: 'aac
    For i = 6 To 7
      rb2.ShowItem(i, FALSE)
    Next
    rb3.Enable(FALSE)

  Case 4: 'opus
    rb2.Enable(TRUE)
    rb3.Enable(FALSE)
    rb4.Enable(FALSE)

    For i = 1 To 5
      rb2.ShowItem(i, FALSE)
    Next
    rb2.ShowItem(18, FALSE)

  Case 5: 'ogg
    For i = 11 To 18
      rb2.ShowItem(i, FALSE)
    Next
    rb3.Enable(FALSE)

  Case 6: 'mp3
    rb2.ShowItem(10, FALSE)
    rb2.ShowItem(17, FALSE)
    rb2.ShowItem(18, FALSE)
  End Select
End Sub


Sub onSetCurDir(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  Dim ctrl = DynamicCast("wxDirPickerCtrl", wxFindWindowByName("browseButton"))

  ctrl.SetPath(fctrl.GetShownDirectory())
End Sub


'start convert process
'read the parameter
Sub onConvertButtonClick(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  If !fCtrl.GetCount() Then Return
  If isplayed Then stopMedia()

  Dim btn = DynamicCast("wxBitmapButton", wxFindWindowByName("convert"))
  Dim Ok = DynamicCast("wxButton", wxFindWindowByName("closebtn"))
  Dim textCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outctrl"))

  isConvert = !isConvert

  If !isConvert Then
    convertFiles.Clear()
    textCtrl.AppendText("... " &_("aborted") &"\n\n")
    If convertPid Then wxProcess_Kill(convertPid, wxSIGKILL)
    
    app.Yield()

  Else

    Dim ctrl = DynamicCast("wxCheckBox", wxFindWindowByName("renameCb"))

    'rename the files
    If ctrl.IsChecked() Then
      renameFiles1()

    'conert the files
    Else

      Dim cmd As String = ""
      errCnt = 0

      Dim rb1 = DynamicCast("wxRadioBox", wxFindWindowByName("format"))
        Dim ext As String
        Select Case rb1.GetSelection()
        Case 0: ext = ".wav" 
        Case 1: ext = ".flac" 
        Case 2: ext = ".m4a" 
        Case 3: ext = ".aac" 
        Case 4: ext = ".opus" 
        Case 5: ext = ".ogg" 
        Case 6: ext = ".mp3" 
        End Select

      Dim rb2 = DynamicCast("wxRadioBox", wxFindWindowByName("quality"))
        If (rb2.GetSelection()> 0) And rb2.IsEnabled() Then
          Dim quality As String = ""
          Dim qName As String = rb2.GetStringSelection()
          Dim at As Integer = InStr(qName, " ")
          Select Case rb1.GetSelection()
          Case 2: quality = " -aac_quality " &qName[: at - 1]
          Case 3: quality = " -opus_quality " &qName[: at - 1]
          Case 4: quality = " -vorbis_quality " &qName[: at - 1]
          Case 6: quality = " -mp3_quality " &qName[: at - 1]
          End Select

          cmd &= quality
        End If

      Dim rb3 = DynamicCast("wxRadioBox", wxFindWindowByName("encoding"))
        If (rb3.GetSelection()> 0) And rb3.IsEnabled() Then
          Dim res As String = ""
          Select Case rb3.GetSelection()
          Case 1: res = " -aformat uint8" 
          Case 2: res = " -aformat int16" 
          Case 3: res = " -aformat int32" 
          Case 4: res = " -aformat float32" 
          End Select

          cmd &= res
        End If

      Dim rb4 = DynamicCast("wxRadioBox", wxFindWindowByName("samplerate"))
        If (rb4.GetSelection()> 0) And rb4.IsEnabled() Then
          Dim rate As String = ""
          Select Case rb4.GetSelection()
          Case 1: rate = " -rate 20000" 
          Case 2: rate = " -rate 44100" 
          Case 3: rate = " -rate 48000" 
          Case 4: rate = " -rate 96000" 
          End Select

          cmd &= rate
        End If

      ctrl = DynamicCast("wxDirPickerCtrl", wxFindWindowByName("browseButton"))
      cmd &= " -o " &Chr(34) &ctrl.GetPath() &DELIMITER_CHAR

      Dim outName As wxTextCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outname"))
      Dim fn As String = outName.GetValue()

      Dim dt As wxDateTime = wxDateTime_Now() 
      If InStr(fn, "@d") Then fn = Replace(fn, "@d", dt.Format("%y_%m_%d"))
      If InStr(fn, "@t") Then fn = Replace(fn, "@t", dt.Format("%H_%M_%S"))

      Dim countCtrl As wxSpinCtrl = DynamicCast("wxSpinCtrl", wxFindWindowByName("counter"))
      Dim counter As Integer = countCtrl.GetValue()
      Dim useCounter As Integer = FALSE
      If InStr(fn, "@c") Then useCounter = TRUE

      cmd&= fn &ext&Chr(34)

      Dim ctrl1 = DynamicCast("wxCheckBox", wxFindWindowByName("ov"))
      If ctrl1.IsChecked() Then cmd&= " -f"

      Dim ctrl2 = DynamicCast("wxCheckBox", wxFindWindowByName("pd"))
      If ctrl2.IsChecked() Then cmd&= " -preserve_date"

      Ok.Enable(FALSE)
      btn.SetBitmap(iList["convertHover"])
      btn.SetBitmapFocus(iList["convertHover"])
      btn.SetToolTip(_("Stop convert process"))
      textCtrl.Clear()
      textCtrl.Refresh()
      app.Yield()

      convertFiles.Clear()
      For i = 0 To  fCtrl.GetCount() - 1
        convertFiles.Add(fCtrl.GetString(i))
      Next

      convertCmd = cmd &":" &counter
      If convertFiles.Count() Then phiolaConvert(convertFiles.Item(0), cmd, IIf(useCounter, counter, 0))
    End If
  End If
End Sub


'convert a file to the new format
'the parameters and the counter are given in the cmd
Sub phiolaConvert(path As String, cmd As String, counter As Integer)
  Dim at = RInstr(convertCmd, ":")
  convertCmd = convertCmd[: at] &counter

  Dim FileName As wxFileName = wxFileName("")
  FileName.AssignPath(path)

  If InStr(cmd, "@f") Then cmd = Replace(cmd, "@f", FileName.GetName())

  If counter > 0 Then
    Dim num As String = Str(counter)
    While Len(num)< 5
      num = "0" &num
    Wend

    cmd = Replace(cmd, "@c", num)
  End If

  'get the real output path
  at = InStr(cmd, "-o ")
  Dim outPath = wordbetween(cmd[at: ], "\"","\"")

  Dim textCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outctrl"))
  textCtrl.AppendText(_("Converting") &" '" &FileName.GetFullName() &"'")

  FileName.AssignPath(outPath)
  Dim errText As String = ""

  If wxFileExists(outPath) And !InStr(cmd, " -f") Then
    errText = _("The file already exists")

  Elseif wxFileExists(outPath) And !FileName.IsFileWritable() Then
    errText = _("The file is write-protected")
  End If

  'the process is not needed, skip the file
  If errText <> "" Then
    errCnt += 1
    textCtrl.AppendText(Space(10) &"..." &errText &"\n")

    'goto next file or set the buttons to normal state
    convertFiles.RemoveAt(0)

    If convertFiles.Count() Then
      at = RInstr(convertCmd, ":")
      phiolaConvert(convertFiles.Item(0),  convertCmd[: at - 1], Val(convertCmd[at + 1: ])+ 1)

    Else

      endConvert()
    End If

    Return
  End If

  infoPrc = New wxProcess(musicFrame, -1)
  infoPrc.Redirect()
  Connect(infoPrc, wxEVT_END_PROCESS, "onEndConvertProcess")

  cmd = Chr(34) &phiolaPath &Chr(34) &" convert "  &Chr(34) &path &Chr(34) &cmd

  convertPid = wxExecute(cmd, wxEXEC_ASYNC, infoPrc)
  If !convertPid Then
    ~infoPrc
    infoPrc = Nothing
  End If

  Dim inStream As wxInputStream = infoPrc.GetInputStream()
  Dim buffer As String = ""

  'read the stream
  If inStream And inStream.IsOk() Then
    Dim cnt As Integer = 0
    While !inStream.Eof()
      cnt += 1
      buffer &= instream.Read(1)
      If cnt % 1000 = 0 Then app.Yield()
    Wend

    'handle more errors here
    If InStr(buffer, "ERROR") Then errText = _("Error")
    If errText <> "" Then
      textCtrl.AppendText(Space(10) &"..." &errText &"\n")
      errCnt += 1
    End If
  End If
End Sub


'end convert
Sub onEndConvertProcess(event As wxProcessEvent)
  convertPid = 0
  app.Yield()

  Dim textCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outctrl"))
  If !event.GetExitCode() Then textCtrl.AppendText(Space(10) &"..." &_("Ok") &"\n")
  
  Dim ctrl = DynamicCast("wxCheckBox", wxFindWindowByName("deleteCb"))
  If ctrl.IsChecked() Then wxRemoveFile(convertFiles.Item(0))

  infoPrc = Nothing
  convertFiles.RemoveAt(0)

  If convertFiles.Count() Then
    Dim at = RInstr(convertCmd, ":")
    phiolaConvert(convertFiles.Item(0),  convertCmd[: at - 1], Val(convertCmd[at + 1: ])+ 1)

  Else

    endConvert()
  End If
End Sub


Sub endConvert()
  Dim btn = DynamicCast("wxBitmapButton", wxFindWindowByName("convert"))
  btn.SetBitmap(iList["convert"])
  btn.SetBitmapFocus(wxNullBitmap)
  btn.SetToolTip(_("Start convert process"))

  Dim Ok = DynamicCast("wxButton", wxFindWindowByName("closebtn"))
  Ok.Enable(TRUE)

  dim textCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outctrl"))
  textCtrl.AppendText(_("Conversion ended with") &" " &errCnt &" " &_("errors") &"\n")

  isConvert = FALSE
End Sub


'set the rename mode and enable the needed controls
Sub onRenameMode(event As wxCommandEvent)
  selectControls(event.GetSelection())
End Sub


'enable or disable controls
Sub selectControls(isRename As Integer)
  Dim rb1 = DynamicCast("wxRadioBox", wxFindWindowByName("format"))
  Dim rb2 = DynamicCast("wxRadioBox", wxFindWindowByName("quality"))
  Dim rb3 = DynamicCast("wxRadioBox", wxFindWindowByName("encoding"))
  Dim rb4 = DynamicCast("wxRadioBox", wxFindWindowByName("samplerate"))
  Dim ctrl1 = DynamicCast("wxCheckBox", wxFindWindowByName("deleteCb"))
  Dim ctrl2 = DynamicCast("wxCheckBox", wxFindWindowByName("pd"))
  Dim ctrl3 = DynamicCast("wxCheckBox", wxFindWindowByName("ov"))

  rb1.Enable( !isRename)
  rb2.Enable( !isRename)
  rb3.Enable( !isRename)
  rb4.Enable( !isRename)
  ctrl1.Enable( !isRename)
  ctrl2.Enable( !isRename)
  ctrl3.Enable( !isRename)

  If !isRename Then
    'set the output format
    Dim cfg As wxFileConfig = wxFileConfig("", "", playerIni)
    cfg.SetPath("/Convert")
    Dim outFormat = cfg.Read("Output", 0)
    rb1.SetSelection(outFormat)
    selectFormat(outFormat)
  End If
End Sub


'rename the files
Sub renameFiles1()
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  If !fCtrl.GetCount() Then Return

  Dim ctrl = DynamicCast("wxButton", wxFindWindowByName("browseButton"))
  Dim outPath As String = ctrl.GetLabel() &DELIMITER_CHAR

  Dim outName As wxTextCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outname"))
  Dim fn As String = outName.GetValue()

  Dim dt As wxDateTime = wxDateTime_Now() 
  If InStr(fn, "@d") Then fn = Replace(fn, "@d", dt.Format("%y_%m_%d"))
  If InStr(fn, "@t") Then fn = Replace(fn, "@t", dt.Format("%H_%M_%S"))
  outPath &= fn

  Dim useCounter As Integer = FALSE
  If InStr(fn, "@c") Then useCounter = TRUE

  Dim countCtrl As wxSpinCtrl = DynamicCast("wxSpinCtrl", wxFindWindowByName("counter"))
  Dim counter As Integer = countCtrl.GetValue()

  ctrl = DynamicCast("wxCheckBox", wxFindWindowByName("ov"))
  Dim ov As Integer = ctrl.IsChecked()

  ctrl = DynamicCast("wxCheckBox", wxFindWindowByName("deleteCb"))
  Dim isDel = ctrl.IsChecked()

  Dim path As String
  Dim textCtrl = DynamicCast("wxTextCtrl", wxFindWindowByName("outctrl"))
  textCtrl.Clear()

  Dim curPath As String
  Dim Ok As Integer
  Dim errCounter As Integer = 0
  Dim FileName As wxFileName = wxFileName("")
  Dim noLog = wxLogNull()
  Dim ext As String

  For i = 0 To fCtrl.GetCount() - 1
    curPath = outPath
    path = fCtrl.GetString(i)

    FileName.AssignPath(path)
    ext = FileName.GetExt()

    If InStr(curPath, "@f") Then curPath = Replace(curPath, "@f", FileName.GetName())
    
    If useCounter Then
      Dim num As String = Str(counter)
      While Len(num)< 5
        num = "0" &num
      Wend

      curPath = Replace(curPath, "@c", num)
      counter += 1
    End If

    FileName.AssignPath(curPath)
    FileName.SetExt(ext)
    curPath = FileName.GetFullPath()

    textCtrl.AppendText(_("Rename file") &" " &wxFileNameFromPath(path))

    If wxFileExists(curPath) And !ov Then
      errCounter += 1
      textCtrl.AppendText(Space(10) &"..." &_("The file already exists") &"\n")

    Elseif path = curPath Then
      errCounter += 1
      textCtrl.AppendText(Space(10) &"..." &_("The file cannot overwrite itself") &"\n")

    Elseif wxFileExists(outPath) And !FileName.IsFileWritable() Then
      errCounter += 1
      textCtrl.AppendText(Space(10) &"..." &_("The file is write-protected") &"\n")

    Else
      Ok = wxCopyFile(path, curPath, ov)

      If Ok Then
        textCtrl.AppendText(Space(10) &"..." &_("Ok"))

        If isDel Then
          Ok = wxRemoveFile(path)
          If !Ok Then
            textCtrl.AppendText(Space(10) &"..." &_("Error deleting the source file"))
            errCounter += 1
          End If
        End If
        textCtrl.AppendText("\n")
        
      Else
        errCounter += 1
        textCtrl.AppendText(Space(10) &"..." &_("Error") &"\n")
      End If
    End If
  Next
  ~nolog

  textCtrl.AppendText(_("Rename opreration ended with") &" " &errCounter &" " &_("errors") &"\n")

  'refresh the filectrl
  Dim fctrl1 = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  fCtrl1.Freeze()
  Dim cdir As String = fCtrl1.GetDirectory()
  fCtrl1.GoToParentDir()
  fCtrl1.SetDirectory(cdir)
  fCtrl1.Thaw()
  
  Dim btn = DynamicCast("wxBitmapButton", wxFindWindowByName("convert"))
  btn.SetBitmap(iList["convert"])
  btn.SetBitmapFocus(wxNullBitmap)
  btn.SetToolTip(_("Start convert process"))

  btn = DynamicCast("wxButton", wxFindWindowByName("closebtn"))
  btn.Enable(TRUE)

  isConvert = FALSE
End Sub
