     { "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 read [ 4 read le> [ <uint> ] [ read ] bi 3append ] [ f ] if* ;
+    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= ;

        { [ 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&&

C-STRUCT: riff-chunk
    { "riff-chunk-header" "header" }
    { "char[4]" "format" }
    ;

C-STRUCT: wav-fmt-chunk
