 SINGLETON: png-image
 "png" png-image register-image-class
 
-TUPLE: loading-png < image chunks
-width height bit-depth color-type compression-method
-filter-method interlace-method uncompressed ;
+TUPLE: loading-png
+    chunks
+    width height bit-depth color-type compression-method
+    filter-method interlace-method uncompressed ;
 
 CONSTRUCTOR: loading-png ( -- image )
     V{ } clone >>chunks ;

        [ [ 12 ] dip nth >>interlace-method ]
    } cleave ;

: find-compressed-bytes ( image -- bytes )
    chunks>> [ type>> "IDAT" = ] filter
    [ data>> ] map concat ;

: fill-image-data ( image -- image )
    dup [ width>> ] [ height>> ] bi 2array >>dim ;

: zlib-data ( png-image -- bytes ) 
    chunks>> [ type>> "IDAT" = ] find nip data>> ;

ERROR: unknown-color-type n ;
ERROR: unimplemented-color-type image ;

: inflate-data ( image -- bytes )
    zlib-data zlib-inflate ; 

: decode-greyscale ( image -- image )
    unimplemented-color-type ;

: decode-truecolor ( image -- image )
    {
        [ inflate-data ]
        [ dim>> first 3 * 1 + group reverse-png-filter ]
        [ swap >byte-array >>bitmap drop ]
        [ RGB >>component-order drop ]
        [ ]
    } cleave ;
    
: decode-indexed-color ( image -- image )
    unimplemented-color-type ;

: decode-greyscale-alpha ( image -- image )
    unimplemented-color-type ;

: decode-truecolor-alpha ( image -- image )
    unimplemented-color-type ;

: decode-png ( image -- image ) 
    dup color-type>> {
        { 0 [ decode-greyscale ] }
        { 2 [ decode-truecolor ] }


ERROR: bad-checksum ;

: read-png-chunks ( loading-png -- loading-png )
    <png-chunk>
    4 read be> [ >>length ] [ 4 + ] bi
    read dup crc32 checksum-bytes
    4 read = [ bad-checksum ] unless
    4 cut-slice
    [ ascii decode >>type ] [ B{ } like >>data ] bi*
    [ over chunks>> push ] 
    [ type>> ] bi "IEND" =
    [ read-png-chunks ] unless ;

: find-chunk ( loading-png string -- chunk )
    [ chunks>> ] dip '[ type>> _ = ] find nip ;

: parse-ihdr-chunk ( loading-png -- loading-png )
    dup "IHDR" find-chunk data>> {
        [ [ 0 4 ] dip subseq be> >>width ]
        [ [ 4 8 ] dip subseq be> >>height ]
