 ! Copyright (C) 2009 Doug Coleman.
 ! See http://factorcode.org/license.txt for BSD license.
-USING: accessors arrays assocs byte-arrays classes combinators
-compression.lzw endian fry grouping images io
-io.binary io.encodings.ascii io.encodings.binary
-io.encodings.string io.encodings.utf8 io.files kernel math
-math.bitwise math.order math.parser pack sequences
-strings math.vectors specialized-arrays locals
-images.loader io.streams.throwing ;
-FROM: alien.c-types => float ;
-SPECIALIZED-ARRAY: float
+USING: accessors arrays assocs byte-arrays combinators
+combinators.short-circuit compression.lzw endian fry grouping
+images images.loader io io.binary io.encodings.ascii
+io.encodings.string io.encodings.utf8 io.streams.throwing kernel
+math math.bitwise math.vectors pack sequences ;
 IN: images.tiff
 
 SINGLETON: tiff-image
 
-TUPLE: loading-tiff endianness the-answer ifd-offset ifds ;
+TUPLE: loading-tiff endianness the-answer ifd-offset ifd-offsets ifds ;
 
 : <loading-tiff> ( -- tiff )
-    loading-tiff new V{ } clone >>ifds ;
-
-TUPLE: ifd count ifd-entries next
-processed-tags strips bitmap ;
-
-: <ifd> ( count ifd-entries next -- ifd )
+    loading-tiff new
+        H{ } clone >>ifds ; inline
+
+! offset, next-offset, and count are not strictly necessary here
+! count is just the length of ifd-entries
+TUPLE: ifd offset next-offset count
+ifd-entries processed-tags strips bitmap ;
+
+: <ifd> ( offset count ifd-entries next-offset -- ifd )
     ifd new
-        swap >>next
+        swap >>next-offset
         swap >>ifd-entries
-        swap >>count ;
+        swap >>count
+        swap >>offset ;
 
 TUPLE: ifd-entry tag type count offset/value ;
 

        [ seek-absolute seek-input read ] { } 2map-as
    ] if >>strips ;

ERROR: unknown-ifd-type n ;

: bytes>bits ( n/byte-array -- n )
    dup byte-array? [ le> ] when ;

: value-length ( ifd-entry -- n )
    [ count>> ] [ type>> ] bi {
        { 1 [ ] }

        [
            dup ifd-entries>>
            [ process-ifd-entry swap ] H{ } map>assoc >>processed-tags
        ] assoc-map
    ] change-ifds ;

ERROR: unhandled-compression compression ;
