;; Wrap stereo 32 kHz, little-endian 16-bit headerless PCM in a WAV file.
(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 $head i32)
    (if (i32.and (local.get $length) (i32.const 3)) (then (return (i32.const -1))))
    (local.set $head (i32.sub (local.get $start) (i32.const 44)))
    (i32.store (local.get $head) (i32.const 0x46464952))
    (i32.store offset=4 (local.get $head) (i32.add (local.get $length) (i32.const 36)))
    (i32.store offset=8 (local.get $head) (i32.const 0x45564157))
    (i32.store offset=12 (local.get $head) (i32.const 0x20746d66))
    (i32.store offset=16 (local.get $head) (i32.const 16))
    (i32.store offset=20 (local.get $head) (i32.const 0x00020001))
    (i32.store offset=24 (local.get $head) (i32.const 32000))
    (i32.store offset=28 (local.get $head) (i32.const 128000))
    (i32.store offset=32 (local.get $head) (i32.const 0x00100004))
    (i32.store offset=36 (local.get $head) (i32.const 0x61746164))
    (i32.store offset=40 (local.get $head) (local.get $length))
    (global.set $length (i32.add (local.get $length) (i32.const 44)))
    (local.get $head))
  (func (export "result_length") (result i32) (global.get $length)))
