;; Convert the studio's stereo 32 kHz, 16-bit PCM WAV into headerless PCM.
(module
  (memory (export "memory") 1 2048)
  (global $length (mut i32) (i32.const 0))
  (func (export "allocate") (param $length i32) (result i32)
    (local $pages i32)
    (local.set $pages (i32.shr_u (i32.add (local.get $length) (i32.const 66559)) (i32.const 16)))
    (if (i32.gt_u (local.get $pages) (memory.size))
      (then
        (if (i32.eq (memory.grow (i32.sub (local.get $pages) (memory.size))) (i32.const -1))
          (then (return (i32.const -1))))))
    (i32.const 1024))
  (func (export "convert") (param $start i32) (param $length i32) (result i32)
    (local $payload i32)
    (if (i32.lt_u (local.get $length) (i32.const 44)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load (local.get $start)) (i32.const 0x46464952)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load offset=8 (local.get $start)) (i32.const 0x45564157)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load offset=20 (local.get $start)) (i32.const 0x00020001)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load offset=24 (local.get $start)) (i32.const 32000)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load16_u offset=34 (local.get $start)) (i32.const 16)) (then (return (i32.const -1))))
    (if (i32.ne (i32.load offset=36 (local.get $start)) (i32.const 0x61746164)) (then (return (i32.const -1))))
    (local.set $payload (i32.load offset=40 (local.get $start)))
    (if (i32.gt_u (local.get $payload) (i32.sub (local.get $length) (i32.const 44))) (then (return (i32.const -1))))
    (global.set $length (local.get $payload))
    (i32.add (local.get $start) (i32.const 44)))
  (func (export "result_length") (result i32) (global.get $length)))
