 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 ;

        read-png-header
        read-png-chunks
        parse-ihdr-chunk
        fill-image-data
        decode-png
    ] with-input-stream ;


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

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


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

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

: inflate-data ( loading-png -- bytes )
    zlib-data zlib-inflate ; 

: decode-greyscale ( loading-png -- loading-png )
    unimplemented-color-type ;

: png-image-bytes ( loading-png -- byte-array )
    [ inflate-data ] [ width>> 3 * 1 + ] bi group
    reverse-png-filter ;

: decode-truecolor ( loading-png -- loading-png )
    [ <image> ] dip {
        [ png-image-bytes >>bitmap ]
        [ [ width>> ] [ height>> ] bi 2array >>dim ]
        [ drop RGB >>component-order ]
    } cleave ;
    
: decode-indexed-color ( loading-png -- loading-png )
    unimplemented-color-type ;

: decode-greyscale-alpha ( loading-png -- loading-png )
    unimplemented-color-type ;

: decode-truecolor-alpha ( loading-png -- loading-png )
    unimplemented-color-type ;

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