EnableExplicit

Procedure DPrint(xString.s)
  PrintN(xString)
  Debug(xString)
  EndProcedure

Procedure.i MyFileCopyData(hFile1.i, hFile2.i, NumBytes.i)
  Define.i xResult
  Define *Mem
  *Mem = AllocateMemory(NumBytes)
  If *Mem
    If ReadData(hFile1, *Mem, NumBytes)
      If WriteData(hFile2, *Mem, NumBytes)
        xResult = #True
        EndIf
      EndIf
    FreeMemory(*Mem)
    EndIf
  ProcedureReturn xResult
  EndProcedure

Define.i hFile
Define.i xSize2
Define.i xFile2
Define.i xSize
Define.s xFNO
Define.i xLong1
Define *Mem

OpenConsole()
hFile = ReadFile(#PB_Any, "music_p.lsd")
If hFile
  DPrint("Extracting music...")
  Else
  hFile = ReadFile(#PB_Any, "sound_p.lsd")
  If hFile
    DPrint("Extracting sounds...")
    EndIf
  EndIf
If hFile
  ReadLong(hFile)
  Repeat
    If Eof(hFile)
      DPrint("  ok")
      Break
      EndIf
    *Mem = AllocateMemory(33)
    If Not *Mem
      DPrint("  out of memory!")
      Break
      EndIf
    ReadData(hFile, *Mem, 32)
    xFNO = PeekS(*Mem, 32, #PB_Ascii)
    FreeMemory(*Mem)
    xSize = ReadLong(hFile)
    DPrint("  " + xFNO + ".wav")
    xFile2 = CreateFile(#PB_Any, xFNO + ".wav")
    If Not xFile2
      DPrint("  Cannot create output file!")
      Break
      EndIf
    WriteLong(xFile2, $46464952) ; RIFF
    WriteLong(xFile2, xSize + 2 + 36)
    WriteLong(xFile2, $45564157) ; WAVE
    WriteLong(xFile2, $20746D66) ; fmt<$20>
    WriteLong(xFile2, $00000010) ; for PCM
    If Not MyFileCopyData(hFile, xFile2, $10)
      DPrint("  Failed to write to output file!")
      Break
      EndIf
    WriteLong(xFile2, $61746164) ; data
    WriteLong(xFile2, xSize + 2)
    If Not MyFileCopyData(hFile, xFile2, xSize + 2)
      DPrint("  Failed to write to output file!")
      Break
      EndIf
    If Loc(xFile2) <> xSize + 2 + 44
      DPrint("  Failed to write to output file!")
      Break
      EndIf
    CloseFile(xFile2)
    ForEver
  CloseFile(hFile)
  EndIf
CloseConsole()
; IDE Options = PureBasic 5.31 (Windows - x86)
; ExecutableFormat = Console
; CursorPosition = 3
; Folding = -
; Executable = LSD Extractor.exe
; CompileSourceDirectory
; EnablePurifier