# Sony PS2 .XWH/.XWB pairs
# original script by RENINKRILL(http://forum.xentax.com/viewtopic.php?p=64747#p64747)
# expanded by AnonBaiter to include the ATRAC3 codec used in later PS2 games developed/published by SCEI

open FDDE "XWH" 0
open FDDE "XWB" 1

math ATRAC3 = 0

idstring "RXWS"
get RXWSsz long   # minus 16byte header
get UNKNOWN long   # 0x200
get NULL long
idstring FORM
get FORMsz long   # -16
get UNKNOWN long   # 0x100
get NULL long
get STREAMS long

set FTXT_LOC long FORMsz
math FTXT_LOC += 0x20
goto FTXT_LOC
idstring FTXT
get FTXTsz long
get UNKNOWN long   # 0x100
get NULL long
savepos FTXT_LOC
log MEMORY_FILE FTXT_LOC FTXTsz
get STREAMS2 long MEMORY_FILE   # synonymous with 'STREAMS' value

goto 0x24

for i = 0 < STREAMS
   get UNK1 short   # 0x1c00
   get UNK2 short
   get UNK3 long   # 0x7f7f
   get UNK4 short
   get FREQUENCY short
   get NULL long
   get OFFSET long
   if UNK4 == 0x200
      get SIZE long
   else
      get UNK5 long
      xmath SIZE1 "UNK5 / 5"
   endif
   get LOOP_POS long
   
   get STPOS long MEMORY_FILE
   savepos MFPOS MEMORY_FILE
   goto STPOS MEMORY_FILE
   get NAME string MEMORY_FILE
   goto MFPOS MEMORY_FILE
   putarray 0 i OFFSET
   putarray 1 i SIZE1
   putarray 2 i UNK1
   putarray 3 i UNK2
   putarray 4 i UNK3
   putarray 5 i UNK4
   putarray 6 i FREQUENCY
   putarray 7 i NULL
   putarray 8 i OFFSET
   putarray 9 i LOOP_POS
   putarray 10 i NAME

   if UNK4 == 0x200
      callfunction RXW 1
   else
      math ATRAC3 = 1
   endif
next i

if ATRAC3 = 1
   get OFFSET asize 1
   putarray 0 i OFFSET
   for i = 0 < STREAMS
      getarray OFFSET 0 i
      getarray SIZE1 1 i
      getarray UNK1 2 i
      getarray UNK2 3 i
      getarray UNK3 4 i
      getarray UNK4 5 i
      getarray FREQUENCY 6 i
      getarray NULL 7 i
      getarray OFFSET 8 i
      getarray LOOP_POS 9 i
      getarray NAME 10 i
      math i + 1
      getarray SIZE 0 i
      math SIZE - OFFSET
      putarray 3 i SIZE
      xmath REMAINING "SIZE1 - SIZE"
      putarray 4 i REMAINING
      xmath FINAL_SIZE "SIZE1 - REMAINING"
      putarray 5 i FINAL_SIZE
      math FINAL_SIZE == SIZE
      callfunction RXW 1
      math i - 1
   next i
endif

startfunction RXW
   set MEMORY_FILE2 binary "\x52\x58\x57\x53\x30\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x46\x4F\x52\x4D\x20\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
   putvarchr MEMORY_FILE2 0x24 UNK1 short
   putvarchr MEMORY_FILE2 0x26 UNK4 short
   putvarchr MEMORY_FILE2 0x28 UNK3 long
   putvarchr MEMORY_FILE2 0x2c UNK4 short
   putvarchr MEMORY_FILE2 0x2e FREQUENCY short
   putvarchr MEMORY_FILE2 0x38 SIZE long
   putvarchr MEMORY_FILE2 0x3c LOOP_POS long
   append
   log MEMORY_FILE2 OFFSET SIZE 1
   append
   string NAME += ".rxw"

   math SIZE += 0x40
   log NAME 0 SIZE MEMORY_FILE2
endfunction