 
 : read-wav ( filename -- audio )
     binary [
-        read-chunk
-        [ verify-wav ]
-        [ riff-chunk-body <memory-stream> [ (read-wav) ] with-input-stream* ] bi
+        read-riff-chunk verify-wav (read-wav)
     ] with-file-reader ;

        { [ dup DATA-MAGIC id= ] [ data! ] }
    } cond ] while drop
    fmt data ;

ERROR: invalid-wav-file ;

: verify-wav ( chunk -- )
    { [ RIFF-MAGIC id= ] [ riff-chunk-format WAVE-MAGIC id= ] } 1&&

    { "uchar[0]" "body" }
    ;

ERROR: invalid-wav-file ;

: ensured-read ( count -- output/f )
    [ read ] keep over length = [ drop f ] unless ;
: ensured-read* ( count -- output )
    ensured-read [ invalid-wav-file ] unless* ;

: read-chunk ( -- byte-array/f )
    4 ensured-read [ 4 ensured-read* dup le> ensured-read* 3append ] [ f ] if* ;
: read-riff-chunk ( -- byte-array/f )
    "riff-chunk" heap-size ensured-read* ;

: id= ( chunk id -- ? )
    [ 4 memory>byte-array ] dip sequence= ;
