diff --git a/JuicyPixels.cabal b/JuicyPixels.cabal
--- a/JuicyPixels.cabal
+++ b/JuicyPixels.cabal
@@ -1,98 +1,554 @@
-Name:                JuicyPixels
-Version:             3.3.9
-Synopsis:            Picture loading/serialization (in png, jpeg, bitmap, gif, tga, tiff and radiance)
-Description:
-    <<data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADABAMAAACg8nE0AAAAElBMVEUAAABJqDSTWEL/qyb///8AAABH/1GTAAAAAXRSTlMAQObYZgAAAN5JREFUeF7s1sEJgFAQxFBbsAV72v5bEVYWPwT/XDxmCsi7zvHXavYREBDI3XP2GgICqBBYuwIC+/rVayPUAyAg0HvIXBcQoDFDGnUBgWQQ2Bx3AYFaRoBpAQHWb3bt2ARgGAiCYFFuwf3X5HA/McgGJWI2FdykCv4aBYzmKwDwvl6NVmUAAK2vlwEALK7fo88GANB6HQsAAAAAAAAA7P94AQCzswEAAAAAAAAAAAAAAAAAAICzh4UAO4zWAYBfRutHA4Bn5C69JhowAMGoBaMWDG0wCkbBKBgFo2AUAACPmegUST/IJAAAAABJRU5ErkJggg==>>
-    .
-    This library can load and store images in PNG,Bitmap, Jpeg, Radiance, Tiff and Gif images.
-
-homepage:            https://github.com/Twinside/Juicy.Pixels
-License:             BSD3
-License-file:        LICENSE
-Author:              Vincent Berthoux
-Maintainer:          vincent.berthoux@gmail.com
-Category:            Codec, Graphics, Image
-Stability:           Stable
-Build-type:          Simple
-cabal-version: 1.18
-tested-with:
-  GHC == 9.8.1
-  GHC == 9.6.4
-  GHC == 9.4.8
-  GHC == 9.2.8
-  GHC == 9.0.2
-  GHC == 8.10.7
-  GHC == 8.8.4
-  GHC == 8.6.5
-  GHC == 8.4.4
-  GHC == 8.2.2
-  GHC == 8.0.2
-
-extra-doc-files: changelog, docimages/*.png, docimages/*.svg, README.md
-extra-doc-files: docimages/*.png, docimages/*.svg
-
-Source-Repository head
-    Type:      git
-    Location:  git://github.com/Twinside/Juicy.Pixels.git
-
-Source-Repository this
-    Type:      git
-    Location:  git://github.com/Twinside/Juicy.Pixels.git
-    Tag:       v3.3.8
-
-Flag Mmap
-    Description: Enable the file loading via mmap (memory map)
-    Default: False
-
-Library
-  hs-source-dirs: src
-  Default-Language: Haskell2010
-  default-extensions: TypeOperators
-  Exposed-modules:  Codec.Picture,
-                    Codec.Picture.Bitmap,
-                    Codec.Picture.Gif,
-                    Codec.Picture.Png,
-                    Codec.Picture.Jpg,
-                    Codec.Picture.HDR,
-                    Codec.Picture.Tga,
-                    Codec.Picture.Tiff,
-                    Codec.Picture.Metadata,
-                    Codec.Picture.Metadata.Exif,
-                    Codec.Picture.Saving,
-                    Codec.Picture.Types,
-                    Codec.Picture.ColorQuant,
-                    Codec.Picture.Jpg.Internal.DefaultTable,
-                    Codec.Picture.Jpg.Internal.Metadata,
-                    Codec.Picture.Jpg.Internal.FastIdct,
-                    Codec.Picture.Jpg.Internal.FastDct,
-                    Codec.Picture.Jpg.Internal.Types,
-                    Codec.Picture.Jpg.Internal.Common,
-                    Codec.Picture.Jpg.Internal.Progressive,
-                    Codec.Picture.Gif.Internal.LZW,
-                    Codec.Picture.Gif.Internal.LZWEncoding,
-                    Codec.Picture.Png.Internal.Export,
-                    Codec.Picture.Png.Internal.Type,
-                    Codec.Picture.Png.Internal.Metadata,
-                    Codec.Picture.Tiff.Internal.Metadata,
-                    Codec.Picture.Tiff.Internal.Types
-
-  Ghc-options: -O3 -Wall
-  Build-depends: base                >= 4.8     && < 5,
-                 bytestring          >= 0.9     && < 0.13,
-                 mtl                 >= 1.1     && < 2.4,
-                 binary              >= 0.8.1   && < 0.9,
-                 zlib                >= 0.5.3.1 && < 0.8,
-                 transformers        >= 0.2,
-                 vector              >= 0.12.3.1,
-                 primitive           >= 0.4,
-                 deepseq             >= 1.1     && < 1.6,
-                 containers          >= 0.4.2   && < 0.8
-
-  -- Modules not exported by this package.
-  Other-modules: Codec.Picture.BitWriter,
-                 Codec.Picture.InternalHelper,
-                 Codec.Picture.VectorByteConversion
-
-  Install-Includes: src/Codec/Picture/ConvGraph.hs
-  Include-Dirs: src/Codec/Picture
-
+Cabal-version:       1.18
+  -- Constraint on the version of Cabal needed to build this package.
+  -- NB: 3.0 is the first to support globs like 'tests/**/*.png' correctly.
+
+Name:                JuicyPixels
+Version:             3.3.10
+Synopsis:            Picture loading/serialization (in png, jpeg, bitmap, gif, tga, tiff and radiance)
+Description:
+    <<data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADABAMAAACg8nE0AAAAElBMVEUAAABJqDSTWEL/qyb///8AAABH/1GTAAAAAXRSTlMAQObYZgAAAN5JREFUeF7s1sEJgFAQxFBbsAV72v5bEVYWPwT/XDxmCsi7zvHXavYREBDI3XP2GgICqBBYuwIC+/rVayPUAyAg0HvIXBcQoDFDGnUBgWQQ2Bx3AYFaRoBpAQHWb3bt2ARgGAiCYFFuwf3X5HA/McgGJWI2FdykCv4aBYzmKwDwvl6NVmUAAK2vlwEALK7fo88GANB6HQsAAAAAAAAA7P94AQCzswEAAAAAAAAAAAAAAAAAAICzh4UAO4zWAYBfRutHA4Bn5C69JhowAMGoBaMWDG0wCkbBKBgFo2AUAACPmegUST/IJAAAAABJRU5ErkJggg==>>
+    .
+    This library can load and store images in PNG,Bitmap, Jpeg, Radiance, Tiff and Gif images.
+
+homepage:            https://github.com/Twinside/Juicy.Pixels
+License:             BSD3
+License-file:        LICENSE
+Author:              Vincent Berthoux
+Maintainer:          vincent.berthoux@gmail.com
+Category:            Codec, Graphics, Image
+Stability:           Stable
+Build-type:          Simple
+
+tested-with:
+  GHC == 9.14.1
+  GHC == 9.12.3
+  GHC == 9.10.3
+  GHC == 9.8.1
+  GHC == 9.6.4
+  GHC == 9.4.8
+  GHC == 9.2.8
+  GHC == 9.0.2
+  GHC == 8.10.7
+  GHC == 8.8.4
+  GHC == 8.6.5
+  GHC == 8.4.4
+  GHC == 8.2.2
+  GHC == 8.0.2
+
+extra-doc-files: changelog, docimages/*.png, docimages/*.svg, README.md
+
+extra-source-files:
+  -- tests/pngsuite
+  tests/pngsuite/s39i3p04.png
+  tests/pngsuite/s38i3p04.png
+  tests/pngsuite/s05n3p02.png
+  tests/pngsuite/cs5n2c08.png
+  tests/pngsuite/bgwn6a08.png
+  tests/pngsuite/xc1n0g08.png
+  tests/pngsuite/basn3p02.png
+  tests/pngsuite/bggn4a16.png
+  tests/pngsuite/tbgn3p08.png
+  tests/pngsuite/basi0g08.png
+  tests/pngsuite/bgbn4a08.png
+  tests/pngsuite/basn4a16.png
+  tests/pngsuite/s04n3p01.png
+  tests/pngsuite/s33i3p04.png
+  tests/pngsuite/s32i3p04.png
+  tests/pngsuite/cm0n0g04.png
+  tests/pngsuite/basn3p01.png
+  tests/pngsuite/basi2c08.png
+  tests/pngsuite/bgyn6a16.png
+  tests/pngsuite/ps1n2c16.png
+  tests/pngsuite/g03n3p04.png
+  tests/pngsuite/xs1n0g01.png
+  tests/pngsuite/basn6a16.png
+  tests/pngsuite/ccwn3p08.png
+  tests/pngsuite/oi1n2c16.png
+  tests/pngsuite/f03n0g08.png
+  tests/pngsuite/f02n0g08.png
+  tests/pngsuite/oi1n0g16.png
+  tests/pngsuite/s06i3p02.png
+  tests/pngsuite/tbyn3p08.png
+  tests/pngsuite/s07i3p02.png
+  tests/pngsuite/cdhn2c08.png
+  tests/pngsuite/f03n2c08.png
+  tests/pngsuite/f02n2c08.png
+  tests/pngsuite/cs8n3p08.png
+  tests/pngsuite/basn3p04.png
+  tests/pngsuite/g04n0g16.png
+  tests/pngsuite/g05n0g16.png
+  tests/pngsuite/cthn0g04.png
+  tests/pngsuite/cs3n3p08.png
+  tests/pngsuite/bgai4a08.png
+  tests/pngsuite/xhdn0g08.png
+  tests/pngsuite/basi3p08.png
+  tests/pngsuite/g05n3p04.png
+  tests/pngsuite/g04n3p04.png
+  tests/pngsuite/xs7n0g01.png
+  tests/pngsuite/bgan6a16.png
+  tests/pngsuite/f04n0g08.png
+  tests/pngsuite/ct0n0g04.png
+  tests/pngsuite/ct1n0g04.png
+  tests/pngsuite/f04n2c08.png
+  tests/pngsuite/tbbn2c16.png
+  tests/pngsuite/cten0g04.png
+  tests/pngsuite/basn0g01.png
+  tests/pngsuite/g03n0g16.png
+  tests/pngsuite/basn2c16.png
+  tests/pngsuite/s40n3p04.png
+  tests/pngsuite/xdtn0g01.png
+  tests/pngsuite/basi4a08.png
+  tests/pngsuite/cs5n3p08.png
+  tests/pngsuite/s37n3p04.png
+  tests/pngsuite/s36n3p04.png
+  tests/pngsuite/s01i3p01.png
+  tests/pngsuite/xcsn0g01.png
+  tests/pngsuite/g07n2c08.png
+  tests/pngsuite/basn0g02.png
+  tests/pngsuite/basn0g16.png
+  tests/pngsuite/PngSuite.README
+  tests/pngsuite/tbrn2c08.png
+  tests/pngsuite/tbbn0g04.png
+  tests/pngsuite/g25n2c08.png
+  tests/pngsuite/xcrn0g04.png
+  tests/pngsuite/PngSuite.png
+  tests/pngsuite/basi6a08.png
+  tests/pngsuite/tbwn0g16.png
+  tests/pngsuite/xd0n2c08.png
+  tests/pngsuite/z03n2c08.png
+  tests/pngsuite/s08n3p02.png
+  tests/pngsuite/s09n3p02.png
+  tests/pngsuite/pp0n6a08.png
+  tests/pngsuite/cs8n2c08.png
+  tests/pngsuite/f99n0g04.png
+  tests/pngsuite/ps2n0g08.png
+  tests/pngsuite/s34i3p04.png
+  tests/pngsuite/s35i3p04.png
+  tests/pngsuite/huge.png
+  tests/pngsuite/ctzn0g04.png
+  tests/pngsuite/s03n3p01.png
+  tests/pngsuite/s02n3p01.png
+  tests/pngsuite/z09n2c08.png
+  tests/pngsuite/g10n2c08.png
+  tests/pngsuite/cm7n0g04.png
+  tests/pngsuite/ccwn2c08.png
+  tests/pngsuite/basn0g04.png
+  tests/pngsuite/g07n0g16.png
+  tests/pngsuite/basi3p01.png
+  tests/pngsuite/basn2c08.png
+  tests/pngsuite/PngSuite.LICENSE
+  tests/pngsuite/oi9n2c16.png
+  tests/pngsuite/basi4a16.png
+  tests/pngsuite/s04i3p01.png
+  tests/pngsuite/ctjn0g04.png
+  tests/pngsuite/s33n3p04.png
+  tests/pngsuite/s32n3p04.png
+  tests/pngsuite/oi9n0g16.png
+  tests/pngsuite/g03n2c08.png
+  tests/pngsuite/basn0g08.png
+  tests/pngsuite/xs2n0g01.png
+  tests/pngsuite/basi3p02.png
+  tests/pngsuite/tp0n2c08.png
+  tests/pngsuite/bgan6a08.png
+  tests/pngsuite/oi2n2c16.png
+  tests/pngsuite/f00n0g08.png
+  tests/pngsuite/f01n0g08.png
+  tests/pngsuite/s05i3p02.png
+  tests/pngsuite/oi2n0g16.png
+  tests/pngsuite/f00n2c08.png
+  tests/pngsuite/f01n2c08.png
+  tests/pngsuite/s39n3p04.png
+  tests/pngsuite/s38n3p04.png
+  tests/pngsuite/tp0n0g08.png
+  tests/pngsuite/tbgn2c16.png
+  tests/pngsuite/cdun2c08.png
+  tests/pngsuite/xc9n2c08.png
+  tests/pngsuite/g10n0g16.png
+  tests/pngsuite/ch1n3p04.png
+  tests/pngsuite/ps2n2c16.png
+  tests/pngsuite/basi3p04.png
+  tests/pngsuite/cs3n2c16.png
+  tests/pngsuite/s06n3p02.png
+  tests/pngsuite/s07n3p02.png
+  tests/pngsuite/g25n0g16.png
+  tests/pngsuite/z06n2c08.png
+  tests/pngsuite/basi6a16.png
+  tests/pngsuite/cm9n0g04.png
+  tests/pngsuite/cdsn2c08.png
+  tests/pngsuite/tbbn3p08.png
+  tests/pngsuite/ps1n0g08.png
+  tests/pngsuite/basi0g02.png
+  tests/pngsuite/basi0g16.png
+  tests/pngsuite/basn4a08.png
+  tests/pngsuite/s37i3p04.png
+  tests/pngsuite/s36i3p04.png
+  tests/pngsuite/s01n3p01.png
+  tests/pngsuite/s40i3p04.png
+  tests/pngsuite/xd9n2c08.png
+  tests/pngsuite/g25n3p04.png
+  tests/pngsuite/tp1n3p08.png
+  tests/pngsuite/tp0n3p08.png
+  tests/pngsuite/basi2c16.png
+  tests/pngsuite/pp0n2c16.png
+  tests/pngsuite/basi0g01.png
+  tests/pngsuite/g10n3p04.png
+  tests/pngsuite/basn3p08.png
+  tests/pngsuite/xlfn0g04.png
+  tests/pngsuite/xd3n2c08.png
+  tests/pngsuite/z00n2c08.png
+  tests/pngsuite/basi0g04.png
+  tests/pngsuite/s34n3p04.png
+  tests/pngsuite/s35n3p04.png
+  tests/pngsuite/s03i3p01.png
+  tests/pngsuite/s02i3p01.png
+  tests/pngsuite/s08i3p02.png
+  tests/pngsuite/s09i3p02.png
+  tests/pngsuite/tbwn3p08.png
+  tests/pngsuite/g05n2c08.png
+  tests/pngsuite/g04n2c08.png
+  tests/pngsuite/ch2n3p08.png
+  tests/pngsuite/bgai4a16.png
+  tests/pngsuite/cdfn2c08.png
+  tests/pngsuite/basn6a08.png
+  tests/pngsuite/xs4n0g01.png
+  tests/pngsuite/g07n3p04.png
+  tests/pngsuite/oi4n2c16.png
+  tests/pngsuite/oi4n0g16.png
+  tests/pngsuite/megaman.png
+  tests/pngsuite/ctfn0g04.png
+  tests/pngsuite/ctgn0g04.png
+  -- tests/apng
+  tests/apng/APNG-cube.png
+  tests/apng/APNG-Icos4D.png
+  tests/apng/APNG-spinfox.png
+  tests/apng/APNG-pyani.png
+  tests/apng/APNG-clock.png
+  -- tests/tga
+  tests/tga/XING_T24.TGA
+  tests/tga/tgatest.c
+  tests/tga/XING_T32.TGA
+  tests/tga/UBW8.TGA
+  tests/tga/CBW8.TGA
+  tests/tga/CTC16.TGA
+  tests/tga/FLAG_T32.TGA
+  tests/tga/XING_B16.TGA
+  tests/tga/FLAG_B16.TGA
+  tests/tga/UTC16.TGA
+  tests/tga/UTC24.TGA
+  tests/tga/MARBLES.TGA
+  tests/tga/FLAG_B24.TGA
+  tests/tga/FLAG_B32.TGA
+  tests/tga/CCM8.TGA
+  tests/tga/UTC32.TGA
+  tests/tga/XING_B24.TGA
+  tests/tga/UCM8.TGA
+  tests/tga/XING_B32.TGA
+  tests/tga/CTC32.TGA
+  tests/tga/FLAG_T16.TGA
+  tests/tga/CTC24.TGA
+  tests/tga/XING_T16.TGA
+  -- tests/radiance
+  tests/radiance/sunrise.hdr
+  tests/radiance/free_009.hdr
+  -- tests/jpeg
+  tests/jpeg/img_cmyk.jpg
+  tests/jpeg/rgb.jpg
+  tests/jpeg/JPEG_example_JPG_RIP_001.jpg
+  tests/jpeg/Channel_digital_image_CMYK_color.jpg
+  tests/jpeg/JPEG_example_JPG_RIP_010.jpg
+  tests/jpeg/inf_loop02.jpg
+  tests/jpeg/20100713-0107-interleaved2.jpg
+  tests/jpeg/inf_loop01.jpg
+  tests/jpeg/JPEG_example_JPG_RIP_100.jpg
+  tests/jpeg/sheep.jpg
+  tests/jpeg/MCU1.jpg
+  tests/jpeg/bad_decode.jpg
+  tests/jpeg/MCU0.jpg
+  tests/jpeg/MCU5.jpg
+  tests/jpeg/16x16jpeg.jpg
+  tests/jpeg/huge.jpg
+  tests/jpeg/MCU35.jpg
+  tests/jpeg/MCU10.jpg
+  tests/jpeg/avatar.jpg
+  tests/jpeg/borked_render.jpg
+  tests/jpeg/.gitignore
+  tests/jpeg/10x8-samsung-s8.jpg
+  tests/jpeg/fenek.jpg
+  tests/jpeg/JPEG_example_JPG_RIP_050.jpg
+  tests/jpeg/broken.jpg
+  tests/jpeg/8x8jpeg.jpg
+  tests/jpeg/richys-groceries.jpg
+  tests/jpeg/bad.jpg
+  tests/jpeg/JPEG_example_JPG_RIP_025.jpg
+  tests/jpeg/explore_jpeg.jpg
+  tests/jpeg/dunno.jpg
+  tests/jpeg/mand_prgrsv.jpg
+  -- tests/bmp
+  tests/bmp/bitmap_32bits_type0.bmp
+  tests/bmp/simple_bitmap_24bits.bmp
+  tests/bmp/smiley.bmp
+  tests/bmp/eggyra0001.bmp
+  tests/bmp/rle_test.bmp
+  tests/bmp/simple_bitmap_8bits.bmp
+  -- tests/bmp/bmpsuite_good
+  tests/bmp/bmpsuite_good/pal8v5.bmp
+  tests/bmp/bmpsuite_good/pal1.bmp
+  tests/bmp/bmpsuite_good/pal8v4.bmp
+  tests/bmp/bmpsuite_good/pal4rle.bmp
+  tests/bmp/bmpsuite_good/pal8rle.bmp
+  tests/bmp/bmpsuite_good/pal8w124.bmp
+  tests/bmp/bmpsuite_good/rgb32.bmp
+  tests/bmp/bmpsuite_good/pal8topdown.bmp
+  tests/bmp/bmpsuite_good/rgb24pal.bmp
+  tests/bmp/bmpsuite_good/pal8w125.bmp
+  tests/bmp/bmpsuite_good/pal8-0.bmp
+  tests/bmp/bmpsuite_good/pal4.bmp
+  tests/bmp/bmpsuite_good/rgb24.bmp
+  tests/bmp/bmpsuite_good/pal8w126.bmp
+  tests/bmp/bmpsuite_good/pal4gs.bmp
+  tests/bmp/bmpsuite_good/pal8nonsquare.bmp
+  tests/bmp/bmpsuite_good/rgb32bf.bmp
+  tests/bmp/bmpsuite_good/rgb16-565pal.bmp
+  tests/bmp/bmpsuite_good/pal8os2.bmp
+  tests/bmp/bmpsuite_good/pal1bg.bmp
+  tests/bmp/bmpsuite_good/rgb32bfdef.bmp
+  tests/bmp/bmpsuite_good/pal1wb.bmp
+  tests/bmp/bmpsuite_good/pal8gs.bmp
+  tests/bmp/bmpsuite_good/pal8.bmp
+  tests/bmp/bmpsuite_good/rgb16.bmp
+  tests/bmp/bmpsuite_good/rgb16-565.bmp
+  tests/bmp/bmpsuite_good/rgb16bfdef.bmp
+  tests/bmp/simple_bitmap_32bits.bmp
+  tests/planeseparationrgba.png
+  tests/planeseparation.png
+  -- tests/palette
+  tests/palette/lena.png
+  tests/palette/seniors.png
+  tests/palette/frog.png
+  tests/palette/barb.png
+  tests/palette/mandrill.png
+  -- tests/tiff
+  tests/tiff/cramps.tif
+  tests/tiff/jim___gg.tif
+  -- tests/tiff/depth
+  tests/tiff/depth/flower-palette-08.tif
+  tests/tiff/depth/flower-separated-contig-08.tif
+  tests/tiff/depth/flower-rgb-planar-24.tif
+  tests/tiff/depth/flower-separated-planar-08.tif
+  tests/tiff/depth/flower-minisblack-14.tif
+  tests/tiff/depth/flower-rgb-contig-24.tif
+  tests/tiff/depth/flower-rgb-contig-32.tif
+  tests/tiff/depth/flower-minisblack-02.tif
+  tests/tiff/depth/flower-minisblack-16.tif
+  tests/tiff/depth/flower-rgb-planar-32.tif
+  tests/tiff/depth/flower-minisblack-12.tif
+  tests/tiff/depth/flower-minisblack-06.tif
+  tests/tiff/depth/flower-minisblack-10.tif
+  tests/tiff/depth/flower-rgb-contig-08.tif
+  tests/tiff/depth/flower-minisblack-04.tif
+  tests/tiff/depth/flower-rgb-planar-08.tif
+  tests/tiff/depth/flower-rgb-contig-04.tif
+  tests/tiff/depth/flower-minisblack-08.tif
+  tests/tiff/depth/flower-rgb-contig-10.tif
+  tests/tiff/depth/flower-rgb-planar-04.tif
+  tests/tiff/depth/flower-rgb-planar-10.tif
+  tests/tiff/depth/flower-separated-contig-16.tif
+  tests/tiff/depth/flower-rgb-planar-12.tif
+  tests/tiff/depth/flower-separated-planar-16.tif
+  tests/tiff/depth/flower-rgb-contig-12.tif
+  tests/tiff/depth/summary.txt
+  tests/tiff/depth/flower-minisblack-32.tif
+  tests/tiff/depth/flower-rgb-contig-16.tif
+  tests/tiff/depth/flower-rgb-contig-02.tif
+  tests/tiff/depth/flower-rgb-planar-16.tif
+  tests/tiff/depth/flower-rgb-planar-02.tif
+  tests/tiff/depth/flower-rgb-planar-14.tif
+  tests/tiff/depth/flower-rgb-contig-14.tif
+  tests/tiff/depth/flower-minisblack-24.tif
+  tests/tiff/depth/README.txt
+  tests/tiff/depth/flower-palette-02.tif
+  tests/tiff/depth/flower-palette-16.tif
+  tests/tiff/depth/flower-palette-04.tif
+  tests/tiff/quad-tile.tif
+  tests/tiff/oxford.tif
+  tests/tiff/g3test.g3
+  --tests/tiff/other
+  tests/tiff/other/butique-YA16.tif
+  tests/tiff/other/butique-YA8.tif
+  tests/tiff/strike.tif
+  tests/tiff/caspian.tif
+  tests/tiff/ladoga.tif
+  tests/tiff/off_l16.tif
+  tests/tiff/README
+  tests/tiff/g3test.tif
+  tests/tiff/cramps-tile.tif
+  tests/tiff/jim___ah.tif
+  tests/tiff/horizontal-difference-lzw.tiff
+  tests/tiff/rad_YF.tif
+  tests/tiff/text.tif
+  tests/tiff/rad_Y32.tif
+  tests/tiff/jello.tif
+  tests/tiff/ycbcr-cat.tif
+  tests/tiff/off_luv32.tif
+  tests/tiff/dscf0013.tif
+  --tests/tiff/compression
+  tests/tiff/compression/flower-rgb-contig-16-packbits.tif
+  tests/tiff/compression/cs3n2c16.tif
+  tests/tiff/quad-lzw.tif
+  tests/tiff/smallliz.tif
+  tests/tiff/off_luv24.tif
+  tests/tiff/jim___cg.tif
+  tests/tiff/zackthecat.tif
+  tests/tiff/quad-jpeg.tif
+  tests/tiff/jim___dg.tif
+  tests/tiff/pc260001.tif
+  tests/tiff/fax2d.tif
+  -- tests/gif
+  tests/gif/fgs.gif
+  tests/gif/delta.gif
+  tests/gif/magceit.gif
+  tests/gif/1bitgiffail.gif
+  tests/gif/rId98.gif
+  tests/gif/Gif_pixel_cube.gif
+  tests/gif/pikachu.gif
+  tests/gif/animated.gif
+  tests/gif/delta2.gif
+  tests/gif/2k.gif
+  tests/gif/huge.gif
+  tests/gif/interleaved.gif
+
+Source-Repository head
+    Type:      git
+    Location:  https://github.com/Twinside/Juicy.Pixels.git
+
+Source-Repository this
+    Type:      git
+    Location:  https://github.com/Twinside/Juicy.Pixels.git
+    Tag:       v3.3.8
+
+Flag Mmap
+    Description: Enable the file loading via mmap (memory map)
+    Default: False
+
+Executable toPng
+  hs-source-dirs: test-src
+  Default-Language: Haskell2010
+  Main-Is: toPng.hs
+  Ghc-options: -Wall
+  Ghc-prof-options: -rtsopts -Wall -auto-all
+  Include-Dirs: src/Codec/Picture
+  -- -cpp -prof -auto-all -rtsopts -caf-all -fforce-recomp
+  Build-depends: base,
+                 bytestring,
+                 JuicyPixels
+
+Test-suite bmp-rle-safety
+  type: exitcode-stdio-1.0
+  hs-source-dirs: test-src
+  Default-Language: Haskell2010
+  Main-Is: BmpRleSafety.hs
+  Ghc-options: -Wall
+  Build-depends: base,
+                 bytestring,
+                 vector,
+                 JuicyPixels
+
+Test-suite imageTest
+  type: exitcode-stdio-1.0
+  hs-source-dirs: test-src
+  Default-Language: Haskell2010
+  Main-Is: main.hs
+  Ghc-options: -Wall
+  Ghc-prof-options: -rtsopts -Wall -auto-all
+  -- -O3 -Wall
+  --
+  -- -ddump-simpl
+  --
+  Include-Dirs: src/Codec/Picture
+  -- -cpp -prof -auto-all -rtsopts -caf-all -fforce-recomp
+  Build-depends: base,
+                 bytestring, mtl, binary, zlib, transformers,
+                 vector, primitive, deepseq,
+                 filepath            >= 1.3,
+                 criterion           >= 1.0,
+                 JuicyPixels
+
+  if flag(Mmap)
+    Build-depends: mmap
+    CC-Options: "-DWITH_MMAP_BYTESTRING"
+
+Benchmark imageBenchmark
+  type: exitcode-stdio-1.0
+  hs-source-dirs: test-src
+  Default-Language: Haskell2010
+  Main-Is: main.hs
+  Ghc-options: -Wall
+  Ghc-prof-options: -rtsopts -Wall -auto-all
+  -- -O3 -Wall
+  --
+  -- -ddump-simpl
+  --
+  Include-Dirs: src/Codec/Picture
+  -- -cpp -prof -auto-all -rtsopts -caf-all -fforce-recomp
+  Build-depends: base,
+                 bytestring, mtl, binary, zlib, transformers,
+                 vector, primitive, deepseq,
+                 filepath            >= 1.3,
+                 criterion           >= 1.0,
+                 JuicyPixels
+
+  if flag(Mmap)
+    Build-depends: mmap
+    CC-Options: "-DWITH_MMAP_BYTESTRING"
+
+Library
+  hs-source-dirs: src
+  Default-Language: Haskell2010
+  default-extensions: TypeOperators
+  Exposed-modules:  Codec.Picture,
+                    Codec.Picture.Bitmap,
+                    Codec.Picture.Gif,
+                    Codec.Picture.Png,
+                    Codec.Picture.Jpg,
+                    Codec.Picture.HDR,
+                    Codec.Picture.Tga,
+                    Codec.Picture.Tiff,
+                    Codec.Picture.Metadata,
+                    Codec.Picture.Metadata.Exif,
+                    Codec.Picture.Saving,
+                    Codec.Picture.Types,
+                    Codec.Picture.ColorQuant,
+                    Codec.Picture.Jpg.Internal.DefaultTable,
+                    Codec.Picture.Jpg.Internal.Metadata,
+                    Codec.Picture.Jpg.Internal.FastIdct,
+                    Codec.Picture.Jpg.Internal.FastDct,
+                    Codec.Picture.Jpg.Internal.Types,
+                    Codec.Picture.Jpg.Internal.Common,
+                    Codec.Picture.Jpg.Internal.Progressive,
+                    Codec.Picture.Gif.Internal.LZW,
+                    Codec.Picture.Gif.Internal.LZWEncoding,
+                    Codec.Picture.Png.Internal.Export,
+                    Codec.Picture.Png.Internal.Type,
+                    Codec.Picture.Png.Internal.Metadata,
+                    Codec.Picture.Tiff.Internal.Metadata,
+                    Codec.Picture.Tiff.Internal.Types
+
+  Ghc-options: -Wall
+  Build-depends: base                >= 4.8     && < 5,
+                 bytestring          >= 0.9     && < 0.13,
+                 mtl                 >= 1.1     && < 2.4,
+                 binary              >= 0.8.1   && < 0.11,
+                 zlib                >= 0.5.3.1 && < 0.8,
+                 transformers        >= 0.2,
+                 vector              >= 0.12.3.1,
+                 primitive           >= 0.4,
+                 deepseq             >= 1.1     && < 1.7,
+                 containers          >= 0.4.2
+
+  -- Modules not exported by this package.
+  Other-modules: Codec.Picture.BitWriter,
+                 Codec.Picture.InternalHelper,
+                 Codec.Picture.VectorByteConversion
+
+  Install-Includes: src/Codec/Picture/ConvGraph.hs
+  Include-Dirs: src/Codec/Picture
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -111,7 +111,7 @@
         - 8 and 16 bits
         - CMYK, YCbCr, RGB, RGBA, Greyscale
         - Uncompressed
-    * Metadata: reading DpiX, DpiY and EXIF informations.
+    * Metadata: reading DpiX, DpiY and EXIF information.
 
 _I love juicy pixels_
 
diff --git a/changelog b/changelog
--- a/changelog
+++ b/changelog
@@ -1,459 +1,477 @@
-Change log
-==========
-
-v3.3.9 June 2024
-----------------
-
- * Something something compilation
-
-v3.3.7 July 2022
-----------------
-
- * Dependence fidling
- * Jpg: do not call "error" in the parser, use fail instead.
-
-v3.3.7 March 2022
------------------
-
- * Jpg: Fixing renderng bug with MCUs with single block in width and
-   multiple in height
-
-v3.3.6 October 2021
--------------------
-
- * Bytestring bound bump
- * Fix bug #187.  (Some JPEGs are misidentified as SourceTiff.)
- * Fix EXIF handling of strings of four characters or fewer.
- * Fix endianness bug in short ExifString and ExifUndefined.
-
-
-v3.3.5 January 2020
--------------------
-
-Maintenance release to push various pull requests onto
-hackage
-
- * Exporting Pixel32 (will)
- * Palettization of transparent frames in Gif (flutterlice)
- * Documentation fixes (lehins)
-
-v3.3.4 September 2019
----------------------
-
- * support reading compressed zTXt metadata from PNG files (claudeha)
- * Add helper functions to convert a DynamicImage to RGB16 (uglyoldbob)
- * Fix RGB to CMYK conversion (lehins)
-
-v3.3.3.1 June 2019
-------------------
-
- * New GHC maintenance (thanks to ekmett)
-
-v3.3.3 December 2018
---------------------
-
- * Enhanced: loading of bitmap format (thanks to CLowcay)
- * Refactoring: exposing more internal modules (thanks to wyager)
- * Refactoring: exposing dynamicMap & dynamicPixelMap
-   through `Codec.Picture` (thnks to LightAndLight)
-
- * v3.3.3.1: fixing compilation with older GHC
-
-v3.3.2 October 2018
--------------------
-
- * Fix: GHC-8.6 compilation fix (no upper bound on base)
- * Fix: upper bound on containers (pull request phadej)
- * Fix: palette validation for gifs (pull request omedan)
- * New: More complete gif creation API (pull request omedan)
-
-v3.3.1 August 2018
-------------------
-
- * Fix: gif decoding of 1bit palette (fix Ornedan)
- * Fix: end of stream handling for gif's lzw encoding (fix Ornedan)
-
-v3.3 July 2018
---------------
-
- * New: Eq instances for image
- * Fix: color gif resolution offset
- * New: support for Float Tiff
- * Breaking change: New `ImageY32` constructor for `Dynamic`
-					hence the version bump.
-
-v3.2.9.5 March 2018
--------------------
- 
- * Fix: uniform color quantization
-
-v3.2.9.4 January 2018
-----------------------
-
- * Compat for GHC-8.4 (pull request)
- * Fix: a character in latin1 which was still around. Whatever.
-        So tired of this.
-
-
-v3.2.9.3 December 2017
-----------------------
-
- * Fix: remove bad invisible unicde char
-
-v3.2.9.2 December 2017
-----------------------
-
- * Fix: Progressive jpeg decoding when number of blocks of the MCU
-		is below line size
-
-v3.2.9.1 November 2017
-----------------------
-
- * Feature: Paletted alpha png saving
-
-v3.2.9 November 2017
-----------------------
-
- * Fix: Adding correct import of Exif Flash for Jpeg (thanks to Alexander Kjeldaas)
- * Feature: Jpg Exif writing
-
-
-v3.2.8.3 August 2017
-------------------
-
- * Fix: Jpeg loading of extended sequential jpg, not sure of all
-		the implications, works with the sample
-
-v3.2.8.2 June 2017
-------------------
-
- * Fix: usage of fail in Either monad, giving an unwanted exception
-
-v3.2.8.1 March 2016
--------------------
-
- * Fix: proper flushing of jpeg writing, avoiding warning from libjpeg.
- * Fix: RGB jpeg get an Adobe's APP14 block to help MacOS & Photoshop reading
-
-v3.2.8 September 2016
----------------------
-
- * Added: possibility to retrieve the parsed palette.
- * Fix: Fixing problem of progressive Jpeg decoding when
-		block height is different of block width (#)
-
-v3.2.7.2 June 2016
-------------------
-
- * Fix: no more libjpeg warning when decoding Juicy.Pixels encoded images.
-
-v3.2.7.1 May 2016
------------------
- * Fix: some wrongly infinitely looping JPEG decoding
-
-v3.2.7 January 2016
--------------------
- * Addition: convertRGB8 and convertRGBA8 helper functions
- * Addition: new output colorspace for JPEG format: Y, RGB & CMYK
- * Addition: RGBA8 bitmap reading (thanks to mtolly)
- * Enhancement: Optimized JPG & Tiff reading (thanks to Calvin Beck)
- * Enhancement: INLINE SPECIALIZE for pixelMap (Pixel8 -> Pixel8) (thx to Calvin Beck)
- * Fix: GHC 8.0 compilation (thanks to phadej)
-
-v3.2.6.5 December 2015
-----------------------
- * Fix: Compilation on GHC 7.6/7.8
-
-v3.2.6.4 December 2015
-----------------------
- * Fix: previous broken bugfix.
-
-v3.2.6.3 November 2015
-----------------------
- * Fix: Fixing unwanted sharing with createMutableImage due to
-		wrongly used INLINE pragma
-
-v3.2.6.2 November 2015
-----------------------
- * Fix: Using minimal GIF version if outputing a single image.
-
-v3.2.6.1 August 2015
---------------------
- * Fix: handling of negative height & width in bitmap format.
- * Fix: regression on Tiff parsing.
-
-V3.2.6 August 2015
---------------------
-
- * Added: imageToTga saving helper function.
- * Fix: don't invert TGA alpha channel.
- * Fix: various typo in documentation.
-
-V3.2.5.3 July 2015
-------------------
-
- * Fix: bumping vector upper bounds.
-
-V3.2.5.2 June 2015
-------------------
-
- * Adding: Width & Height metdata to help querying image information
-	without decompressing the whole.
- * Adding: Source format metadata.
-
-v3.2.5.1 May 2015
----------------
-
- * Fixing: utf-8 encoding of Jpg/Types causing problems with Haddock.
-
-v3.2.5 May 2015
----------------
-
- * Adding: Metadata extraction for various file format.
- * Adding: Metadata writing for various file format.
- * Adding: light EXIF mapping.
- * Fix: handling of Tiff with predictors (thanks to Patrick Pelletier)
- 
-v3.2.4 April 2015
------------------
-
- * Adding: Traversals compatible with the lens library.
-
-v3.2.3.2 April 2015
--------------------
-
- * Bumping: zlib max bound
-
-v3.2.3.1 March 2015
--------------------
-
- * Bumping: primitive to allow 0.6
- * Fix: BMP output generated wrong size (thanks to mtolly).
- * Fix: 7.10.1 warning free
-
-v3.2.3 March 2015
------------------
-
- * Adding: Support for RGB in jpeg (yeah, that exist...)
- * Adding: Support of CMYK & YCrCbK color space in jpeg files.
- * Addinng: a pixelFoldMap functions analog to the `foldMap` function
-  of the Foldable type class.
- * Fix: better performances for the pixelFold* functions
-
-v3.2.2 January 2015
--------------------
-
- * Fix: Squashing GHC 7.10 warnings
-
-v3.2.1 December 2014
---------------------
- * Fix: Bumping deepseq dependencies preparing for GHC 7.10
-   release.
-
-v3.2 December 2014
-------------------
-
-*BREAKING CHANGES*: the Codec.Picture.Gif functions has changed interfaces.
-
- * Adding: TGA reading.
- * Adding: TGA writing.
- * Adding: Packeable pixel unpack.
- * Fix: Returning gif with transparency (breaking Codec.Picture.Gif interface)
-
-v3.1.7.1 August 2014
---------------------
-
- * Previous gif fix was not working withing the readImage
-   function, only in specialized gif images. Correcting
-   miscorection
-
-v3.1.7 August 2014
-------------------
-
- * Making Juicy.Pixels compatible with GHC 7.9 HEAD (ggreif)
- * Adding writing to uncompressed radiance file, due to
-   problems with Mac OS X "preview" application
- * Fixing problem of gif parsing without global palette
- * Some inlining annotations on some functions
-
-v3.1.6.1 August 2014
---------------------
-
- * Fix of Gif palette creation (jeffreyrosenbluth)
- * Restoring transformers 0.3.* compat
-
-v3.1.6 August 2014
-------------------
-
- * Fix bad disposal handling in GIF animations.
- * Added ColorConvertible instance for PixelRGB8 -> PixelRGBA16 (KaiHa)
- * Fixing a bad handling of tRNS causing bad transprency decoding in
-   some circonstances.
- * Adding the concept of Packeable pixel for faster pixel filling
-   using mutable array.
-
-v3.1.5.2 May 2014
------------------
-
- * Bumping the transformers dependency
-
-v3.1.5.1 May 2014
------------------
-
- * Adding some INLINE annotations for some pixel functions
-
-v3.1.5 March 2014
------------------
-
- * Typos and documentation proof reading fixes
-   (pull request from iger).
- * Fix of progressive jpeg loading with more than two
-   huffman tables (4 allowed).
- * Fix of progressive jpeg rendering (was too noisy before)
- * Added loading of paletted bitmap files.
- * Function to load gif images with frame duration
-   information (pull request from bit-shift)
- * Fixing bug showing when loading JPEG with component
-   ID starting at 0.
- * Adding reading for YA8 et YA16 Tiff images (pull 
-   request from iger)
- * Adding a mixWithAlpha method, to help work on transparent
-   pixel types
-
-
-v3.1.4.1 February 2014
-----------------------
-
- * Putting back data URI logo for cabal description, it's
-   apparently not supported by Hackage :-(
-
-v3.1.4 February 2014
---------------------
-
- * Adding a pixelOpacity method to the pixel type class.
- * Adding handling greyscale BMP files (phischu)
- * Fixing promotePixel for Pixel8 -> Pixel16
- * Some type fixes in the documentation
- * Updating the pixel conversion graph
- * Removed URI-encoded images, now using clean cabal embedding
-
-v3.1.3.3 February 2014
-----------------------
-
- * Lowering cabal version limit to be compiled with older GHCs
-
-v3.1.3.2 January 2014
----------------------
-
- * Hacking around Binary to accept old version of it, down to version 0.5
-   allowing Juicy.Pixels to be compiled with GHC 6.3
-
-v3.1.3.1 January 2014
----------------------
-
- * Fixing color counting function in color quantisation.
- * Adding missing documentation for foreign pointer import.
-
-v3.1.3 January 2014
--------------------
-
- * Adding palette creation (color Quantization) by Jeffrey Rosenbluth.
- * Adding support for Gif writing
- * Adding support for Gif animation writing
- * Fixing some progressive Jpeg decoding problems (#39)
-
-v3.1.2 December 2013
---------------------
-
- * Adding support for progressive jpeg.
- * Adding support for plane separated MCU jpeg.
- * Adding support for grayscale 32bit decoding (with reduced precision to
-	16bits).
- * Fixing erroneous bitmap decoding in case of excessive padding (#31).
-
-v3.1.1.1 October 2013
----------------------
-
- * Fixing some spurious crash while decoding some JPEG image (#30).
-
-v3.1.1  October 2013
---------------------
-
- * Adding uncompresed TIFF saving.
- * Adding error message to avoid loading progressive loading.
- * Made MMAP optional, controled by a cabal flag.
- * adding dynamicPixelMap helper function.
- * Handling png transparency using color key (#26).
-
-v3.1 June 2013
---------------
-
- * Adding basic handling of 16bits pixel types.
- * Addition of Tiff reading:
-    - 2, 4, 8, 16 bit depth reading (planar and contiguous for each).
-    - CMYK, YCbCr, RGB, Paletted, Greyscale.
-    - Uncompressed, PackBits, LZW.
- * Some new tiny helper functions (nothing too fancy).
- * Huge performances improvement.
-
-v3.0 January 2013
------------------
-
- * Simplification of the 'Pixel' typeclass, removed many unused part.
- * Removal of some Storable instances for pixel types.
- * Amelioration of the documentation.
- * Support for High Dynamic range images, opening support for different pixel
-   base component.
- * Support for the Radiance file format (or RGBE, file extension .pic and .hdr).
- * Dropped the cereal library in favor of the last version of Binary, present 
-   in the Haskell platform. Every dependencies are now present in the platform.
-
-v2.0.2 October 2012
--------------------
-
- * Decoding of interleaved gif image.
- * Decoding delta coded gif animation.
- * Bumping dependencies.
-
-v2.0.1 September 2012
----------------------
-
- * Documentation enhancements.
- * Fixing some huge gif file loading.
- * Fixing performance problem of Bitmap and Jpeg savings.
-
-v2.0 September 2012
--------------------
-
- * New extractComponent version with type safe plane extraction.
- * Gif file reading.
-
-v1.3 June 2012
---------------
-
- * Fix extractComponent function.
- * Adding saving for YA8 functions.
-
-v1.2.1 April 2012
------------------
-
- * Dependencies version bump.
- * Dropping array dependency.
-
-v1.2 March 2012
----------------
-
- * Adding a generateImage helper function.
- * Adding NFData instances for image.
- * Adding JPEG writing.
-
-v1.1 February 2012
-------------------
-
- * Switching to vector for arrays, big performance improvement.
-
-v1.0 January 2012
------------------
-
- * Initial release
-
+Change log
+==========
+
+v3.3.10 November 2026
+---------------------
+
+ * Bmp: Fixed an out-of-bounds write (CWE-787) in the RLE decoder: the
+   pixel buffer size was computed with 32-bit `Int32` multiplication
+   (wrapping on large headers), and the RLE cursor (delta escapes,
+   end-of-line) was neither clamped nor bounds-checked before
+   `unsafeWrite`. Dimensions are now validated centrally (pixel count
+   capped at 2^29), allocations use exact `Int` arithmetic, and
+   out-of-bounds RLE writes are clipped. (HSEC-2026-00XX / CVE pending)
+ * Tiff: Fixed an out-of-bounds write (CWE-787) in contiguous strip
+   decoding: uncompressed and PackBits strip copies had no destination
+   bound, and the per-strip size computation wrapped negative for strips
+   starting past the end of the raster. Strip writes are now bounded by
+   the destination buffer and strip counts saturate at the raster
+   boundary. (HSEC-2026-00XX / CVE pending)
+ * Added `bmp-rle-safety` regression test-suite.
+
+v3.3.9 June 2024
+----------------
+
+ * Something something compilation
+
+v3.3.7 July 2022
+----------------
+
+ * Dependence fidling
+ * Jpg: do not call "error" in the parser, use fail instead.
+
+v3.3.7 March 2022
+-----------------
+
+ * Jpg: Fixing renderng bug with MCUs with single block in width and
+   multiple in height
+
+v3.3.6 October 2021
+-------------------
+
+ * Bytestring bound bump
+ * Fix bug #187.  (Some JPEGs are misidentified as SourceTiff.)
+ * Fix EXIF handling of strings of four characters or fewer.
+ * Fix endianness bug in short ExifString and ExifUndefined.
+
+
+v3.3.5 January 2020
+-------------------
+
+Maintenance release to push various pull requests onto
+hackage
+
+ * Exporting Pixel32 (will)
+ * Palettization of transparent frames in Gif (flutterlice)
+ * Documentation fixes (lehins)
+
+v3.3.4 September 2019
+---------------------
+
+ * support reading compressed zTXt metadata from PNG files (claudeha)
+ * Add helper functions to convert a DynamicImage to RGB16 (uglyoldbob)
+ * Fix RGB to CMYK conversion (lehins)
+
+v3.3.3.1 June 2019
+------------------
+
+ * New GHC maintenance (thanks to ekmett)
+
+v3.3.3 December 2018
+--------------------
+
+ * Enhanced: loading of bitmap format (thanks to CLowcay)
+ * Refactoring: exposing more internal modules (thanks to wyager)
+ * Refactoring: exposing dynamicMap & dynamicPixelMap
+   through `Codec.Picture` (thnks to LightAndLight)
+
+ * v3.3.3.1: fixing compilation with older GHC
+
+v3.3.2 October 2018
+-------------------
+
+ * Fix: GHC-8.6 compilation fix (no upper bound on base)
+ * Fix: upper bound on containers (pull request phadej)
+ * Fix: palette validation for gifs (pull request omedan)
+ * New: More complete gif creation API (pull request omedan)
+
+v3.3.1 August 2018
+------------------
+
+ * Fix: gif decoding of 1bit palette (fix Ornedan)
+ * Fix: end of stream handling for gif's lzw encoding (fix Ornedan)
+
+v3.3 July 2018
+--------------
+
+ * New: Eq instances for image
+ * Fix: color gif resolution offset
+ * New: support for Float Tiff
+ * Breaking change: New `ImageY32` constructor for `Dynamic`
+					hence the version bump.
+
+v3.2.9.5 March 2018
+-------------------
+ 
+ * Fix: uniform color quantization
+
+v3.2.9.4 January 2018
+----------------------
+
+ * Compat for GHC-8.4 (pull request)
+ * Fix: a character in latin1 which was still around. Whatever.
+        So tired of this.
+
+
+v3.2.9.3 December 2017
+----------------------
+
+ * Fix: remove bad invisible unicode char
+
+v3.2.9.2 December 2017
+----------------------
+
+ * Fix: Progressive jpeg decoding when number of blocks of the MCU
+		is below line size
+
+v3.2.9.1 November 2017
+----------------------
+
+ * Feature: Paletted alpha png saving
+
+v3.2.9 November 2017
+----------------------
+
+ * Fix: Adding correct import of Exif Flash for Jpeg (thanks to Alexander Kjeldaas)
+ * Feature: Jpg Exif writing
+
+
+v3.2.8.3 August 2017
+------------------
+
+ * Fix: Jpeg loading of extended sequential jpg, not sure of all
+		the implications, works with the sample
+
+v3.2.8.2 June 2017
+------------------
+
+ * Fix: usage of fail in Either monad, giving an unwanted exception
+
+v3.2.8.1 March 2016
+-------------------
+
+ * Fix: proper flushing of jpeg writing, avoiding warning from libjpeg.
+ * Fix: RGB jpeg get an Adobe's APP14 block to help MacOS & Photoshop reading
+
+v3.2.8 September 2016
+---------------------
+
+ * Added: possibility to retrieve the parsed palette.
+ * Fix: Fixing problem of progressive Jpeg decoding when
+		block height is different of block width (#)
+
+v3.2.7.2 June 2016
+------------------
+
+ * Fix: no more libjpeg warning when decoding Juicy.Pixels encoded images.
+
+v3.2.7.1 May 2016
+-----------------
+ * Fix: some wrongly infinitely looping JPEG decoding
+
+v3.2.7 January 2016
+-------------------
+ * Addition: convertRGB8 and convertRGBA8 helper functions
+ * Addition: new output colorspace for JPEG format: Y, RGB & CMYK
+ * Addition: RGBA8 bitmap reading (thanks to mtolly)
+ * Enhancement: Optimized JPG & Tiff reading (thanks to Calvin Beck)
+ * Enhancement: INLINE SPECIALIZE for pixelMap (Pixel8 -> Pixel8) (thx to Calvin Beck)
+ * Fix: GHC 8.0 compilation (thanks to phadej)
+
+v3.2.6.5 December 2015
+----------------------
+ * Fix: Compilation on GHC 7.6/7.8
+
+v3.2.6.4 December 2015
+----------------------
+ * Fix: previous broken bugfix.
+
+v3.2.6.3 November 2015
+----------------------
+ * Fix: Fixing unwanted sharing with createMutableImage due to
+		wrongly used INLINE pragma
+
+v3.2.6.2 November 2015
+----------------------
+ * Fix: Using minimal GIF version if outputting a single image.
+
+v3.2.6.1 August 2015
+--------------------
+ * Fix: handling of negative height & width in bitmap format.
+ * Fix: regression on Tiff parsing.
+
+V3.2.6 August 2015
+--------------------
+
+ * Added: imageToTga saving helper function.
+ * Fix: don't invert TGA alpha channel.
+ * Fix: various typo in documentation.
+
+V3.2.5.3 July 2015
+------------------
+
+ * Fix: bumping vector upper bounds.
+
+V3.2.5.2 June 2015
+------------------
+
+ * Adding: Width & Height metadata to help querying image information
+	without decompressing the whole.
+ * Adding: Source format metadata.
+
+v3.2.5.1 May 2015
+---------------
+
+ * Fixing: utf-8 encoding of Jpg/Types causing problems with Haddock.
+
+v3.2.5 May 2015
+---------------
+
+ * Adding: Metadata extraction for various file format.
+ * Adding: Metadata writing for various file format.
+ * Adding: light EXIF mapping.
+ * Fix: handling of Tiff with predictors (thanks to Patrick Pelletier)
+ 
+v3.2.4 April 2015
+-----------------
+
+ * Adding: Traversals compatible with the lens library.
+
+v3.2.3.2 April 2015
+-------------------
+
+ * Bumping: zlib max bound
+
+v3.2.3.1 March 2015
+-------------------
+
+ * Bumping: primitive to allow 0.6
+ * Fix: BMP output generated wrong size (thanks to mtolly).
+ * Fix: 7.10.1 warning free
+
+v3.2.3 March 2015
+-----------------
+
+ * Adding: Support for RGB in jpeg (yeah, that exist...)
+ * Adding: Support of CMYK & YCrCbK color space in jpeg files.
+ * Addinng: a pixelFoldMap functions analog to the `foldMap` function
+  of the Foldable type class.
+ * Fix: better performances for the pixelFold* functions
+
+v3.2.2 January 2015
+-------------------
+
+ * Fix: Squashing GHC 7.10 warnings
+
+v3.2.1 December 2014
+--------------------
+ * Fix: Bumping deepseq dependencies preparing for GHC 7.10
+   release.
+
+v3.2 December 2014
+------------------
+
+*BREAKING CHANGES*: the Codec.Picture.Gif functions has changed interfaces.
+
+ * Adding: TGA reading.
+ * Adding: TGA writing.
+ * Adding: Packeable pixel unpack.
+ * Fix: Returning gif with transparency (breaking Codec.Picture.Gif interface)
+
+v3.1.7.1 August 2014
+--------------------
+
+ * Previous gif fix was not working within the readImage
+   function, only in specialized gif images. Correcting
+   miscorection
+
+v3.1.7 August 2014
+------------------
+
+ * Making Juicy.Pixels compatible with GHC 7.9 HEAD (ggreif)
+ * Adding writing to uncompressed radiance file, due to
+   problems with Mac OS X "preview" application
+ * Fixing problem of gif parsing without global palette
+ * Some inlining annotations on some functions
+
+v3.1.6.1 August 2014
+--------------------
+
+ * Fix of Gif palette creation (jeffreyrosenbluth)
+ * Restoring transformers 0.3.* compat
+
+v3.1.6 August 2014
+------------------
+
+ * Fix bad disposal handling in GIF animations.
+ * Added ColorConvertible instance for PixelRGB8 -> PixelRGBA16 (KaiHa)
+ * Fixing a bad handling of tRNS causing bad transparency decoding in
+   some circonstances.
+ * Adding the concept of Packeable pixel for faster pixel filling
+   using mutable array.
+
+v3.1.5.2 May 2014
+-----------------
+
+ * Bumping the transformers dependency
+
+v3.1.5.1 May 2014
+-----------------
+
+ * Adding some INLINE annotations for some pixel functions
+
+v3.1.5 March 2014
+-----------------
+
+ * Typos and documentation proof reading fixes
+   (pull request from iger).
+ * Fix of progressive jpeg loading with more than two
+   huffman tables (4 allowed).
+ * Fix of progressive jpeg rendering (was too noisy before)
+ * Added loading of paletted bitmap files.
+ * Function to load gif images with frame duration
+   information (pull request from bit-shift)
+ * Fixing bug showing when loading JPEG with component
+   ID starting at 0.
+ * Adding reading for YA8 et YA16 Tiff images (pull 
+   request from iger)
+ * Adding a mixWithAlpha method, to help work on transparent
+   pixel types
+
+
+v3.1.4.1 February 2014
+----------------------
+
+ * Putting back data URI logo for cabal description, it's
+   apparently not supported by Hackage :-(
+
+v3.1.4 February 2014
+--------------------
+
+ * Adding a pixelOpacity method to the pixel type class.
+ * Adding handling greyscale BMP files (phischu)
+ * Fixing promotePixel for Pixel8 -> Pixel16
+ * Some type fixes in the documentation
+ * Updating the pixel conversion graph
+ * Removed URI-encoded images, now using clean cabal embedding
+
+v3.1.3.3 February 2014
+----------------------
+
+ * Lowering cabal version limit to be compiled with older GHCs
+
+v3.1.3.2 January 2014
+---------------------
+
+ * Hacking around Binary to accept old version of it, down to version 0.5
+   allowing Juicy.Pixels to be compiled with GHC 6.3
+
+v3.1.3.1 January 2014
+---------------------
+
+ * Fixing color counting function in color quantisation.
+ * Adding missing documentation for foreign pointer import.
+
+v3.1.3 January 2014
+-------------------
+
+ * Adding palette creation (color Quantization) by Jeffrey Rosenbluth.
+ * Adding support for Gif writing
+ * Adding support for Gif animation writing
+ * Fixing some progressive Jpeg decoding problems (#39)
+
+v3.1.2 December 2013
+--------------------
+
+ * Adding support for progressive jpeg.
+ * Adding support for plane separated MCU jpeg.
+ * Adding support for grayscale 32bit decoding (with reduced precision to
+	16bits).
+ * Fixing erroneous bitmap decoding in case of excessive padding (#31).
+
+v3.1.1.1 October 2013
+---------------------
+
+ * Fixing some spurious crash while decoding some JPEG image (#30).
+
+v3.1.1  October 2013
+--------------------
+
+ * Adding uncompressed TIFF saving.
+ * Adding error message to avoid loading progressive loading.
+ * Made MMAP optional, controlled by a cabal flag.
+ * adding dynamicPixelMap helper function.
+ * Handling png transparency using color key (#26).
+
+v3.1 June 2013
+--------------
+
+ * Adding basic handling of 16bits pixel types.
+ * Addition of Tiff reading:
+    - 2, 4, 8, 16 bit depth reading (planar and contiguous for each).
+    - CMYK, YCbCr, RGB, Paletted, Greyscale.
+    - Uncompressed, PackBits, LZW.
+ * Some new tiny helper functions (nothing too fancy).
+ * Huge performances improvement.
+
+v3.0 January 2013
+-----------------
+
+ * Simplification of the 'Pixel' typeclass, removed many unused part.
+ * Removal of some Storable instances for pixel types.
+ * Amelioration of the documentation.
+ * Support for High Dynamic range images, opening support for different pixel
+   base component.
+ * Support for the Radiance file format (or RGBE, file extension .pic and .hdr).
+ * Dropped the cereal library in favor of the last version of Binary, present 
+   in the Haskell platform. Every dependencies are now present in the platform.
+
+v2.0.2 October 2012
+-------------------
+
+ * Decoding of interleaved gif image.
+ * Decoding delta coded gif animation.
+ * Bumping dependencies.
+
+v2.0.1 September 2012
+---------------------
+
+ * Documentation enhancements.
+ * Fixing some huge gif file loading.
+ * Fixing performance problem of Bitmap and Jpeg savings.
+
+v2.0 September 2012
+-------------------
+
+ * New extractComponent version with type safe plane extraction.
+ * Gif file reading.
+
+v1.3 June 2012
+--------------
+
+ * Fix extractComponent function.
+ * Adding saving for YA8 functions.
+
+v1.2.1 April 2012
+-----------------
+
+ * Dependencies version bump.
+ * Dropping array dependency.
+
+v1.2 March 2012
+---------------
+
+ * Adding a generateImage helper function.
+ * Adding NFData instances for image.
+ * Adding JPEG writing.
+
+v1.1 February 2012
+------------------
+
+ * Switching to vector for arrays, big performance improvement.
+
+v1.0 January 2012
+-----------------
+
+ * Initial release
+
diff --git a/src/Codec/Picture/BitWriter.hs b/src/Codec/Picture/BitWriter.hs
--- a/src/Codec/Picture/BitWriter.hs
+++ b/src/Codec/Picture/BitWriter.hs
@@ -1,358 +1,358 @@
-{-# LANGUAGE Rank2Types #-}
-{-# LANGUAGE BangPatterns #-}
-{-# LANGUAGE CPP #-}
--- | This module implement helper functions to read & write data
--- at bits level.
-module Codec.Picture.BitWriter( BoolReader
-                              , emptyBoolState
-                              , BoolState
-                              , byteAlignJpg
-                              , getNextBitsLSBFirst
-                              , getNextBitsMSBFirst 
-                              , getNextBitJpg
-                              , getNextIntJpg
-                              , setDecodedString
-                              , setDecodedStringMSB
-                              , setDecodedStringJpg
-                              , runBoolReader
-
-                              , BoolWriteStateRef 
-                              , newWriteStateRef
-                              , finalizeBoolWriter
-                              , finalizeBoolWriterGif
-                              , writeBits'
-                              , writeBitsGif
-
-                              , initBoolState 
-                              , initBoolStateJpg
-                              , execBoolReader
-                              , runBoolReaderWith
-                              ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<*>), (<$>) )
-#endif
-
-import Data.STRef
-import Control.Monad( when )
-import Control.Monad.ST( ST )
-import qualified Control.Monad.Trans.State.Strict as S
-import Data.Int ( Int32 )
-import Data.Word( Word8, Word32 )
-import Data.Bits( (.&.), (.|.), unsafeShiftR, unsafeShiftL )
-
-import Codec.Picture.VectorByteConversion( blitVector )
-import qualified Data.Vector.Storable.Mutable as M
-import qualified Data.Vector.Storable as VS
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as L
-
-
---------------------------------------------------
-----            Reader
---------------------------------------------------
--- | Current bit index, current value, string
-data BoolState = BoolState {-# UNPACK #-} !Int
-                           {-# UNPACK #-} !Word8
-                           !B.ByteString
-
-emptyBoolState :: BoolState
-emptyBoolState = BoolState (-1) 0 B.empty
-
--- | Type used to read bits
-type BoolReader s a = S.StateT BoolState (ST s) a
-
-runBoolReader :: BoolReader s a -> ST s a
-runBoolReader action = S.evalStateT action $ BoolState 0 0 B.empty
-
-runBoolReaderWith :: BoolState -> BoolReader s a -> ST s (a, BoolState)
-runBoolReaderWith st action = S.runStateT action st
-
-execBoolReader :: BoolState -> BoolReader s a -> ST s BoolState
-execBoolReader st reader = S.execStateT reader st
-
-initBoolState :: B.ByteString -> BoolState
-initBoolState str = case B.uncons str of
-     Nothing -> BoolState 0 0 B.empty
-     Just (v, rest) -> BoolState 0 v rest
-
-initBoolStateJpg :: B.ByteString -> BoolState
-initBoolStateJpg str = 
-   case B.uncons str of
-     Nothing -> BoolState 0 0 B.empty
-     Just (0xFF, rest) -> case B.uncons rest of
-            Nothing                  -> BoolState 7 0 B.empty
-            Just (0x00, afterMarker) -> BoolState 7 0xFF afterMarker
-            Just (_   , afterMarker) -> initBoolStateJpg afterMarker
-     Just (v, rest) -> BoolState 7 v rest
-
--- | Bitify a list of things to decode.
-setDecodedString :: B.ByteString -> BoolReader s ()
-setDecodedString str = case B.uncons str of
-     Nothing        -> S.put $ BoolState      0 0 B.empty
-     Just (v, rest) -> S.put $ BoolState      0 v    rest
-
--- | Drop all bit until the bit of indice 0, usefull to parse restart
--- marker, as they are byte aligned, but Huffman might not.
-byteAlignJpg :: BoolReader s ()
-byteAlignJpg = do
-  BoolState idx _ chain <- S.get
-  when (idx /= 7) (setDecodedStringJpg chain)
-
-getNextBitJpg :: BoolReader s Bool
-{-# INLINE getNextBitJpg #-}
-getNextBitJpg = do
-    BoolState idx v chain <- S.get
-    let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
-    if idx == 0
-      then setDecodedStringJpg chain
-      else S.put $ BoolState (idx - 1) v chain
-    return val
-
-getNextIntJpg :: Int -> BoolReader s Int32
-{-# INLINE getNextIntJpg #-}
-getNextIntJpg = go 0 where
-  go !acc !0 = return acc
-  go !acc !n = do
-    BoolState idx v chain <- S.get
-    let !leftBits = 1 + fromIntegral idx
-    if n >= leftBits then do
-      setDecodedStringJpg chain
-      let !remaining = n - leftBits
-          !mask = (1 `unsafeShiftL` leftBits) - 1
-          !finalV = fromIntegral v .&. mask
-          !theseBits = finalV `unsafeShiftL` remaining
-      go (acc .|. theseBits) remaining
-    else do
-      let !remaining = leftBits - n
-          !mask = (1 `unsafeShiftL` n) - 1
-          !finalV = fromIntegral v `unsafeShiftR` remaining
-      S.put $ BoolState (fromIntegral remaining - 1) v chain
-      return $ (finalV .&. mask) .|. acc
-
-
-setDecodedStringMSB :: B.ByteString -> BoolReader s ()
-setDecodedStringMSB str = case B.uncons str of
-  Nothing        -> S.put $ BoolState      8 0 B.empty
-  Just (v, rest) -> S.put $ BoolState      8 v    rest
-
-
-{-# INLINE getNextBitsMSBFirst #-}
-getNextBitsMSBFirst :: Int -> BoolReader s Word32
-getNextBitsMSBFirst requested = go 0 requested where
-  go :: Word32 -> Int -> BoolReader s Word32
-  go !acc !0 = return acc
-  go !acc !n = do
-    BoolState idx v chain <- S.get
-    let !leftBits = fromIntegral idx
-    if n >= leftBits then do
-      setDecodedStringMSB chain
-      let !theseBits = fromIntegral v `unsafeShiftL` (n - leftBits)
-      go (acc .|. theseBits) (n - leftBits)
-    else do
-      let !remaining = leftBits - n
-          !mask = (1 `unsafeShiftL` remaining) - 1
-      S.put $ BoolState (fromIntegral remaining) (v .&. mask) chain
-      return $ (fromIntegral v `unsafeShiftR` remaining) .|. acc
-
-{-# INLINE getNextBitsLSBFirst #-}
-getNextBitsLSBFirst :: Int -> BoolReader s Word32
-getNextBitsLSBFirst count = aux 0 count
-  where aux acc 0 = return acc
-        aux acc n = do
-            bit <- getNextBit
-            let nextVal | bit = acc .|. (1 `unsafeShiftL` (count - n))
-                        | otherwise = acc
-            aux nextVal (n - 1)
-
-{-# INLINE getNextBit #-}
-getNextBit :: BoolReader s Bool
-getNextBit = do
-    BoolState idx v chain <- S.get
-    let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
-    if idx == 7
-      then setDecodedString chain
-      else S.put $ BoolState (idx + 1) v chain
-    return val
-
--- | Bitify a list of things to decode. Handle Jpeg escape
--- code (0xFF 0x00), thus should be only used in JPEG decoding.
-setDecodedStringJpg :: B.ByteString -> BoolReader s ()
-setDecodedStringJpg str = case B.uncons str of
-     Nothing        -> S.put $ BoolState 7 0 B.empty
-     Just (0xFF, rest) -> case B.uncons rest of
-            Nothing                  -> S.put $ BoolState 7 0 B.empty
-            Just (0x00, afterMarker) -> -- trace "00" $ 
-                S.put $ BoolState 7 0xFF afterMarker
-            Just (_   , afterMarker) -> setDecodedStringJpg afterMarker
-     Just (v, rest) ->
-        S.put $ BoolState 7 v rest
-
---------------------------------------------------
-----            Writer
---------------------------------------------------
-defaultBufferSize :: Int
-defaultBufferSize = 256 * 1024
-
-data BoolWriteStateRef s = BoolWriteStateRef
-        { bwsCurrBuffer   :: STRef s (M.MVector s Word8)
-        , bwsBufferList   :: STRef s [B.ByteString]
-        , bwsWrittenWords :: STRef s Int
-        , bwsBitAcc       :: STRef s Word8
-        , bwsBitReaded    :: STRef s Int
-        }
-
-newWriteStateRef :: ST s (BoolWriteStateRef s)
-newWriteStateRef = do
-    origMv <- M.new defaultBufferSize
-    BoolWriteStateRef <$> newSTRef origMv
-                      <*> newSTRef []
-                      <*> newSTRef 0
-                      <*> newSTRef 0
-                      <*> newSTRef 0
-
-finalizeBoolWriter :: BoolWriteStateRef s -> ST s L.ByteString
-finalizeBoolWriter st = do
-    flushLeftBits' st
-    forceBufferFlushing' st
-    L.fromChunks <$> readSTRef (bwsBufferList st)
-
-forceBufferFlushing' :: BoolWriteStateRef s -> ST s ()
-forceBufferFlushing' (BoolWriteStateRef { bwsCurrBuffer = vecRef
-                                        , bwsWrittenWords = countRef
-                                        , bwsBufferList = lstRef
-                                        }) = do
-    vec <- readSTRef vecRef
-    count <- readSTRef countRef
-    lst <- readSTRef lstRef
-
-    nmv <- M.new defaultBufferSize
-    str <- byteStringFromVector vec count
-
-    writeSTRef vecRef nmv
-    writeSTRef lstRef $ lst ++ [str]
-    writeSTRef countRef 0
-
-flushCurrentBuffer' :: BoolWriteStateRef s -> ST s ()
-flushCurrentBuffer' st = do
-    count <- readSTRef $ bwsWrittenWords st
-    when (count >= defaultBufferSize)
-         (forceBufferFlushing' st)
-
-byteStringFromVector :: M.MVector s Word8 -> Int -> ST s B.ByteString
-byteStringFromVector vec size = do
-    frozen <- VS.unsafeFreeze vec
-    return $ blitVector frozen 0 size
-
-setBitCount' :: BoolWriteStateRef s -> Word8 -> Int -> ST s ()
-{-# INLINE setBitCount' #-}
-setBitCount' st acc count = do
-    writeSTRef (bwsBitAcc st) acc
-    writeSTRef (bwsBitReaded st) count
-
-resetBitCount' :: BoolWriteStateRef s -> ST s ()
-{-# INLINE resetBitCount' #-}
-resetBitCount' st = setBitCount' st 0 0
-
-pushByte' :: BoolWriteStateRef s -> Word8 -> ST s ()
-{-# INLINE pushByte' #-}
-pushByte' st v = do
-    flushCurrentBuffer' st
-    idx <- readSTRef (bwsWrittenWords st)
-    vec <- readSTRef (bwsCurrBuffer st)
-    M.write vec idx v
-    writeSTRef (bwsWrittenWords st) $ idx + 1
-
-flushLeftBits' :: BoolWriteStateRef s -> ST s ()
-flushLeftBits' st = do
-    currCount <- readSTRef $ bwsBitReaded st
-    when (currCount > 0) $ do
-      currWord <- readSTRef $ bwsBitAcc st
-      pushByte' st $ currWord `unsafeShiftL` (8 - currCount)
-
--- | Append some data bits to a Put monad.
-writeBits' :: BoolWriteStateRef s
-           -> Word32     -- ^ The real data to be stored. Actual data should be in the LSB
-           -> Int        -- ^ Number of bit to write from 1 to 32
-           -> ST s ()
-{-# INLINE writeBits' #-}
-writeBits' st d c = do
-    currWord <- readSTRef $ bwsBitAcc st
-    currCount <- readSTRef $  bwsBitReaded st
-    serialize d c currWord currCount
-  where dumpByte 0xFF = pushByte' st 0xFF >> pushByte' st 0x00
-        dumpByte    i = pushByte' st i
-
-        serialize bitData bitCount currentWord count
-            | bitCount + count == 8 = do
-                     resetBitCount' st
-                     dumpByte (fromIntegral $ (currentWord `unsafeShiftL` bitCount) .|.
-                                                fromIntegral cleanData)
-
-            | bitCount + count < 8 =
-                let newVal = currentWord `unsafeShiftL` bitCount
-                in setBitCount' st (newVal .|. fromIntegral cleanData) $ count + bitCount
-
-            | otherwise =
-                let leftBitCount = 8 - count :: Int
-                    highPart = cleanData `unsafeShiftR` (bitCount - leftBitCount) :: Word32
-                    prevPart = fromIntegral currentWord `unsafeShiftL` leftBitCount :: Word32
-
-                    nextMask = (1 `unsafeShiftL` (bitCount - leftBitCount)) - 1 :: Word32
-                    newData = cleanData .&. nextMask :: Word32
-                    newCount = bitCount - leftBitCount :: Int
-
-                    toWrite = fromIntegral $ prevPart .|. highPart :: Word8
-                in dumpByte toWrite >> serialize newData newCount 0 0
-
-              where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
-                    cleanData = bitData .&. cleanMask     :: Word32
-
--- | Append some data bits to a Put monad.
-writeBitsGif :: BoolWriteStateRef s
-             -> Word32     -- ^ The real data to be stored. Actual data should be in the LSB
-             -> Int        -- ^ Number of bit to write from 1 to 32
-             -> ST s ()
-{-# INLINE writeBitsGif #-}
-writeBitsGif st d c = do
-    currWord <- readSTRef $ bwsBitAcc st
-    currCount <- readSTRef $  bwsBitReaded st
-    serialize d c currWord currCount
-  where dumpByte = pushByte' st
-
-        serialize bitData bitCount currentWord count
-            | bitCount + count == 8 = do
-                     resetBitCount' st
-                     dumpByte (fromIntegral $ currentWord  .|.
-                                                (fromIntegral cleanData `unsafeShiftL` count))
-
-            | bitCount + count < 8 =
-                let newVal = fromIntegral cleanData `unsafeShiftL` count
-                in setBitCount' st (newVal .|. currentWord) $ count + bitCount
-
-            | otherwise =
-                let leftBitCount = 8 - count :: Int
-                    newData = cleanData `unsafeShiftR` leftBitCount :: Word32
-                    newCount = bitCount - leftBitCount :: Int
-                    toWrite = fromIntegral $ fromIntegral currentWord 
-                                            .|. (cleanData `unsafeShiftL` count) :: Word8
-                in dumpByte toWrite >> serialize newData newCount 0 0
-
-              where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
-                    cleanData = bitData .&. cleanMask     :: Word32
-
-finalizeBoolWriterGif :: BoolWriteStateRef s -> ST s L.ByteString
-finalizeBoolWriterGif st = do
-    flushLeftBitsGif st
-    forceBufferFlushing' st
-    L.fromChunks <$> readSTRef (bwsBufferList st)
-
-flushLeftBitsGif :: BoolWriteStateRef s -> ST s ()
-flushLeftBitsGif st = do
-    currCount <- readSTRef $ bwsBitReaded st
-    when (currCount > 0) $ do
-      currWord <- readSTRef $ bwsBitAcc st
-      pushByte' st currWord
-
-{-# ANN module "HLint: ignore Reduce duplication" #-}
-
+{-# LANGUAGE Rank2Types #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE CPP #-}
+-- | This module implement helper functions to read & write data
+-- at bits level.
+module Codec.Picture.BitWriter( BoolReader
+                              , emptyBoolState
+                              , BoolState
+                              , byteAlignJpg
+                              , getNextBitsLSBFirst
+                              , getNextBitsMSBFirst 
+                              , getNextBitJpg
+                              , getNextIntJpg
+                              , setDecodedString
+                              , setDecodedStringMSB
+                              , setDecodedStringJpg
+                              , runBoolReader
+
+                              , BoolWriteStateRef 
+                              , newWriteStateRef
+                              , finalizeBoolWriter
+                              , finalizeBoolWriterGif
+                              , writeBits'
+                              , writeBitsGif
+
+                              , initBoolState 
+                              , initBoolStateJpg
+                              , execBoolReader
+                              , runBoolReaderWith
+                              ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<*>), (<$>) )
+#endif
+
+import Data.STRef
+import Control.Monad( when )
+import Control.Monad.ST( ST )
+import qualified Control.Monad.Trans.State.Strict as S
+import Data.Int ( Int32 )
+import Data.Word( Word8, Word32 )
+import Data.Bits( (.&.), (.|.), unsafeShiftR, unsafeShiftL )
+
+import Codec.Picture.VectorByteConversion( blitVector )
+import qualified Data.Vector.Storable.Mutable as M
+import qualified Data.Vector.Storable as VS
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as L
+
+
+--------------------------------------------------
+----            Reader
+--------------------------------------------------
+-- | Current bit index, current value, string
+data BoolState = BoolState {-# UNPACK #-} !Int
+                           {-# UNPACK #-} !Word8
+                           !B.ByteString
+
+emptyBoolState :: BoolState
+emptyBoolState = BoolState (-1) 0 B.empty
+
+-- | Type used to read bits
+type BoolReader s a = S.StateT BoolState (ST s) a
+
+runBoolReader :: BoolReader s a -> ST s a
+runBoolReader action = S.evalStateT action $ BoolState 0 0 B.empty
+
+runBoolReaderWith :: BoolState -> BoolReader s a -> ST s (a, BoolState)
+runBoolReaderWith st action = S.runStateT action st
+
+execBoolReader :: BoolState -> BoolReader s a -> ST s BoolState
+execBoolReader st reader = S.execStateT reader st
+
+initBoolState :: B.ByteString -> BoolState
+initBoolState str = case B.uncons str of
+     Nothing -> BoolState 0 0 B.empty
+     Just (v, rest) -> BoolState 0 v rest
+
+initBoolStateJpg :: B.ByteString -> BoolState
+initBoolStateJpg str = 
+   case B.uncons str of
+     Nothing -> BoolState 0 0 B.empty
+     Just (0xFF, rest) -> case B.uncons rest of
+            Nothing                  -> BoolState 7 0 B.empty
+            Just (0x00, afterMarker) -> BoolState 7 0xFF afterMarker
+            Just (_   , afterMarker) -> initBoolStateJpg afterMarker
+     Just (v, rest) -> BoolState 7 v rest
+
+-- | Bitify a list of things to decode.
+setDecodedString :: B.ByteString -> BoolReader s ()
+setDecodedString str = case B.uncons str of
+     Nothing        -> S.put $ BoolState      0 0 B.empty
+     Just (v, rest) -> S.put $ BoolState      0 v    rest
+
+-- | Drop all bit until the bit of indice 0, useful to parse restart
+-- marker, as they are byte aligned, but Huffman might not.
+byteAlignJpg :: BoolReader s ()
+byteAlignJpg = do
+  BoolState idx _ chain <- S.get
+  when (idx /= 7) (setDecodedStringJpg chain)
+
+getNextBitJpg :: BoolReader s Bool
+{-# INLINE getNextBitJpg #-}
+getNextBitJpg = do
+    BoolState idx v chain <- S.get
+    let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
+    if idx == 0
+      then setDecodedStringJpg chain
+      else S.put $ BoolState (idx - 1) v chain
+    return val
+
+getNextIntJpg :: Int -> BoolReader s Int32
+{-# INLINE getNextIntJpg #-}
+getNextIntJpg = go 0 where
+  go !acc !0 = return acc
+  go !acc !n = do
+    BoolState idx v chain <- S.get
+    let !leftBits = 1 + fromIntegral idx
+    if n >= leftBits then do
+      setDecodedStringJpg chain
+      let !remaining = n - leftBits
+          !mask = (1 `unsafeShiftL` leftBits) - 1
+          !finalV = fromIntegral v .&. mask
+          !theseBits = finalV `unsafeShiftL` remaining
+      go (acc .|. theseBits) remaining
+    else do
+      let !remaining = leftBits - n
+          !mask = (1 `unsafeShiftL` n) - 1
+          !finalV = fromIntegral v `unsafeShiftR` remaining
+      S.put $ BoolState (fromIntegral remaining - 1) v chain
+      return $ (finalV .&. mask) .|. acc
+
+
+setDecodedStringMSB :: B.ByteString -> BoolReader s ()
+setDecodedStringMSB str = case B.uncons str of
+  Nothing        -> S.put $ BoolState      8 0 B.empty
+  Just (v, rest) -> S.put $ BoolState      8 v    rest
+
+
+{-# INLINE getNextBitsMSBFirst #-}
+getNextBitsMSBFirst :: Int -> BoolReader s Word32
+getNextBitsMSBFirst requested = go 0 requested where
+  go :: Word32 -> Int -> BoolReader s Word32
+  go !acc !0 = return acc
+  go !acc !n = do
+    BoolState idx v chain <- S.get
+    let !leftBits = fromIntegral idx
+    if n >= leftBits then do
+      setDecodedStringMSB chain
+      let !theseBits = fromIntegral v `unsafeShiftL` (n - leftBits)
+      go (acc .|. theseBits) (n - leftBits)
+    else do
+      let !remaining = leftBits - n
+          !mask = (1 `unsafeShiftL` remaining) - 1
+      S.put $ BoolState (fromIntegral remaining) (v .&. mask) chain
+      return $ (fromIntegral v `unsafeShiftR` remaining) .|. acc
+
+{-# INLINE getNextBitsLSBFirst #-}
+getNextBitsLSBFirst :: Int -> BoolReader s Word32
+getNextBitsLSBFirst count = aux 0 count
+  where aux acc 0 = return acc
+        aux acc n = do
+            bit <- getNextBit
+            let nextVal | bit = acc .|. (1 `unsafeShiftL` (count - n))
+                        | otherwise = acc
+            aux nextVal (n - 1)
+
+{-# INLINE getNextBit #-}
+getNextBit :: BoolReader s Bool
+getNextBit = do
+    BoolState idx v chain <- S.get
+    let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
+    if idx == 7
+      then setDecodedString chain
+      else S.put $ BoolState (idx + 1) v chain
+    return val
+
+-- | Bitify a list of things to decode. Handle Jpeg escape
+-- code (0xFF 0x00), thus should be only used in JPEG decoding.
+setDecodedStringJpg :: B.ByteString -> BoolReader s ()
+setDecodedStringJpg str = case B.uncons str of
+     Nothing        -> S.put $ BoolState 7 0 B.empty
+     Just (0xFF, rest) -> case B.uncons rest of
+            Nothing                  -> S.put $ BoolState 7 0 B.empty
+            Just (0x00, afterMarker) -> -- trace "00" $ 
+                S.put $ BoolState 7 0xFF afterMarker
+            Just (_   , afterMarker) -> setDecodedStringJpg afterMarker
+     Just (v, rest) ->
+        S.put $ BoolState 7 v rest
+
+--------------------------------------------------
+----            Writer
+--------------------------------------------------
+defaultBufferSize :: Int
+defaultBufferSize = 256 * 1024
+
+data BoolWriteStateRef s = BoolWriteStateRef
+        { bwsCurrBuffer   :: STRef s (M.MVector s Word8)
+        , bwsBufferList   :: STRef s [B.ByteString]
+        , bwsWrittenWords :: STRef s Int
+        , bwsBitAcc       :: STRef s Word8
+        , bwsBitReaded    :: STRef s Int
+        }
+
+newWriteStateRef :: ST s (BoolWriteStateRef s)
+newWriteStateRef = do
+    origMv <- M.new defaultBufferSize
+    BoolWriteStateRef <$> newSTRef origMv
+                      <*> newSTRef []
+                      <*> newSTRef 0
+                      <*> newSTRef 0
+                      <*> newSTRef 0
+
+finalizeBoolWriter :: BoolWriteStateRef s -> ST s L.ByteString
+finalizeBoolWriter st = do
+    flushLeftBits' st
+    forceBufferFlushing' st
+    L.fromChunks <$> readSTRef (bwsBufferList st)
+
+forceBufferFlushing' :: BoolWriteStateRef s -> ST s ()
+forceBufferFlushing' (BoolWriteStateRef { bwsCurrBuffer = vecRef
+                                        , bwsWrittenWords = countRef
+                                        , bwsBufferList = lstRef
+                                        }) = do
+    vec <- readSTRef vecRef
+    count <- readSTRef countRef
+    lst <- readSTRef lstRef
+
+    nmv <- M.new defaultBufferSize
+    str <- byteStringFromVector vec count
+
+    writeSTRef vecRef nmv
+    writeSTRef lstRef $ lst ++ [str]
+    writeSTRef countRef 0
+
+flushCurrentBuffer' :: BoolWriteStateRef s -> ST s ()
+flushCurrentBuffer' st = do
+    count <- readSTRef $ bwsWrittenWords st
+    when (count >= defaultBufferSize)
+         (forceBufferFlushing' st)
+
+byteStringFromVector :: M.MVector s Word8 -> Int -> ST s B.ByteString
+byteStringFromVector vec size = do
+    frozen <- VS.unsafeFreeze vec
+    return $ blitVector frozen 0 size
+
+setBitCount' :: BoolWriteStateRef s -> Word8 -> Int -> ST s ()
+{-# INLINE setBitCount' #-}
+setBitCount' st acc count = do
+    writeSTRef (bwsBitAcc st) acc
+    writeSTRef (bwsBitReaded st) count
+
+resetBitCount' :: BoolWriteStateRef s -> ST s ()
+{-# INLINE resetBitCount' #-}
+resetBitCount' st = setBitCount' st 0 0
+
+pushByte' :: BoolWriteStateRef s -> Word8 -> ST s ()
+{-# INLINE pushByte' #-}
+pushByte' st v = do
+    flushCurrentBuffer' st
+    idx <- readSTRef (bwsWrittenWords st)
+    vec <- readSTRef (bwsCurrBuffer st)
+    M.write vec idx v
+    writeSTRef (bwsWrittenWords st) $ idx + 1
+
+flushLeftBits' :: BoolWriteStateRef s -> ST s ()
+flushLeftBits' st = do
+    currCount <- readSTRef $ bwsBitReaded st
+    when (currCount > 0) $ do
+      currWord <- readSTRef $ bwsBitAcc st
+      pushByte' st $ currWord `unsafeShiftL` (8 - currCount)
+
+-- | Append some data bits to a Put monad.
+writeBits' :: BoolWriteStateRef s
+           -> Word32     -- ^ The real data to be stored. Actual data should be in the LSB
+           -> Int        -- ^ Number of bit to write from 1 to 32
+           -> ST s ()
+{-# INLINE writeBits' #-}
+writeBits' st d c = do
+    currWord <- readSTRef $ bwsBitAcc st
+    currCount <- readSTRef $  bwsBitReaded st
+    serialize d c currWord currCount
+  where dumpByte 0xFF = pushByte' st 0xFF >> pushByte' st 0x00
+        dumpByte    i = pushByte' st i
+
+        serialize bitData bitCount currentWord count
+            | bitCount + count == 8 = do
+                     resetBitCount' st
+                     dumpByte (fromIntegral $ (currentWord `unsafeShiftL` bitCount) .|.
+                                                fromIntegral cleanData)
+
+            | bitCount + count < 8 =
+                let newVal = currentWord `unsafeShiftL` bitCount
+                in setBitCount' st (newVal .|. fromIntegral cleanData) $ count + bitCount
+
+            | otherwise =
+                let leftBitCount = 8 - count :: Int
+                    highPart = cleanData `unsafeShiftR` (bitCount - leftBitCount) :: Word32
+                    prevPart = fromIntegral currentWord `unsafeShiftL` leftBitCount :: Word32
+
+                    nextMask = (1 `unsafeShiftL` (bitCount - leftBitCount)) - 1 :: Word32
+                    newData = cleanData .&. nextMask :: Word32
+                    newCount = bitCount - leftBitCount :: Int
+
+                    toWrite = fromIntegral $ prevPart .|. highPart :: Word8
+                in dumpByte toWrite >> serialize newData newCount 0 0
+
+              where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
+                    cleanData = bitData .&. cleanMask     :: Word32
+
+-- | Append some data bits to a Put monad.
+writeBitsGif :: BoolWriteStateRef s
+             -> Word32     -- ^ The real data to be stored. Actual data should be in the LSB
+             -> Int        -- ^ Number of bit to write from 1 to 32
+             -> ST s ()
+{-# INLINE writeBitsGif #-}
+writeBitsGif st d c = do
+    currWord <- readSTRef $ bwsBitAcc st
+    currCount <- readSTRef $  bwsBitReaded st
+    serialize d c currWord currCount
+  where dumpByte = pushByte' st
+
+        serialize bitData bitCount currentWord count
+            | bitCount + count == 8 = do
+                     resetBitCount' st
+                     dumpByte (fromIntegral $ currentWord  .|.
+                                                (fromIntegral cleanData `unsafeShiftL` count))
+
+            | bitCount + count < 8 =
+                let newVal = fromIntegral cleanData `unsafeShiftL` count
+                in setBitCount' st (newVal .|. currentWord) $ count + bitCount
+
+            | otherwise =
+                let leftBitCount = 8 - count :: Int
+                    newData = cleanData `unsafeShiftR` leftBitCount :: Word32
+                    newCount = bitCount - leftBitCount :: Int
+                    toWrite = fromIntegral $ fromIntegral currentWord 
+                                            .|. (cleanData `unsafeShiftL` count) :: Word8
+                in dumpByte toWrite >> serialize newData newCount 0 0
+
+              where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
+                    cleanData = bitData .&. cleanMask     :: Word32
+
+finalizeBoolWriterGif :: BoolWriteStateRef s -> ST s L.ByteString
+finalizeBoolWriterGif st = do
+    flushLeftBitsGif st
+    forceBufferFlushing' st
+    L.fromChunks <$> readSTRef (bwsBufferList st)
+
+flushLeftBitsGif :: BoolWriteStateRef s -> ST s ()
+flushLeftBitsGif st = do
+    currCount <- readSTRef $ bwsBitReaded st
+    when (currCount > 0) $ do
+      currWord <- readSTRef $ bwsBitAcc st
+      pushByte' st currWord
+
+{-# ANN module "HLint: ignore Reduce duplication" #-}
+
diff --git a/src/Codec/Picture/Bitmap.hs b/src/Codec/Picture/Bitmap.hs
--- a/src/Codec/Picture/Bitmap.hs
+++ b/src/Codec/Picture/Bitmap.hs
@@ -51,7 +51,7 @@
                       )
 
 import Data.Bits
-import Data.Int( Int32 )
+import Data.Int( Int32, Int64 )
 import Data.Word( Word32, Word16, Word8 )
 import qualified Data.ByteString as B
 import qualified Data.ByteString.Internal as BI
@@ -528,7 +528,7 @@
   wi = fromIntegral w
   hi = abs $ fromIntegral h
   stArray = runST $ do
-      arr <- M.new (fromIntegral $ w * abs h * 4)
+      arr <- M.new (wi * hi * 4)
       if h > 0 then
         foldM_ (readLine arr) 0 [0 .. hi - 1]
       else
@@ -570,7 +570,7 @@
   wi = fromIntegral w
   hi = abs $ fromIntegral h
   stArray = runST $ do
-      arr <- M.new (fromIntegral $ w * abs h * 3)
+      arr <- M.new (wi * hi * 3)
       if h > 0 then
         foldM_ (readLine arr) 0 [0 .. hi - 1]
       else
@@ -620,7 +620,7 @@
   wi = fromIntegral w
   hi = abs $ fromIntegral h
   stArray = runST $ do
-      arr <- M.new . fromIntegral $ w * abs h
+      arr <- M.new (wi * hi)
       if h > 0 then
         foldM_ (readLine arr) 0 [0 .. hi - 1]
       else
@@ -667,9 +667,10 @@
   wi = fromIntegral w
   hi = abs $ fromIntegral h
   xOffsetMax = wi - 1
+  bufferSize = wi * hi
 
   stArray = runST $ do
-    arr <- M.new . fromIntegral $ w * abs h
+    arr <- M.new (wi * hi)
     decodeRLE arr (B.unpack (B.take (fromIntegral sz) str)) ((hi - 1) * wi, 0)
     VS.unsafeFreeze arr
 
@@ -716,10 +717,17 @@
           (False, _) ->
             writeByte b writePos >>= copyN isPadded (n - 1) rest
 
-      -- | Write the next byte to the output array.
+      -- | Write the next byte to the output array. Writes outside the
+      -- [0, wi*hi) range are clipped: malformed RLE streams can move the
+      -- cursor anywhere (delta escapes, EOL past the last row) and the
+      -- sibling non-RLE decoders clip at the end of the image the same way.
+      -- Unwritten pixels stay zero-filled (M.new initializes), so the
+      -- decoded image is deterministic.
       writeByte :: Word8 -> (Int, Int) -> ST s (Int, Int)
       writeByte byte (yOffset, xOffset) = do
-        (arr `M.unsafeWrite` (yOffset + xOffset)) byte
+        let writeIdx = yOffset + xOffset
+        when (writeIdx >= 0 && writeIdx < bufferSize) $
+          (arr `M.unsafeWrite` writeIdx) byte
         return (yOffset, (xOffset + 1) `min` xOffsetMax)
 
 pixel4Get :: Get [Word8]
@@ -785,6 +793,12 @@
 
   when (height bmpHeader == 0)
        (fail $ "Invalid bmp height (0) ")
+
+  -- Guard against 32-bit multiplication overflow in the image size computation
+  -- and absurd memory allocations: cap the pixel count at 2^29 (2 GiB of RGBA8).
+  when (fromIntegral (width bmpHeader) * abs (fromIntegral (height bmpHeader))
+          > (2 ^ (29 :: Int64)))
+       (fail $ "Invalid bmp dimensions, " ++ show (width bmpHeader, height bmpHeader))
 
   decodeBitmapWithHeaders fileHeader bmpHeader
 
diff --git a/src/Codec/Picture/ColorQuant.hs b/src/Codec/Picture/ColorQuant.hs
--- a/src/Codec/Picture/ColorQuant.hs
+++ b/src/Codec/Picture/ColorQuant.hs
@@ -1,435 +1,435 @@
-{-# LANGUAGE ExistentialQuantification #-}
-{-# LANGUAGE BangPatterns #-}
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE CPP #-}
--- | This module provide some color quantisation algorithm
--- in order to help in the creation of paletted images.
--- The most important function is `palettize` which will
--- make everything to create a nice color indexed image
--- with its palette.
-module Codec.Picture.ColorQuant
-    ( palettize
-    , palettizeWithAlpha
-    , defaultPaletteOptions
-    , PaletteCreationMethod(..)
-    , PaletteOptions( .. )
-    ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import           Control.Applicative (Applicative (..), (<$>))
-#endif
-
-import           Data.Bits           (unsafeShiftL, unsafeShiftR, (.&.), (.|.))
-import           Data.List           (elemIndex)
-import           Data.Maybe          (fromMaybe)
-import           Data.Set            (Set)
-import qualified Data.Set            as Set
-import           Data.Word           (Word32)
-
-import           Data.Vector         (Vector, (!))
-import qualified Data.Vector         as V
-import qualified Data.Vector.Unboxed as VU
-import qualified Data.Vector.Storable as VS
-
-import           Codec.Picture.Types
-import           Codec.Picture.Gif (GifFrame(..), GifDisposalMethod, GifDelay)
-
--------------------------------------------------------------------------------
-----            Palette Creation and Dithering
--------------------------------------------------------------------------------
-
--- | Define which palette creation method is used.
-data PaletteCreationMethod =
-      -- | MedianMeanCut method, provide the best results (visualy)
-      -- at the cost of increased calculations.
-      MedianMeanCut
-      -- | Very fast algorithm (one pass), doesn't provide good
-      -- looking results.
-    | Uniform
-
--- | To specify how the palette will be created.
-data PaletteOptions = PaletteOptions
-    { -- | Algorithm used to find the palette
-      paletteCreationMethod :: PaletteCreationMethod
-
-      -- | Do we want to apply the dithering to the
-      -- image. Enabling it often reduce compression
-      -- ratio but enhance the perceived quality
-      -- of the final image.
-    , enableImageDithering  :: Bool
-
-      -- | Maximum number of color we want in the
-      -- palette
-    , paletteColorCount     :: Int
-    }
-
--- | Default palette option, which aim at the best quality
--- and maximum possible colors (256)
-defaultPaletteOptions :: PaletteOptions
-defaultPaletteOptions = PaletteOptions
-    { paletteCreationMethod = MedianMeanCut
-    , enableImageDithering  = True
-    , paletteColorCount     = 256
-    }
-
--- | Changes all pixels with alpha = 0 to black
--- converting image to RGB (from RGBA) in meantime
-alphaToBlack :: Image PixelRGBA8 -> Image PixelRGB8
-alphaToBlack = pixelMap f
-  where f (PixelRGBA8 r g b a) =
-          if a == 0 then PixelRGB8 0 0 0
-          else PixelRGB8 r g b
-
--- | Using second image as a stencil, changes palette index to the transparent
-alphaTo255 :: Image Pixel8 -> Image PixelRGBA8 -> Pixel8 -> Image Pixel8
-alphaTo255 img1 img2 transparentIndex = generateImage f (imageWidth img1) (imageHeight img2)
-  where f x y =
-          if a == 0 then transparentIndex
-          else v
-          where v = pixelAt img1 x y
-                PixelRGBA8 _ _ _ a = pixelAt img2 x y
-
--- | Converts RGBA image to the array of GifFame's to use in encodeComplexGifImage
-palettizeWithAlpha :: [(GifDelay, Image PixelRGBA8)] -> GifDisposalMethod -> [GifFrame]
-palettizeWithAlpha [] _ = []
-palettizeWithAlpha (x:xs) dispose =
-  GifFrame
-    0 -- Offset X
-    0 -- Offset Y 
-    (Just $ palet)
-    (Just $ transparentIndex)
-    delay
-    dispose
-    (alphaTo255 pixels i (fromIntegral transparentIndex))
-  : palettizeWithAlpha xs dispose
-  where (delay, i) = x
-        img = alphaToBlack i
-        (palet, pixels) =
-          if isBelow
-            then (vecToPalette (belowPaletteVec `V.snoc` PixelRGB8 0 0 0), pixelMap belowPaletteIndex img)
-            else (vecToPalette (genPaletteVec   `V.snoc` PixelRGB8 0 0 0), pixelMap genPaletteIndex img)
-
-        (belowPalette, isBelow) = isColorCountBelow 255 img
-        belowPaletteVec = V.fromList $ Set.toList belowPalette
-        belowPaletteIndex p = nearestColorIdx p belowPaletteVec
-
-        cs = Set.toList . clusters 255 $ img
-        genPaletteVec = mkPaletteVec cs
-        genPaletteIndex p = nearestColorIdx p genPaletteVec
-
-        transparentIndex = length $ if isBelow then belowPaletteVec else genPaletteVec
-
--- | Reduces an image to a color palette according to `PaletteOptions` and
---   returns the /indices image/ along with its `Palette`.
-palettize :: PaletteOptions -> Image PixelRGB8 -> (Image Pixel8, Palette)
-palettize opts@PaletteOptions { paletteCreationMethod = method } =
-  case method of
-    MedianMeanCut -> medianMeanCutQuantization opts
-    Uniform       -> uniformQuantization opts
-
--- | Modified median cut algorithm with optional ordered dithering. Returns an
--- image of `Pixel8` that acts as a matrix of indices into the `Palette`.
-medianMeanCutQuantization :: PaletteOptions -> Image PixelRGB8
-                          -> (Image Pixel8, Palette)
-medianMeanCutQuantization opts img
-  | isBelow =
-      (pixelMap okPaletteIndex img, vecToPalette okPaletteVec)
-  | enableImageDithering opts = (pixelMap paletteIndex dImg, palette)
-  | otherwise = (pixelMap paletteIndex img, palette)
-  where
-    maxColorCount = paletteColorCount opts
-    (okPalette, isBelow) = isColorCountBelow maxColorCount img
-    okPaletteVec = V.fromList $ Set.toList okPalette
-    okPaletteIndex p = nearestColorIdx p okPaletteVec
-
-    palette = vecToPalette paletteVec
-    paletteIndex p = nearestColorIdx p paletteVec
-    paletteVec = mkPaletteVec cs
-    cs =  Set.toList . clusters maxColorCount $ img
-    dImg = pixelMapXY dither img
-
--- | A naive one pass Color Quantization algorithm - Uniform Quantization.
--- Simply take the most significant bits. The maxCols parameter is rounded
--- down to the nearest power of 2, and the bits are divided among the three
--- color channels with priority order green, red, blue. Returns an
--- image of `Pixel8` that acts as a matrix of indices into the `Palette`.
-uniformQuantization :: PaletteOptions -> Image PixelRGB8 -> (Image Pixel8, Palette)
-uniformQuantization opts img
-  -- -| colorCount img <= maxCols = colorQuantExact img
-  | enableImageDithering opts =
-        (pixelMap paletteIndex (pixelMapXY dither img), palette)
-  | otherwise = (pixelMap paletteIndex img, palette)
-  where
-    maxCols = paletteColorCount opts
-    palette = listToPalette paletteList
-    paletteList = [PixelRGB8 r g b | r <- [0,dr..255]
-                                   , g <- [0,dg..255]
-                                   , b <- [0,db..255]]
-    (bg, br, bb) = bitDiv3 maxCols
-    (dr, dg, db) = (2^(8-br), 2^(8-bg), 2^(8-bb))
-    paletteIndex (PixelRGB8 r g b) = fromIntegral $ fromMaybe 0 (elemIndex
-      (PixelRGB8 (r .&. negate dr) (g .&. negate dg) (b .&. negate db))
-      paletteList)
-
-isColorCountBelow :: Int -> Image PixelRGB8 -> (Set.Set PixelRGB8, Bool)
-isColorCountBelow maxColorCount img = go 0 Set.empty
-  where rawData = imageData img
-        maxIndex = VS.length rawData
-        
-        go !idx !allColors
-            | Set.size allColors > maxColorCount = (Set.empty, False)
-            | idx >= maxIndex - 2 = (allColors, True)
-            | otherwise = go (idx + 3) $ Set.insert px allColors
-                where px = unsafePixelAt rawData idx 
-
-vecToPalette :: Vector PixelRGB8 -> Palette
-vecToPalette ps = generateImage (\x _ -> ps ! x) (V.length ps) 1
-
-listToPalette :: [PixelRGB8] -> Palette
-listToPalette ps = generateImage (\x _ -> ps !! x) (length ps) 1
-
-bitDiv3 :: Int -> (Int, Int, Int)
-bitDiv3 n = case r of
-            0 -> (q, q, q)
-            1 -> (q+1, q, q)
-            _ -> (q+1, q+1, q)
-  where
-    r = m `mod` 3
-    q = m `div` 3
-    m = floor . logBase (2 :: Double) $ fromIntegral n
-
--------------------------------------------------------------------------------
-----            Dithering
--------------------------------------------------------------------------------
-
--- Add a dither mask to an image for ordered dithering.
--- Uses a small, spatially stable dithering algorithm based on magic numbers
--- and arithmetic inspired by the /a dither/ algorithm of Øyvind Kolås,
--- pippin@gimp.org, 2013. See, http://pippin.gimp.org/a_dither/.
-dither :: Int -> Int -> PixelRGB8 -> PixelRGB8
-dither x y (PixelRGB8 r g b) = PixelRGB8 (fromIntegral r')
-                                         (fromIntegral g')
-                                         (fromIntegral b')
-  where
-    -- Should view 16 as a parameter that can be optimized for best looking
-    -- results
-    r' = min 255 (fromIntegral r + (x' + y') .&. 16)
-    g' = min 255 (fromIntegral g + (x' + y' + 7973) .&. 16)
-    b' = min 255 (fromIntegral b + (x' + y' + 15946) .&. 16)
-    x' = 119 * x
-    y' = 28084 * y
-
--------------------------------------------------------------------------------
-----            Small modification of foldl package by Gabriel Gonzalez
--------------------------------------------------------------------------------
-
--- Modification to Control.foldl by Gabriel Gonzalez copyright 2013, BSD3.
--- http://hackage.haskell.org/package/foldl-1.0.1/docs/Control-Foldl.html
-
-{-| Efficient representation of a left fold that preserves the fold's step
-    function, initial accumulator, and extraction function
-
-    This allows the 'Applicative' instance to assemble derived folds that
-    traverse the container only once
--}
-data Fold a b = forall x . Fold (x -> a -> x) x (x -> b)
-
-{-| Apply a strict left 'Fold' to a 'Foldable' container
-
-    Much slower than 'fold' on lists because 'Foldable' operations currently do
-    not trigger @build/foldr@ fusion
--}
-fold :: Fold PackedRGB b -> VU.Vector PackedRGB -> b
-fold (Fold step begin done) = done . VU.foldl' step begin
-{-# INLINE fold #-}
-
-{-
-F.foldr :: (a -> b -> b) -> b -> t a -> b
-
-fold :: (Foldable f) => Fold a b -> f a -> b
-fold (Fold step begin done) as = F.foldr step' done as begin
-  where step' x k z = k $! step z x
--}
-
-data Pair a b = Pair !a !b
-
-instance Functor (Fold a) where
-    fmap f (Fold step begin done) = Fold step begin (f . done)
-    {-# INLINABLE fmap #-}
-
-instance Applicative (Fold a) where
-    pure b    = Fold (\() _ -> ()) () (\() -> b)
-    {-# INLINABLE pure #-}
-    (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =
-        let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)
-            begin = Pair beginL beginR
-            done (Pair xL xR) = doneL xL $ doneR xR
-        in  Fold step begin done
-    {-# INLINABLE (<*>) #-}
-
-{- | Like 'length', except with a more general 'Num' return value -}
-intLength :: Fold a Int
-intLength = Fold (\n _ -> n + 1) 0 id
-
--------------------------------------------------------------------------------
-----            Modified Median Cut Algorithm
--------------------------------------------------------------------------------
-
--- Based on the OCaml implementation:
--- http://rosettacode.org/wiki/Color_quantization
--- which is in turn based on: www.leptonica.org/papers/mediancut.pdf.
--- We use the product of volume and population to determine the next cluster
--- to split and determine the placement of each color by compating it to the
--- mean of the parent cluster. So median cut is a bit of a misnomer, since one
--- of the modifiations is to use the mean.
-
-mkPaletteVec :: [Cluster] -> Vector PixelRGB8
-mkPaletteVec  = V.fromList . map (toRGB8 . meanColor)
-
-type PackedRGB = Word32
-
-data Cluster = Cluster
-    { value       :: {-# UNPACK #-} !Float
-    , meanColor   :: !PixelRGBF
-    , dims        :: !PixelRGBF
-    , colors      :: VU.Vector PackedRGB
-    }
-
-instance Eq Cluster where
-    a == b =
-        (value a, meanColor a, dims a) == (value b, meanColor b, dims b)
-
-instance Ord Cluster where
-    compare a b =
-        compare (value a, meanColor a, dims a) (value b, meanColor b, dims b)
-
-data Axis = RAxis | GAxis | BAxis
-
-inf :: Float
-inf = read "Infinity"
-
-fromRGB8 :: PixelRGB8 -> PixelRGBF
-fromRGB8 (PixelRGB8 r g b) =
-  PixelRGBF (fromIntegral r) (fromIntegral g) (fromIntegral b)
-
-toRGB8 :: PixelRGBF -> PixelRGB8
-toRGB8 (PixelRGBF r g b) =
-  PixelRGB8 (round r) (round g) (round b)
-
-meanRGB :: Fold PixelRGBF PixelRGBF
-meanRGB = mean <$> intLength <*> pixelSum
-  where
-    pixelSum = Fold (mixWith $ const (+)) (PixelRGBF 0 0 0) id
-    mean n = colorMap (/ nf)
-      where nf = fromIntegral n
-
-minimal :: Fold PixelRGBF PixelRGBF
-minimal = Fold mini (PixelRGBF inf inf inf) id
-  where mini = mixWith $ const min
-
-maximal :: Fold PixelRGBF PixelRGBF
-maximal = Fold maxi (PixelRGBF (-inf) (-inf) (-inf)) id
-  where maxi = mixWith $ const max
-
-extrems :: Fold PixelRGBF (PixelRGBF, PixelRGBF)
-extrems = (,) <$> minimal <*> maximal
-
-volAndDims :: Fold PixelRGBF (Float, PixelRGBF)
-volAndDims = deltify <$> extrems
-  where deltify (mini, maxi) = (dr * dg * db, delta)
-          where delta@(PixelRGBF dr dg db) =
-                        mixWith (const (-)) maxi mini
-
-unpackFold :: Fold PixelRGBF a -> Fold PackedRGB a
-unpackFold (Fold step start done) = Fold (\acc -> step acc . transform) start done
-  where transform = fromRGB8 . rgbIntUnpack
-
-mkCluster :: VU.Vector PackedRGB -> Cluster
-mkCluster ps = Cluster
-    { value = v * fromIntegral l
-    , meanColor = m
-    , dims = ds
-    , colors = ps
-    }
-  where
-    worker = (,,) <$> volAndDims <*> meanRGB <*> intLength
-    ((v, ds), m, l) = fold (unpackFold worker) ps
-
-maxAxis :: PixelRGBF -> Axis
-maxAxis (PixelRGBF r g b) =
-  case (r `compare` g, r `compare` b, g `compare` b) of
-    (GT, GT, _)  -> RAxis
-    (LT, GT, _)  -> GAxis
-    (GT, LT, _)  -> BAxis
-    (LT, LT, GT) -> GAxis
-    (EQ, GT, _)  -> RAxis
-    (_,  _,  _)  -> BAxis
-
--- Split a cluster about its largest axis using the mean to divide up the
--- pixels.
-subdivide :: Cluster -> (Cluster, Cluster)
-subdivide cluster = (mkCluster px1, mkCluster px2)
-  where
-    (PixelRGBF mr mg mb) = meanColor cluster
-    (px1, px2) = VU.partition (cond . rgbIntUnpack) $ colors cluster
-    cond = case maxAxis $ dims cluster of
-      RAxis -> \(PixelRGB8 r _ _) -> fromIntegral r < mr
-      GAxis -> \(PixelRGB8 _ g _) -> fromIntegral g < mg
-      BAxis -> \(PixelRGB8 _ _ b) -> fromIntegral b < mb
-
-rgbIntPack :: PixelRGB8 -> PackedRGB
-rgbIntPack (PixelRGB8 r g b) =
-    wr `unsafeShiftL` (2 * 8) .|. wg `unsafeShiftL` 8 .|. wb
-  where wr = fromIntegral r
-        wg = fromIntegral g
-        wb = fromIntegral b
-
-rgbIntUnpack :: PackedRGB -> PixelRGB8
-rgbIntUnpack v = PixelRGB8 r g b
-  where
-    r = fromIntegral $ v `unsafeShiftR` (2 * 8)
-    g = fromIntegral $ v `unsafeShiftR` 8
-    b = fromIntegral v
-
-initCluster :: Image PixelRGB8 -> Cluster
-initCluster img = mkCluster $ VU.generate ((w * h) `div` subSampling) packer
-  where samplingFactor = 3
-        subSampling = samplingFactor * samplingFactor
-        compCount = componentCount (undefined :: PixelRGB8)
-        w = imageWidth img
-        h = imageHeight img
-        rawData = imageData img
-        packer ix =
-            rgbIntPack . unsafePixelAt rawData $ ix * subSampling * compCount
-
--- Take the cluster with the largest value = (volume * population) and remove it
--- from the priority queue. Then subdivide it about its largest axis and put the
--- two new clusters on the queue.
-split :: Set Cluster -> Set Cluster
-split cs = Set.insert c1 . Set.insert c2  $ cs'
-  where
-    (c, cs') = Set.deleteFindMax cs
-    (c1, c2) = subdivide c
-
--- Keep splitting the initial cluster until there are 256 clusters, then return
--- a priority queue containing all 256.
-clusters :: Int -> Image PixelRGB8 -> Set Cluster
-clusters maxCols img = clusters' (maxCols - 1)
-  where
-    clusters' :: Int -> Set Cluster
-    clusters' 0 = Set.singleton c
-    clusters' n = split (clusters' (n-1))
-    c = initCluster img
-
--- Euclidean distance squared, between two pixels.
-dist2Px :: PixelRGB8 -> PixelRGB8 -> Int
-dist2Px (PixelRGB8 r1 g1 b1) (PixelRGB8 r2 g2 b2) = dr*dr + dg*dg + db*db
-  where
-    (dr, dg, db) =
-      ( fromIntegral r1 - fromIntegral r2
-      , fromIntegral g1 - fromIntegral g2
-      , fromIntegral b1 - fromIntegral b2 )
-
-nearestColorIdx :: PixelRGB8 -> Vector PixelRGB8 -> Pixel8
-nearestColorIdx p ps  = fromIntegral $ V.minIndex (V.map (`dist2Px` p) ps)
+{-# LANGUAGE ExistentialQuantification #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE CPP #-}
+-- | This module provide some color quantisation algorithm
+-- in order to help in the creation of paletted images.
+-- The most important function is `palettize` which will
+-- make everything to create a nice color indexed image
+-- with its palette.
+module Codec.Picture.ColorQuant
+    ( palettize
+    , palettizeWithAlpha
+    , defaultPaletteOptions
+    , PaletteCreationMethod(..)
+    , PaletteOptions( .. )
+    ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import           Control.Applicative (Applicative (..), (<$>))
+#endif
+
+import           Data.Bits           (unsafeShiftL, unsafeShiftR, (.&.), (.|.))
+import           Data.List           (elemIndex)
+import           Data.Maybe          (fromMaybe)
+import           Data.Set            (Set)
+import qualified Data.Set            as Set
+import           Data.Word           (Word32)
+
+import           Data.Vector         (Vector, (!))
+import qualified Data.Vector         as V
+import qualified Data.Vector.Unboxed as VU
+import qualified Data.Vector.Storable as VS
+
+import           Codec.Picture.Types
+import           Codec.Picture.Gif (GifFrame(..), GifDisposalMethod, GifDelay)
+
+-------------------------------------------------------------------------------
+----            Palette Creation and Dithering
+-------------------------------------------------------------------------------
+
+-- | Define which palette creation method is used.
+data PaletteCreationMethod =
+      -- | MedianMeanCut method, provide the best results (visually)
+      -- at the cost of increased calculations.
+      MedianMeanCut
+      -- | Very fast algorithm (one pass), doesn't provide good
+      -- looking results.
+    | Uniform
+
+-- | To specify how the palette will be created.
+data PaletteOptions = PaletteOptions
+    { -- | Algorithm used to find the palette
+      paletteCreationMethod :: PaletteCreationMethod
+
+      -- | Do we want to apply the dithering to the
+      -- image. Enabling it often reduce compression
+      -- ratio but enhance the perceived quality
+      -- of the final image.
+    , enableImageDithering  :: Bool
+
+      -- | Maximum number of color we want in the
+      -- palette
+    , paletteColorCount     :: Int
+    }
+
+-- | Default palette option, which aim at the best quality
+-- and maximum possible colors (256)
+defaultPaletteOptions :: PaletteOptions
+defaultPaletteOptions = PaletteOptions
+    { paletteCreationMethod = MedianMeanCut
+    , enableImageDithering  = True
+    , paletteColorCount     = 256
+    }
+
+-- | Changes all pixels with alpha = 0 to black
+-- converting image to RGB (from RGBA) in meantime
+alphaToBlack :: Image PixelRGBA8 -> Image PixelRGB8
+alphaToBlack = pixelMap f
+  where f (PixelRGBA8 r g b a) =
+          if a == 0 then PixelRGB8 0 0 0
+          else PixelRGB8 r g b
+
+-- | Using second image as a stencil, changes palette index to the transparent
+alphaTo255 :: Image Pixel8 -> Image PixelRGBA8 -> Pixel8 -> Image Pixel8
+alphaTo255 img1 img2 transparentIndex = generateImage f (imageWidth img1) (imageHeight img2)
+  where f x y =
+          if a == 0 then transparentIndex
+          else v
+          where v = pixelAt img1 x y
+                PixelRGBA8 _ _ _ a = pixelAt img2 x y
+
+-- | Converts RGBA image to the array of GifFame's to use in encodeComplexGifImage
+palettizeWithAlpha :: [(GifDelay, Image PixelRGBA8)] -> GifDisposalMethod -> [GifFrame]
+palettizeWithAlpha [] _ = []
+palettizeWithAlpha (x:xs) dispose =
+  GifFrame
+    0 -- Offset X
+    0 -- Offset Y 
+    (Just $ palet)
+    (Just $ transparentIndex)
+    delay
+    dispose
+    (alphaTo255 pixels i (fromIntegral transparentIndex))
+  : palettizeWithAlpha xs dispose
+  where (delay, i) = x
+        img = alphaToBlack i
+        (palet, pixels) =
+          if isBelow
+            then (vecToPalette (belowPaletteVec `V.snoc` PixelRGB8 0 0 0), pixelMap belowPaletteIndex img)
+            else (vecToPalette (genPaletteVec   `V.snoc` PixelRGB8 0 0 0), pixelMap genPaletteIndex img)
+
+        (belowPalette, isBelow) = isColorCountBelow 255 img
+        belowPaletteVec = V.fromList $ Set.toList belowPalette
+        belowPaletteIndex p = nearestColorIdx p belowPaletteVec
+
+        cs = Set.toList . clusters 255 $ img
+        genPaletteVec = mkPaletteVec cs
+        genPaletteIndex p = nearestColorIdx p genPaletteVec
+
+        transparentIndex = length $ if isBelow then belowPaletteVec else genPaletteVec
+
+-- | Reduces an image to a color palette according to `PaletteOptions` and
+--   returns the /indices image/ along with its `Palette`.
+palettize :: PaletteOptions -> Image PixelRGB8 -> (Image Pixel8, Palette)
+palettize opts@PaletteOptions { paletteCreationMethod = method } =
+  case method of
+    MedianMeanCut -> medianMeanCutQuantization opts
+    Uniform       -> uniformQuantization opts
+
+-- | Modified median cut algorithm with optional ordered dithering. Returns an
+-- image of `Pixel8` that acts as a matrix of indices into the `Palette`.
+medianMeanCutQuantization :: PaletteOptions -> Image PixelRGB8
+                          -> (Image Pixel8, Palette)
+medianMeanCutQuantization opts img
+  | isBelow =
+      (pixelMap okPaletteIndex img, vecToPalette okPaletteVec)
+  | enableImageDithering opts = (pixelMap paletteIndex dImg, palette)
+  | otherwise = (pixelMap paletteIndex img, palette)
+  where
+    maxColorCount = paletteColorCount opts
+    (okPalette, isBelow) = isColorCountBelow maxColorCount img
+    okPaletteVec = V.fromList $ Set.toList okPalette
+    okPaletteIndex p = nearestColorIdx p okPaletteVec
+
+    palette = vecToPalette paletteVec
+    paletteIndex p = nearestColorIdx p paletteVec
+    paletteVec = mkPaletteVec cs
+    cs =  Set.toList . clusters maxColorCount $ img
+    dImg = pixelMapXY dither img
+
+-- | A naive one pass Color Quantization algorithm - Uniform Quantization.
+-- Simply take the most significant bits. The maxCols parameter is rounded
+-- down to the nearest power of 2, and the bits are divided among the three
+-- color channels with priority order green, red, blue. Returns an
+-- image of `Pixel8` that acts as a matrix of indices into the `Palette`.
+uniformQuantization :: PaletteOptions -> Image PixelRGB8 -> (Image Pixel8, Palette)
+uniformQuantization opts img
+  -- -| colorCount img <= maxCols = colorQuantExact img
+  | enableImageDithering opts =
+        (pixelMap paletteIndex (pixelMapXY dither img), palette)
+  | otherwise = (pixelMap paletteIndex img, palette)
+  where
+    maxCols = paletteColorCount opts
+    palette = listToPalette paletteList
+    paletteList = [PixelRGB8 r g b | r <- [0,dr..255]
+                                   , g <- [0,dg..255]
+                                   , b <- [0,db..255]]
+    (bg, br, bb) = bitDiv3 maxCols
+    (dr, dg, db) = (2^(8-br), 2^(8-bg), 2^(8-bb))
+    paletteIndex (PixelRGB8 r g b) = fromIntegral $ fromMaybe 0 (elemIndex
+      (PixelRGB8 (r .&. negate dr) (g .&. negate dg) (b .&. negate db))
+      paletteList)
+
+isColorCountBelow :: Int -> Image PixelRGB8 -> (Set.Set PixelRGB8, Bool)
+isColorCountBelow maxColorCount img = go 0 Set.empty
+  where rawData = imageData img
+        maxIndex = VS.length rawData
+        
+        go !idx !allColors
+            | Set.size allColors > maxColorCount = (Set.empty, False)
+            | idx >= maxIndex - 2 = (allColors, True)
+            | otherwise = go (idx + 3) $ Set.insert px allColors
+                where px = unsafePixelAt rawData idx 
+
+vecToPalette :: Vector PixelRGB8 -> Palette
+vecToPalette ps = generateImage (\x _ -> ps ! x) (V.length ps) 1
+
+listToPalette :: [PixelRGB8] -> Palette
+listToPalette ps = generateImage (\x _ -> ps !! x) (length ps) 1
+
+bitDiv3 :: Int -> (Int, Int, Int)
+bitDiv3 n = case r of
+            0 -> (q, q, q)
+            1 -> (q+1, q, q)
+            _ -> (q+1, q+1, q)
+  where
+    r = m `mod` 3
+    q = m `div` 3
+    m = floor . logBase (2 :: Double) $ fromIntegral n
+
+-------------------------------------------------------------------------------
+----            Dithering
+-------------------------------------------------------------------------------
+
+-- Add a dither mask to an image for ordered dithering.
+-- Uses a small, spatially stable dithering algorithm based on magic numbers
+-- and arithmetic inspired by the /a dither/ algorithm of Øyvind Kolås,
+-- pippin@gimp.org, 2013. See, http://pippin.gimp.org/a_dither/.
+dither :: Int -> Int -> PixelRGB8 -> PixelRGB8
+dither x y (PixelRGB8 r g b) = PixelRGB8 (fromIntegral r')
+                                         (fromIntegral g')
+                                         (fromIntegral b')
+  where
+    -- Should view 16 as a parameter that can be optimized for best looking
+    -- results
+    r' = min 255 (fromIntegral r + (x' + y') .&. 16)
+    g' = min 255 (fromIntegral g + (x' + y' + 7973) .&. 16)
+    b' = min 255 (fromIntegral b + (x' + y' + 15946) .&. 16)
+    x' = 119 * x
+    y' = 28084 * y
+
+-------------------------------------------------------------------------------
+----            Small modification of foldl package by Gabriel Gonzalez
+-------------------------------------------------------------------------------
+
+-- Modification to Control.foldl by Gabriel Gonzalez copyright 2013, BSD3.
+-- http://hackage.haskell.org/package/foldl-1.0.1/docs/Control-Foldl.html
+
+{-| Efficient representation of a left fold that preserves the fold's step
+    function, initial accumulator, and extraction function
+
+    This allows the 'Applicative' instance to assemble derived folds that
+    traverse the container only once
+-}
+data Fold a b = forall x . Fold (x -> a -> x) x (x -> b)
+
+{-| Apply a strict left 'Fold' to a 'Foldable' container
+
+    Much slower than 'fold' on lists because 'Foldable' operations currently do
+    not trigger @build/foldr@ fusion
+-}
+fold :: Fold PackedRGB b -> VU.Vector PackedRGB -> b
+fold (Fold step begin done) = done . VU.foldl' step begin
+{-# INLINE fold #-}
+
+{-
+F.foldr :: (a -> b -> b) -> b -> t a -> b
+
+fold :: (Foldable f) => Fold a b -> f a -> b
+fold (Fold step begin done) as = F.foldr step' done as begin
+  where step' x k z = k $! step z x
+-}
+
+data Pair a b = Pair !a !b
+
+instance Functor (Fold a) where
+    fmap f (Fold step begin done) = Fold step begin (f . done)
+    {-# INLINABLE fmap #-}
+
+instance Applicative (Fold a) where
+    pure b    = Fold (\() _ -> ()) () (\() -> b)
+    {-# INLINABLE pure #-}
+    (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =
+        let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)
+            begin = Pair beginL beginR
+            done (Pair xL xR) = doneL xL $ doneR xR
+        in  Fold step begin done
+    {-# INLINABLE (<*>) #-}
+
+{- | Like 'length', except with a more general 'Num' return value -}
+intLength :: Fold a Int
+intLength = Fold (\n _ -> n + 1) 0 id
+
+-------------------------------------------------------------------------------
+----            Modified Median Cut Algorithm
+-------------------------------------------------------------------------------
+
+-- Based on the OCaml implementation:
+-- http://rosettacode.org/wiki/Color_quantization
+-- which is in turn based on: www.leptonica.org/papers/mediancut.pdf.
+-- We use the product of volume and population to determine the next cluster
+-- to split and determine the placement of each color by compating it to the
+-- mean of the parent cluster. So median cut is a bit of a misnomer, since one
+-- of the modifications is to use the mean.
+
+mkPaletteVec :: [Cluster] -> Vector PixelRGB8
+mkPaletteVec  = V.fromList . map (toRGB8 . meanColor)
+
+type PackedRGB = Word32
+
+data Cluster = Cluster
+    { value       :: {-# UNPACK #-} !Float
+    , meanColor   :: !PixelRGBF
+    , dims        :: !PixelRGBF
+    , colors      :: VU.Vector PackedRGB
+    }
+
+instance Eq Cluster where
+    a == b =
+        (value a, meanColor a, dims a) == (value b, meanColor b, dims b)
+
+instance Ord Cluster where
+    compare a b =
+        compare (value a, meanColor a, dims a) (value b, meanColor b, dims b)
+
+data Axis = RAxis | GAxis | BAxis
+
+inf :: Float
+inf = read "Infinity"
+
+fromRGB8 :: PixelRGB8 -> PixelRGBF
+fromRGB8 (PixelRGB8 r g b) =
+  PixelRGBF (fromIntegral r) (fromIntegral g) (fromIntegral b)
+
+toRGB8 :: PixelRGBF -> PixelRGB8
+toRGB8 (PixelRGBF r g b) =
+  PixelRGB8 (round r) (round g) (round b)
+
+meanRGB :: Fold PixelRGBF PixelRGBF
+meanRGB = mean <$> intLength <*> pixelSum
+  where
+    pixelSum = Fold (mixWith $ const (+)) (PixelRGBF 0 0 0) id
+    mean n = colorMap (/ nf)
+      where nf = fromIntegral n
+
+minimal :: Fold PixelRGBF PixelRGBF
+minimal = Fold mini (PixelRGBF inf inf inf) id
+  where mini = mixWith $ const min
+
+maximal :: Fold PixelRGBF PixelRGBF
+maximal = Fold maxi (PixelRGBF (-inf) (-inf) (-inf)) id
+  where maxi = mixWith $ const max
+
+extrems :: Fold PixelRGBF (PixelRGBF, PixelRGBF)
+extrems = (,) <$> minimal <*> maximal
+
+volAndDims :: Fold PixelRGBF (Float, PixelRGBF)
+volAndDims = deltify <$> extrems
+  where deltify (mini, maxi) = (dr * dg * db, delta)
+          where delta@(PixelRGBF dr dg db) =
+                        mixWith (const (-)) maxi mini
+
+unpackFold :: Fold PixelRGBF a -> Fold PackedRGB a
+unpackFold (Fold step start done) = Fold (\acc -> step acc . transform) start done
+  where transform = fromRGB8 . rgbIntUnpack
+
+mkCluster :: VU.Vector PackedRGB -> Cluster
+mkCluster ps = Cluster
+    { value = v * fromIntegral l
+    , meanColor = m
+    , dims = ds
+    , colors = ps
+    }
+  where
+    worker = (,,) <$> volAndDims <*> meanRGB <*> intLength
+    ((v, ds), m, l) = fold (unpackFold worker) ps
+
+maxAxis :: PixelRGBF -> Axis
+maxAxis (PixelRGBF r g b) =
+  case (r `compare` g, r `compare` b, g `compare` b) of
+    (GT, GT, _)  -> RAxis
+    (LT, GT, _)  -> GAxis
+    (GT, LT, _)  -> BAxis
+    (LT, LT, GT) -> GAxis
+    (EQ, GT, _)  -> RAxis
+    (_,  _,  _)  -> BAxis
+
+-- Split a cluster about its largest axis using the mean to divide up the
+-- pixels.
+subdivide :: Cluster -> (Cluster, Cluster)
+subdivide cluster = (mkCluster px1, mkCluster px2)
+  where
+    (PixelRGBF mr mg mb) = meanColor cluster
+    (px1, px2) = VU.partition (cond . rgbIntUnpack) $ colors cluster
+    cond = case maxAxis $ dims cluster of
+      RAxis -> \(PixelRGB8 r _ _) -> fromIntegral r < mr
+      GAxis -> \(PixelRGB8 _ g _) -> fromIntegral g < mg
+      BAxis -> \(PixelRGB8 _ _ b) -> fromIntegral b < mb
+
+rgbIntPack :: PixelRGB8 -> PackedRGB
+rgbIntPack (PixelRGB8 r g b) =
+    wr `unsafeShiftL` (2 * 8) .|. wg `unsafeShiftL` 8 .|. wb
+  where wr = fromIntegral r
+        wg = fromIntegral g
+        wb = fromIntegral b
+
+rgbIntUnpack :: PackedRGB -> PixelRGB8
+rgbIntUnpack v = PixelRGB8 r g b
+  where
+    r = fromIntegral $ v `unsafeShiftR` (2 * 8)
+    g = fromIntegral $ v `unsafeShiftR` 8
+    b = fromIntegral v
+
+initCluster :: Image PixelRGB8 -> Cluster
+initCluster img = mkCluster $ VU.generate ((w * h) `div` subSampling) packer
+  where samplingFactor = 3
+        subSampling = samplingFactor * samplingFactor
+        compCount = componentCount (undefined :: PixelRGB8)
+        w = imageWidth img
+        h = imageHeight img
+        rawData = imageData img
+        packer ix =
+            rgbIntPack . unsafePixelAt rawData $ ix * subSampling * compCount
+
+-- Take the cluster with the largest value = (volume * population) and remove it
+-- from the priority queue. Then subdivide it about its largest axis and put the
+-- two new clusters on the queue.
+split :: Set Cluster -> Set Cluster
+split cs = Set.insert c1 . Set.insert c2  $ cs'
+  where
+    (c, cs') = Set.deleteFindMax cs
+    (c1, c2) = subdivide c
+
+-- Keep splitting the initial cluster until there are 256 clusters, then return
+-- a priority queue containing all 256.
+clusters :: Int -> Image PixelRGB8 -> Set Cluster
+clusters maxCols img = clusters' (maxCols - 1)
+  where
+    clusters' :: Int -> Set Cluster
+    clusters' 0 = Set.singleton c
+    clusters' n = split (clusters' (n-1))
+    c = initCluster img
+
+-- Euclidean distance squared, between two pixels.
+dist2Px :: PixelRGB8 -> PixelRGB8 -> Int
+dist2Px (PixelRGB8 r1 g1 b1) (PixelRGB8 r2 g2 b2) = dr*dr + dg*dg + db*db
+  where
+    (dr, dg, db) =
+      ( fromIntegral r1 - fromIntegral r2
+      , fromIntegral g1 - fromIntegral g2
+      , fromIntegral b1 - fromIntegral b2 )
+
+nearestColorIdx :: PixelRGB8 -> Vector PixelRGB8 -> Pixel8
+nearestColorIdx p ps  = fromIntegral $ V.minIndex (V.map (`dist2Px` p) ps)
diff --git a/src/Codec/Picture/ConvGraph.hs b/src/Codec/Picture/ConvGraph.hs
--- a/src/Codec/Picture/ConvGraph.hs
+++ b/src/Codec/Picture/ConvGraph.hs
@@ -1,6 +1,6 @@
 -- $graph
 --
--- The following graph describe the differents way to convert between pixel types,
+-- The following graph describe the different way to convert between pixel types,
 --
 -- * Nodes describe pixel type
 --
diff --git a/src/Codec/Picture/Gif.hs b/src/Codec/Picture/Gif.hs
--- a/src/Codec/Picture/Gif.hs
+++ b/src/Codec/Picture/Gif.hs
@@ -1,1006 +1,1006 @@
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE CPP #-}
--- | Module implementing GIF decoding.
-module Codec.Picture.Gif ( -- * Reading
-                           decodeGif
-                         , decodeGifWithMetadata
-                         , decodeGifWithPaletteAndMetadata
-                         , decodeGifImages
-                         , getDelaysGifImages
-
-                           -- * Writing
-                         , GifDelay
-                         , GifDisposalMethod( .. )
-                         , GifEncode( .. )
-                         , GifFrame( .. )
-                         , GifLooping( .. )
-                         , encodeGifImage
-                         , encodeGifImageWithPalette
-                         , encodeGifImages
-                         , encodeComplexGifImage
-
-                         , writeGifImage
-                         , writeGifImageWithPalette
-                         , writeGifImages
-                         , writeComplexGifImage
-                         , greyPalette
-                         ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure, (<*>), (<$>) )
-#endif
-
-import Control.Arrow( first )
-import Control.Monad( replicateM, replicateM_, unless, when )
-import Control.Monad.ST( runST )
-import Control.Monad.Trans.Class( lift )
-
-import Data.Bits( (.&.), (.|.)
-                , unsafeShiftR
-                , unsafeShiftL
-                , testBit, setBit )
-import Data.Word( Word8, Word16 )
-
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Char8 as BC
-import qualified Data.ByteString.Lazy as L
-import qualified Data.Vector.Storable as V
-import qualified Data.Vector.Storable.Mutable as M
-
-import Data.Binary( Binary(..), encode )
-import Data.Binary.Get( Get
-                      , getWord8
-                      , getWord16le
-                      , getByteString
-                      , bytesRead
-                      , skip
-                      )
-
-import Data.Binary.Put( Put
-                      , putWord8
-                      , putWord16le
-                      , putByteString
-                      )
-
-import Codec.Picture.InternalHelper
-import Codec.Picture.Types
-import Codec.Picture.Metadata( Metadatas
-                             , SourceFormat( SourceGif )
-                             , basicMetadata )
-import Codec.Picture.Gif.Internal.LZW
-import Codec.Picture.Gif.Internal.LZWEncoding
-import Codec.Picture.BitWriter
-
--- | Delay to wait before showing the next Gif image.
--- The delay is expressed in 100th of seconds.
-type GifDelay = Int
-
--- | Help to control the behaviour of GIF animation looping.
-data GifLooping =
-      -- | The animation will stop once the end is reached
-      LoopingNever
-      -- | The animation will restart once the end is reached
-    | LoopingForever
-      -- | The animation will repeat n times before stoping
-    | LoopingRepeat Word16
-
-
--- | GIF image definition for encoding
-data GifEncode = GifEncode
-  { -- | Screen width
-    geWidth      :: Int
-  , -- | Screen height
-    geHeight     :: Int
-  , -- | Global palette, optional
-    gePalette    :: Maybe Palette
-  , -- | Background color index, optional. If given, a global palette is also required
-    geBackground :: Maybe Int
-  , -- | Looping behaviour
-    geLooping    :: GifLooping
-  , -- | Image frames
-    geFrames     :: [GifFrame]
-  }
-
--- | An individual image frame in a GIF image
-data GifFrame = GifFrame
-  { -- | Image X offset in GIF canvas
-    gfXOffset     :: Int
-  , -- | Image Y offset in GIF canvas
-    gfYOffset     :: Int
-  , -- | Image local palette, optional if a global palette is given
-    gfPalette     :: Maybe Palette
-  , -- | Transparent color index, optional
-    gfTransparent :: Maybe Int
-  , -- | Frame transition delay, in 1/100ths of a second
-    gfDelay       :: GifDelay
-  , -- | Frame disposal method
-    gfDisposal    :: GifDisposalMethod
-  , -- | Image pixels
-    gfPixels      :: Image Pixel8
-  }
-
-
-{-
-   <GIF Data Stream> ::=     Header <Logical Screen> <Data>* Trailer
-
-   <Logical Screen> ::=      Logical Screen Descriptor [Global Color Table]
-
-   <Data> ::=                <Graphic Block>  |
-                             <Special-Purpose Block>
-
-   <Graphic Block> ::=       [Graphic Control Extension] <Graphic-Rendering Block>
-
-   <Graphic-Rendering Block> ::=  <Table-Based Image>  |
-                                  Plain Text Extension
-
-   <Table-Based Image> ::=   Image Descriptor [Local Color Table] Image Data
-
-   <Special-Purpose Block> ::=    Application Extension  |
-                                  Comment Extension
- -}
-
---------------------------------------------------
-----            GifVersion
---------------------------------------------------
-data GifVersion = GIF87a | GIF89a
-
-gif87aSignature, gif89aSignature :: B.ByteString
-gif87aSignature = B.pack $ map (fromIntegral . fromEnum) "GIF87a"
-gif89aSignature = B.pack $ map (fromIntegral . fromEnum) "GIF89a"
-
-instance Binary GifVersion where
-    put GIF87a = putByteString gif87aSignature
-    put GIF89a = putByteString gif89aSignature
-
-    get = do
-        sig <- getByteString (B.length gif87aSignature)
-        case (sig == gif87aSignature, sig == gif89aSignature) of
-            (True, _)  -> pure GIF87a
-            (_ , True) -> pure GIF89a
-            _          -> fail $ "Invalid Gif signature : " ++ (toEnum . fromEnum <$> B.unpack sig)
-
-
---------------------------------------------------
-----         LogicalScreenDescriptor
---------------------------------------------------
--- | Section 18 of spec-gif89a
-data LogicalScreenDescriptor = LogicalScreenDescriptor
-  { -- | Stored on 16 bits
-    screenWidth           :: !Word16
-    -- | Stored on 16 bits
-  , screenHeight          :: !Word16
-    -- | Stored on 8 bits
-  , backgroundIndex       :: !Word8
-
-  -- | Stored on 1 bit
-  , hasGlobalMap          :: !Bool
-  -- | Stored on 3 bits
-  , colorResolution       :: !Word8
-  -- | Stored on 1 bit
-  , isColorTableSorted    :: !Bool
-  -- | Stored on 3 bits
-  , colorTableSize        :: !Word8
-  }
-
-instance Binary LogicalScreenDescriptor where
-    put v = do
-      putWord16le $ screenWidth v
-      putWord16le $ screenHeight v
-      let globalMapField
-            | hasGlobalMap v = 0x80
-            | otherwise = 0
-
-          colorTableSortedField
-            | isColorTableSorted v = 0x08
-            | otherwise = 0
-
-          tableSizeField = (colorTableSize v - 1) .&. 7
-
-          colorResolutionField =
-            ((colorResolution v - 1) .&. 7) `unsafeShiftL` 4
-
-          packedField = globalMapField
-                     .|. colorTableSortedField
-                     .|. tableSizeField
-                     .|. colorResolutionField
-
-      putWord8 packedField
-      putWord8 0 -- aspect ratio
-      putWord8 $ backgroundIndex v
-
-    get = do
-        w <- getWord16le
-        h <- getWord16le
-        packedField  <- getWord8
-        backgroundColorIndex  <- getWord8
-        _aspectRatio  <- getWord8
-        return LogicalScreenDescriptor
-            { screenWidth           = w
-            , screenHeight          = h
-            , hasGlobalMap          = packedField `testBit` 7
-            , colorResolution       = (packedField `unsafeShiftR` 4) .&. 0x7 + 1
-            , isColorTableSorted    = packedField `testBit` 3
-            , colorTableSize        = (packedField .&. 0x7) + 1
-            , backgroundIndex       = backgroundColorIndex
-            }
-
-
---------------------------------------------------
-----            ImageDescriptor
---------------------------------------------------
--- | Section 20 of spec-gif89a
-data ImageDescriptor = ImageDescriptor
-  { gDescPixelsFromLeft         :: !Word16
-  , gDescPixelsFromTop          :: !Word16
-  , gDescImageWidth             :: !Word16
-  , gDescImageHeight            :: !Word16
-  , gDescHasLocalMap            :: !Bool
-  , gDescIsInterlaced           :: !Bool
-  , gDescIsImgDescriptorSorted  :: !Bool
-  , gDescLocalColorTableSize    :: !Word8
-  }
-
-imageSeparator, extensionIntroducer, gifTrailer :: Word8
-imageSeparator      = 0x2C
-extensionIntroducer = 0x21
-gifTrailer          = 0x3B
-
-graphicControlLabel, commentLabel, plainTextLabel, applicationLabel :: Word8
-plainTextLabel = 0x01
-graphicControlLabel = 0xF9
-commentLabel = 0xFE
-applicationLabel    = 0xFF
-
-
-parseDataBlocks :: Get B.ByteString
-parseDataBlocks = B.concat <$> (getWord8 >>= aux)
- where aux    0 = pure []
-       aux size = (:) <$> getByteString (fromIntegral size) <*> (getWord8 >>= aux)
-
-putDataBlocks :: B.ByteString -> Put
-putDataBlocks wholeString = putSlices wholeString >> putWord8 0
-  where putSlices str | B.length str == 0 = pure ()
-                      | B.length str > 0xFF =
-            let (before, after) = B.splitAt 0xFF str in
-            putWord8 0xFF >> putByteString before >> putSlices after
-        putSlices str =
-            putWord8 (fromIntegral $ B.length str) >> putByteString str
-
-data GifDisposalMethod
-    = DisposalAny
-    | DisposalDoNot
-    | DisposalRestoreBackground
-    | DisposalRestorePrevious
-    | DisposalUnknown Word8
-
-disposalMethodOfCode :: Word8 -> GifDisposalMethod
-disposalMethodOfCode v = case v of
-    0 -> DisposalAny
-    1 -> DisposalDoNot
-    2 -> DisposalRestoreBackground
-    3 -> DisposalRestorePrevious
-    n -> DisposalUnknown n
-
-codeOfDisposalMethod :: GifDisposalMethod -> Word8
-codeOfDisposalMethod v = case v of
-    DisposalAny -> 0
-    DisposalDoNot -> 1
-    DisposalRestoreBackground -> 2
-    DisposalRestorePrevious -> 3
-    DisposalUnknown n -> n
-
-data GraphicControlExtension = GraphicControlExtension
-    { gceDisposalMethod        :: !GifDisposalMethod -- ^ Stored on 3 bits
-    , gceUserInputFlag         :: !Bool
-    , gceTransparentFlag       :: !Bool
-    , gceDelay                 :: !Word16
-    , gceTransparentColorIndex :: !Word8
-    }
-
-instance Binary GraphicControlExtension where
-    put v = do
-        putWord8 extensionIntroducer
-        putWord8 graphicControlLabel
-        putWord8 0x4  -- size
-        let disposalCode = codeOfDisposalMethod $ gceDisposalMethod v
-            disposalField =
-                (disposalCode .&. 0x7) `unsafeShiftL` 2
-
-            userInputField
-                | gceUserInputFlag v = 0 `setBit` 1
-                | otherwise = 0
-
-            transparentField
-                | gceTransparentFlag v = 0 `setBit` 0
-                | otherwise = 0
-
-            packedFields =  disposalField
-                        .|. userInputField
-                        .|. transparentField
-
-        putWord8 packedFields
-        putWord16le $ gceDelay v
-        putWord8 $ gceTransparentColorIndex v
-        putWord8 0 -- blockTerminator
-
-    get = do
-        -- due to missing lookahead
-        {-_extensionLabel  <- getWord8-}
-        _size            <- getWord8
-        packedFields     <- getWord8
-        delay            <- getWord16le
-        idx              <- getWord8
-        _blockTerminator <- getWord8
-        return GraphicControlExtension
-            { gceDisposalMethod        = 
-                disposalMethodOfCode $
-                    (packedFields `unsafeShiftR` 2) .&. 0x07
-            , gceUserInputFlag         = packedFields `testBit` 1
-            , gceTransparentFlag       = packedFields `testBit` 0
-            , gceDelay                 = delay
-            , gceTransparentColorIndex = idx
-            }
-
-data GifImage = GifImage
-    { imgDescriptor   :: !ImageDescriptor
-    , imgLocalPalette :: !(Maybe Palette)
-    , imgLzwRootSize  :: !Word8
-    , imgData         :: B.ByteString
-    }
-
-instance Binary GifImage where
-    put img = do
-        let descriptor = imgDescriptor img
-        put descriptor
-        case ( imgLocalPalette img
-             , gDescHasLocalMap $ imgDescriptor img) of
-          (Nothing, _) -> return ()
-          (Just _, False) -> return ()
-          (Just p, True) ->
-              putPalette (fromIntegral $ gDescLocalColorTableSize descriptor) p
-        putWord8 $ imgLzwRootSize img
-        putDataBlocks $ imgData img
-
-    get = do
-        desc <- get
-        let hasLocalColorTable = gDescHasLocalMap desc
-        palette <- if hasLocalColorTable
-           then Just <$> getPalette (gDescLocalColorTableSize desc)
-           else pure Nothing
-
-        GifImage desc palette <$> getWord8 <*> parseDataBlocks
-
-data Block = BlockImage GifImage
-           | BlockGraphicControl GraphicControlExtension
-
-skipSubDataBlocks :: Get ()
-skipSubDataBlocks = do
-  s <- fromIntegral <$> getWord8
-  unless (s == 0) $
-    skip s >> skipSubDataBlocks
-
-parseGifBlocks :: Get [Block]
-parseGifBlocks = getWord8 >>= blockParse
-  where
-    blockParse v
-      | v == gifTrailer = pure []
-      | v == imageSeparator = (:) <$> (BlockImage <$> get) <*> parseGifBlocks
-      | v == extensionIntroducer = getWord8 >>= extensionParse
-
-    blockParse v = do
-      readPosition <- bytesRead
-      fail ("Unrecognized gif block " ++ show v ++ " @" ++ show readPosition)
-
-    extensionParse code
-     | code == graphicControlLabel =
-        (:) <$> (BlockGraphicControl <$> get) <*> parseGifBlocks
-     | code == commentLabel = skipSubDataBlocks >> parseGifBlocks
-     | code `elem` [plainTextLabel, applicationLabel] =
-        fromIntegral <$> getWord8 >>= skip >> skipSubDataBlocks >> parseGifBlocks
-     | otherwise = parseDataBlocks >> parseGifBlocks
-
-
-instance Binary ImageDescriptor where
-    put v = do
-        putWord8 imageSeparator
-        putWord16le $ gDescPixelsFromLeft v
-        putWord16le $ gDescPixelsFromTop v
-        putWord16le $ gDescImageWidth v
-        putWord16le $ gDescImageHeight v
-        let localMapField
-                | gDescHasLocalMap v = 0 `setBit` 7
-                | otherwise = 0
-
-            isInterlacedField
-                | gDescIsInterlaced v = 0 `setBit` 6
-                | otherwise = 0
-
-            isImageDescriptorSorted
-                | gDescIsImgDescriptorSorted v = 0 `setBit` 5
-                | otherwise = 0
-
-            localSize = gDescLocalColorTableSize v
-            tableSizeField
-                | localSize > 0 = (localSize - 1) .&. 0x7
-                | otherwise = 0
-
-            packedFields = localMapField
-                        .|. isInterlacedField
-                        .|. isImageDescriptorSorted
-                        .|. tableSizeField
-        putWord8 packedFields
-
-    get = do
-        -- due to missing lookahead
-        {-_imageSeparator <- getWord8-}
-        imgLeftPos <- getWord16le
-        imgTopPos  <- getWord16le
-        imgWidth   <- getWord16le
-        imgHeight  <- getWord16le
-        packedFields <- getWord8
-        return ImageDescriptor
-            { gDescPixelsFromLeft = imgLeftPos
-            , gDescPixelsFromTop  = imgTopPos
-            , gDescImageWidth     = imgWidth
-            , gDescImageHeight    = imgHeight
-            , gDescHasLocalMap    = packedFields `testBit` 7
-            , gDescIsInterlaced     = packedFields `testBit` 6
-            , gDescIsImgDescriptorSorted = packedFields `testBit` 5
-            , gDescLocalColorTableSize = (packedFields .&. 0x7) + 1
-            }
-
-
---------------------------------------------------
-----            Palette
---------------------------------------------------
-getPalette :: Word8 -> Get Palette
-getPalette bitDepth = 
-    Image size 1 . V.fromList <$> replicateM (size * 3) get
-  where size = 2 ^ (fromIntegral bitDepth :: Int)
-
-putPalette :: Int -> Palette -> Put
-putPalette size pal = do
-    V.mapM_ putWord8 (imageData pal)
-    replicateM_ missingColorComponent (putWord8 0)
-  where elemCount = 2 ^ size
-        missingColorComponent = (elemCount - imageWidth pal) * 3
-
---------------------------------------------------
-----            GifImage
---------------------------------------------------
-data GifHeader = GifHeader
-  { gifVersion          :: GifVersion
-  , gifScreenDescriptor :: LogicalScreenDescriptor
-  , gifGlobalMap        :: Maybe Palette
-  }
-
-instance Binary GifHeader where
-    put v = do
-      put $ gifVersion v
-      let descr = gifScreenDescriptor v
-      put descr
-      case gifGlobalMap v of
-        Just palette -> putPalette (fromIntegral $ colorTableSize descr) palette
-        Nothing      -> return ()
-
-    get = do
-        version    <- get
-        screenDesc <- get
-        
-        palette <- 
-          if hasGlobalMap screenDesc then
-            return <$> getPalette (colorTableSize screenDesc)
-          else
-            return Nothing
-
-        return GifHeader
-            { gifVersion = version
-            , gifScreenDescriptor = screenDesc
-            , gifGlobalMap = palette
-            }
-
-data GifFile = GifFile
-    { gifHeader      :: !GifHeader
-    , gifImages      :: [(Maybe GraphicControlExtension, GifImage)]
-    , gifLoopingBehaviour :: GifLooping
-    }
-
-putLooping :: GifLooping -> Put
-putLooping LoopingNever = return ()
-putLooping LoopingForever = putLooping $ LoopingRepeat 0
-putLooping (LoopingRepeat count) = do
-    putWord8 extensionIntroducer
-    putWord8 applicationLabel
-    putWord8 11 -- the size
-    putByteString $ BC.pack "NETSCAPE2.0"
-    putWord8 3 -- size of sub block
-    putWord8 1
-    putWord16le count
-    putWord8 0
-
-associateDescr :: [Block] -> [(Maybe GraphicControlExtension, GifImage)]
-associateDescr [] = []
-associateDescr [BlockGraphicControl _] = []
-associateDescr (BlockGraphicControl _ : rest@(BlockGraphicControl _ : _)) =
-    associateDescr rest
-associateDescr (BlockImage img:xs) = (Nothing, img) : associateDescr xs
-associateDescr (BlockGraphicControl ctrl : BlockImage img : xs) =
-    (Just ctrl, img) : associateDescr xs
-
-instance Binary GifFile where
-    put v = do
-        put $ gifHeader v
-        let putter (Nothing, i) = put i
-            putter (Just a, i) = put a >> put i
-        putLooping $ gifLoopingBehaviour v
-        mapM_ putter $ gifImages v
-        put gifTrailer
-
-    get = do
-        hdr <- get
-        blocks <- parseGifBlocks
-        return GifFile { gifHeader = hdr
-                       , gifImages = associateDescr blocks
-                       , gifLoopingBehaviour = LoopingNever
-                       }
-
-substituteColors :: Palette -> Image Pixel8 -> Image PixelRGB8
-substituteColors palette = pixelMap swaper
-  where swaper n = pixelAt palette (fromIntegral n) 0
-
-substituteColorsWithTransparency :: Int -> Image PixelRGBA8 -> Image Pixel8 -> Image PixelRGBA8
-substituteColorsWithTransparency transparent palette = pixelMap swaper where
-  swaper n | ix == transparent = PixelRGBA8 0 0 0 0
-           | otherwise = promotePixel $ pixelAt palette ix 0
-    where ix = fromIntegral n
-
-
-decodeImage :: GifImage -> Image Pixel8
-decodeImage img = runST $ runBoolReader $ do
-    outputVector <- lift . M.new $ width * height
-    decodeLzw (imgData img) 12 lzwRoot outputVector
-    frozenData <- lift $ V.unsafeFreeze outputVector
-    return . deinterlaceGif $ Image
-      { imageWidth = width
-      , imageHeight = height
-      , imageData = frozenData
-      }
-  where lzwRoot = fromIntegral $ imgLzwRootSize img
-        width = fromIntegral $ gDescImageWidth descriptor
-        height = fromIntegral $ gDescImageHeight descriptor
-        isInterlaced = gDescIsInterlaced descriptor
-        descriptor = imgDescriptor img
-
-        deinterlaceGif | not isInterlaced = id
-                       | otherwise = deinterlaceGifImage
-
-deinterlaceGifImage :: Image Pixel8 -> Image Pixel8
-deinterlaceGifImage img@(Image { imageWidth = w, imageHeight = h }) = generateImage generator w h
-   where lineIndices = gifInterlacingIndices h
-         generator x y = pixelAt img x y'
-            where y' = lineIndices V.! y
-
-gifInterlacingIndices :: Int -> V.Vector Int
-gifInterlacingIndices height = V.accum (\_ v -> v) (V.replicate height 0) indices
-    where indices = flip zip [0..] $
-                concat [ [0,     8 .. height - 1]
-                       , [4, 4 + 8 .. height - 1]
-                       , [2, 2 + 4 .. height - 1]
-                       , [1, 1 + 2 .. height - 1]
-                       ]
-
-paletteOf :: (ColorConvertible PixelRGB8 px)
-          => Image px -> GifImage -> Image px
-paletteOf global GifImage { imgLocalPalette = Nothing } = global
-paletteOf      _ GifImage { imgLocalPalette = Just p  } = promoteImage p
-
-getFrameDelays :: GifFile -> [GifDelay]
-getFrameDelays GifFile { gifImages = [] } = []
-getFrameDelays GifFile { gifImages = imgs } = map extractDelay imgs
-    where extractDelay (ext, _) =
-            case ext of
-                Nothing -> 0
-                Just e -> fromIntegral $ gceDelay e
-
-transparentColorOf :: Maybe GraphicControlExtension -> Int
-transparentColorOf Nothing = 300
-transparentColorOf (Just ext)
-  | gceTransparentFlag ext = fromIntegral $ gceTransparentColorIndex ext
-  | otherwise = 300
-
-hasTransparency :: Maybe GraphicControlExtension -> Bool
-hasTransparency Nothing = False
-hasTransparency (Just control) = gceTransparentFlag control
-
-decodeAllGifImages :: GifFile -> [PalettedImage]
-decodeAllGifImages GifFile { gifImages = [] } = []
-decodeAllGifImages GifFile { gifHeader = GifHeader { gifGlobalMap = palette
-                                                   , gifScreenDescriptor = wholeDescriptor }
-                           , gifImages = (firstControl, firstImage) : rest }
-  | not (hasTransparency firstControl) =
-      let backImage =
-              generateImage (\_ _ -> backgroundColor) globalWidth globalHeight
-          thisPalette = paletteOf globalPalette firstImage
-          baseImage = decodeImage firstImage
-          initState =
-            (thisPalette, firstControl, substituteColors thisPalette baseImage)
-          scanner = gifAnimationApplyer (globalWidth, globalHeight) thisPalette backImage
-          palette' = Palette'
-            { _paletteSize = imageWidth thisPalette
-            , _paletteData = imageData thisPalette
-            }
-      in
-      PalettedRGB8 baseImage palette' :
-        [TrueColorImage $ ImageRGB8 img | (_, _, img) <- tail $ scanl scanner initState rest]
-
-  | otherwise =
-      let backImage :: Image PixelRGBA8
-          backImage =
-            generateImage (\_ _ -> transparentBackground) globalWidth globalHeight
-
-          thisPalette :: Image PixelRGBA8
-          thisPalette = paletteOf (promoteImage globalPalette) firstImage
-
-          transparentCode = transparentColorOf firstControl
-          decoded = 
-            substituteColorsWithTransparency transparentCode thisPalette $
-                decodeImage firstImage
-
-          initState = (thisPalette, firstControl, decoded)
-          scanner =
-            gifAnimationApplyer (globalWidth, globalHeight) thisPalette backImage in
-      [TrueColorImage $ ImageRGBA8 img | (_, _, img) <- scanl scanner initState rest]
-
-    where
-      globalWidth = fromIntegral $ screenWidth wholeDescriptor
-      globalHeight = fromIntegral $ screenHeight wholeDescriptor
-      globalPalette = maybe greyPalette id palette
-
-      transparentBackground = PixelRGBA8 r g b 0
-          where PixelRGB8 r g b = backgroundColor
-
-      backgroundColor
-        | hasGlobalMap wholeDescriptor =
-            pixelAt globalPalette (fromIntegral $ backgroundIndex wholeDescriptor) 0
-        | otherwise = PixelRGB8 0 0 0
-
-gifAnimationApplyer :: forall px.  (ColorConvertible PixelRGB8 px)
-                    => (Int, Int) -> Image px -> Image px
-                    -> (Image px, Maybe GraphicControlExtension, Image px)
-                    -> (Maybe GraphicControlExtension, GifImage)
-                    -> (Image px, Maybe GraphicControlExtension, Image px)
-gifAnimationApplyer (globalWidth, globalHeight) globalPalette backgroundImage
-          (_, prevControl, img1)
-          (controlExt, img2@(GifImage { imgDescriptor = descriptor })) =
-            (thisPalette, controlExt, thisImage)
-  where
-    thisPalette :: Image px
-    thisPalette = paletteOf globalPalette img2
-
-    thisImage = generateImage pixeler globalWidth globalHeight
-    localWidth = fromIntegral $ gDescImageWidth descriptor
-    localHeight = fromIntegral $ gDescImageHeight descriptor
-
-    left = fromIntegral $ gDescPixelsFromLeft descriptor
-    top = fromIntegral $ gDescPixelsFromTop descriptor
-
-    isPixelInLocalImage x y =
-        x >= left && x < left + localWidth && y >= top && y < top + localHeight
-
-    decoded :: Image Pixel8
-    decoded = decodeImage img2
-
-    transparent :: Int
-    transparent = case controlExt of
-        Nothing  -> 300
-        Just ext -> if gceTransparentFlag ext
-            then fromIntegral $ gceTransparentColorIndex ext
-            else 300
-
-    oldImage = case gceDisposalMethod <$> prevControl of
-        Nothing -> img1
-        Just DisposalAny -> img1
-        Just DisposalDoNot -> img1
-        Just DisposalRestoreBackground -> backgroundImage
-        Just DisposalRestorePrevious -> img1
-        Just (DisposalUnknown _) -> img1
-
-    pixeler x y
-      | isPixelInLocalImage x y && code /= transparent = val where
-          code = fromIntegral $ pixelAt decoded (x - left) (y - top)
-          val = pixelAt thisPalette (fromIntegral code) 0
-    pixeler x y = pixelAt oldImage x y
-
-decodeFirstGifImage :: GifFile -> Either String (PalettedImage, Metadatas)
-decodeFirstGifImage img@GifFile { gifImages = (firstImage:_) } =
-    case decodeAllGifImages img { gifImages = [firstImage] } of
-      [] -> Left "No image after decoding"
-      (i:_) -> Right (i, basicMetadata SourceGif (screenWidth hdr) (screenHeight hdr))
-  where hdr = gifScreenDescriptor $ gifHeader img
-decodeFirstGifImage _ = Left "No image in gif file"
-
--- | Transform a raw gif image to an image, without modifying the pixels. This
--- function can output the following images:
---
---  * 'ImageRGB8'
---
---  * 'ImageRGBA8'
---
-decodeGif :: B.ByteString -> Either String DynamicImage
-decodeGif img = decode img >>= (fmap (palettedToTrueColor . fst) . decodeFirstGifImage)
-
--- | Transform a raw gif image to an image, without modifying the pixels.  This
--- function can output the following images:
---
---  * 'ImageRGB8'
---
---  * 'ImageRGBA8'
---
--- Metadatas include Width & Height information.
---
-decodeGifWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
-decodeGifWithMetadata img = first palettedToTrueColor <$> decodeGifWithPaletteAndMetadata img
-
--- | Return the gif image with metadata and palette.
--- The palette is only returned for the first image of an
--- animation and has no transparency.
-decodeGifWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
-decodeGifWithPaletteAndMetadata img = decode img >>= decodeFirstGifImage
-
--- | Transform a raw gif to a list of images, representing
--- all the images of an animation.
-decodeGifImages :: B.ByteString -> Either String [DynamicImage]
-decodeGifImages img = fmap palettedToTrueColor . decodeAllGifImages <$> decode img
-
--- | Extract a list of frame delays from a raw gif.
-getDelaysGifImages :: B.ByteString -> Either String [GifDelay]
-getDelaysGifImages img = getFrameDelays <$> decode img
-
--- | Default palette to produce greyscale images.
-greyPalette :: Palette
-greyPalette = generateImage toGrey 256 1
-  where toGrey x _ = PixelRGB8 ix ix ix
-           where ix = fromIntegral x
-
-checkImageSizes :: GifEncode -> Either String ()
-checkImageSizes GifEncode { geWidth = width, geHeight = height, geFrames = frames }
-  | not $ isInBounds width && isInBounds height = Left "Invalid screen bounds"
-  | not $ null outOfBounds = Left $ "GIF frames with invalid bounds: " ++ show (map snd outOfBounds)
-  | otherwise = Right ()
-  where isInBounds dim = dim > 0 && dim <= 0xffff
-        outOfBounds = filter (not . isFrameInBounds . fst) $ zip frames [0 :: Int ..]
-        isFrameInBounds GifFrame { gfPixels = img } = isInBounds (imageWidth img) && isInBounds (imageHeight img)
-
-checkImagesInBounds :: GifEncode -> Either String ()
-checkImagesInBounds GifEncode { geWidth = width, geHeight = height, geFrames = frames } =
-  if null outOfBounds
-  then Right ()
-  else Left $ "GIF frames out of screen bounds: " ++ show (map snd outOfBounds)
-  where outOfBounds = filter (not . isInBounds . fst) $ zip frames [0 :: Int ..]
-        isInBounds GifFrame { gfXOffset = xOff, gfYOffset = yOff, gfPixels = img } =
-          xOff >= 0 && yOff >= 0 &&
-          xOff + imageWidth img <= width && yOff + imageHeight img <= height
-
-checkPaletteValidity :: GifEncode -> Either String ()
-checkPaletteValidity spec
-  | not $ isPaletteValid $ gePalette spec = Left "Invalid global palette size"
-  | not $ null invalidPalettes = Left $ "Invalid palette size in GIF frames: " ++ show (map snd invalidPalettes)
-  | otherwise = Right ()
-  where invalidPalettes = filter (not . isPaletteValid . gfPalette . fst) $ zip (geFrames spec) [0 :: Int ..]
-        isPaletteValid Nothing  = True
-        isPaletteValid (Just p) = let w = imageWidth p
-                                      h = imageHeight p
-                                  in h == 1 && w > 0 && w <= 256
-
-checkIndexAbsentFromPalette :: GifEncode -> Either String ()
-checkIndexAbsentFromPalette GifEncode { gePalette = global, geFrames = frames } =
-  if null missingPalette
-  then Right ()
-  else Left $ "GIF image frames with color indexes missing from palette: " ++ show (map snd missingPalette)
-  where missingPalette = filter (not . checkFrame . fst) $ zip frames [0 :: Int ..]
-        checkFrame frame = V.all (checkIndexInPalette global (gfPalette frame) . fromIntegral) $
-                           imageData $ gfPixels frame
-
-checkBackground :: GifEncode -> Either String ()
-checkBackground GifEncode { geBackground = Nothing } = Right ()
-checkBackground GifEncode { gePalette = global, geBackground = Just background } =
-  if checkIndexInPalette global Nothing background
-  then Right ()
-  else Left "GIF background index absent from global palette"
-
-checkTransparencies :: GifEncode -> Either String ()
-checkTransparencies GifEncode { gePalette = global, geFrames = frames } =
-  if null missingTransparency
-  then Right ()
-  else Left $ "GIF transparent index absent from palettes for frames: " ++ show (map snd missingTransparency)
-  where missingTransparency = filter (not . transparencyOK . fst) $ zip frames [0 :: Int ..]
-        transparencyOK GifFrame { gfTransparent = Nothing } = True
-        transparencyOK GifFrame { gfPalette = local, gfTransparent = Just transparent } =
-          checkIndexInPalette global local transparent
-
-checkIndexInPalette :: Maybe Palette -> Maybe Palette -> Int -> Bool
-checkIndexInPalette Nothing       Nothing      _  = False
-checkIndexInPalette _             (Just local) ix = ix < imageWidth local
-checkIndexInPalette (Just global) _            ix = ix < imageWidth global
-
-checkGifImageSizes :: [(a, b, Image px)] -> Bool
-checkGifImageSizes [] = False
-checkGifImageSizes ((_, _, img) : rest) = all checkDimension rest
-   where width = imageWidth img
-         height = imageHeight img
-
-         checkDimension (_,_,Image { imageWidth = w, imageHeight = h }) =
-             w == width && h == height
-
-computeColorTableSize :: Palette -> Int
-computeColorTableSize Image { imageWidth = itemCount } = go 1
-  where go k | 2 ^ k >= itemCount = k
-             | otherwise = go $ k + 1
-
--- | Encode a complex gif to a bytestring.
---
--- * There must be at least one image.
---
--- * The screen and every frame dimensions must be between 1 and 65535.
---
--- * Every frame image must fit within the screen bounds.
---
--- * Every palette must have between one and 256 colors.
---
--- * There must be a global palette or every image must have a local palette.
---
--- * The background color index must be present in the global palette.
---
--- * Every frame's transparent color index, if set, must be present in the palette used by that frame.
---
--- * Every color index used in an image must be present in the palette used by that frame.
---
-encodeComplexGifImage :: GifEncode -> Either String L.ByteString
-encodeComplexGifImage spec = do
-  when (null $ geFrames spec) $ Left "No GIF frames"
-  checkImageSizes spec
-  checkImagesInBounds spec
-  checkPaletteValidity spec
-  checkBackground spec
-  checkTransparencies spec
-  checkIndexAbsentFromPalette spec
-
-  Right $ encode allFile
-  where
-    GifEncode { geWidth      = width
-              , geHeight     = height
-              , gePalette    = globalPalette
-              , geBackground = background
-              , geLooping    = looping
-              , geFrames     = frames
-              } = spec
-    allFile = GifFile
-      { gifHeader = GifHeader
-        { gifVersion          = version
-        , gifScreenDescriptor = logicalScreen
-        , gifGlobalMap        = globalPalette
-        }
-      , gifImages           = toSerialize
-      , gifLoopingBehaviour = looping
-      }
-
-    version = case frames of
-      [] -> GIF87a
-      [_] -> GIF87a
-      _:_:_ -> GIF89a
-
-    logicalScreen = LogicalScreenDescriptor
-      { screenWidth        = fromIntegral width
-      , screenHeight       = fromIntegral height
-      , backgroundIndex    = maybe 0 fromIntegral background
-      , hasGlobalMap       = maybe False (const True) globalPalette
-      , colorResolution    = 8
-      , isColorTableSorted = False
-      -- Imply a 8 bit global palette size if there's no explicit global palette.
-      , colorTableSize     = maybe 8 (fromIntegral . computeColorTableSize) globalPalette
-      }
-
-    toSerialize = [(controlExtension delay transparent disposal, GifImage
-                     { imgDescriptor = imageDescriptor left top localPalette img
-                     , imgLocalPalette = localPalette
-                     , imgLzwRootSize = fromIntegral lzwKeySize
-                     , imgData = B.concat . L.toChunks . lzwEncode lzwKeySize $ imageData img
-                     })
-                  | GifFrame { gfXOffset     = left
-                             , gfYOffset     = top
-                             , gfPalette     = localPalette
-                             , gfTransparent = transparent
-                             , gfDelay       = delay
-                             , gfDisposal    = disposal
-                             , gfPixels      = img } <- frames
-                  , let palette = case (globalPalette, localPalette) of
-                          (_, Just local)        -> local
-                          (Just global, Nothing) -> global
-                          (Nothing, Nothing)     -> error "No palette for image" -- redundant, we guard for this
-                    -- Some decoders (looking at you, GIMP) don't handle initial LZW key size of 1 correctly.
-                    -- We'll waste some space for the sake of interoperability
-                  , let lzwKeySize = max 2 $ computeColorTableSize palette
-                  ]
-
-    controlExtension 0     Nothing     DisposalAny = Nothing
-    controlExtension delay transparent disposal    = Just GraphicControlExtension
-      { gceDisposalMethod        = disposal
-      , gceUserInputFlag         = False
-      , gceTransparentFlag       = maybe False (const True) transparent
-      , gceDelay                 = fromIntegral delay
-      , gceTransparentColorIndex = maybe 0 fromIntegral transparent
-      }
-
-    imageDescriptor left top localPalette img = ImageDescriptor
-      { gDescPixelsFromLeft         = fromIntegral left
-      , gDescPixelsFromTop          = fromIntegral top
-      , gDescImageWidth             = fromIntegral $ imageWidth img
-      , gDescImageHeight            = fromIntegral $ imageHeight img
-      , gDescHasLocalMap            = maybe False (const True) localPalette
-      , gDescIsInterlaced           = False
-      , gDescIsImgDescriptorSorted  = False
-      , gDescLocalColorTableSize    = maybe 0 (fromIntegral . computeColorTableSize) localPalette
-      }
-
--- | Encode a gif animation to a bytestring.
---
--- * Every image must have the same size
---
--- * Every palette must have between one and 256 colors.
---
-encodeGifImages :: GifLooping -> [(Palette, GifDelay, Image Pixel8)]
-                -> Either String L.ByteString
-encodeGifImages _ [] = Left "No image in list"
-encodeGifImages _ imageList
-    | not $ checkGifImageSizes imageList = Left "Gif images have different size"
-encodeGifImages looping imageList@((firstPalette, _,firstImage):_) =
-  encodeComplexGifImage $ GifEncode (imageWidth firstImage) (imageHeight firstImage) (Just firstPalette) Nothing looping frames
-  where
-    frames = [ GifFrame 0 0 localPalette Nothing delay DisposalAny image
-             | (palette, delay, image) <- imageList
-             , let localPalette = if paletteEqual palette then Nothing else Just palette ]
-
-    paletteEqual p = imageData firstPalette == imageData p
-
--- | Encode a greyscale image to a bytestring.
-encodeGifImage :: Image Pixel8 -> L.ByteString
-encodeGifImage img = case encodeGifImages LoopingNever [(greyPalette, 0, img)] of
-    Left err -> error $ "Impossible:" ++ err
-    Right v -> v
-
--- | Encode an image with a given palette.
--- Can return errors if the palette is ill-formed.
---
--- * A palette must have between 1 and 256 colors
---
-encodeGifImageWithPalette :: Image Pixel8 -> Palette -> Either String L.ByteString
-encodeGifImageWithPalette img palette =
-    encodeGifImages LoopingNever [(palette, 0, img)]
-
--- | Write a greyscale in a gif file on the disk.
-writeGifImage :: FilePath -> Image Pixel8 -> IO ()
-writeGifImage file = L.writeFile file . encodeGifImage
-
--- | Write a list of images as a gif animation in a file.
---
--- * Every image must have the same size
---
--- * Every palette must have between one and 256 colors.
---
-writeGifImages :: FilePath -> GifLooping -> [(Palette, GifDelay, Image Pixel8)]
-               -> Either String (IO ())
-writeGifImages file looping lst = L.writeFile file <$> encodeGifImages looping lst
-
--- | Write a gif image with a palette to a file.
---
--- * A palette must have between 1 and 256 colors
---
-writeGifImageWithPalette :: FilePath -> Image Pixel8 -> Palette
-                         -> Either String (IO ())
-writeGifImageWithPalette file img palette =
-    L.writeFile file <$> encodeGifImageWithPalette img palette
-
-writeComplexGifImage :: FilePath -> GifEncode -> Either String (IO ())
-writeComplexGifImage file spec = L.writeFile file <$> encodeComplexGifImage spec
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE CPP #-}
+-- | Module implementing GIF decoding.
+module Codec.Picture.Gif ( -- * Reading
+                           decodeGif
+                         , decodeGifWithMetadata
+                         , decodeGifWithPaletteAndMetadata
+                         , decodeGifImages
+                         , getDelaysGifImages
+
+                           -- * Writing
+                         , GifDelay
+                         , GifDisposalMethod( .. )
+                         , GifEncode( .. )
+                         , GifFrame( .. )
+                         , GifLooping( .. )
+                         , encodeGifImage
+                         , encodeGifImageWithPalette
+                         , encodeGifImages
+                         , encodeComplexGifImage
+
+                         , writeGifImage
+                         , writeGifImageWithPalette
+                         , writeGifImages
+                         , writeComplexGifImage
+                         , greyPalette
+                         ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure, (<*>), (<$>) )
+#endif
+
+import Control.Arrow( first )
+import Control.Monad( replicateM, replicateM_, unless, when )
+import Control.Monad.ST( runST )
+import Control.Monad.Trans.Class( lift )
+
+import Data.Bits( (.&.), (.|.)
+                , unsafeShiftR
+                , unsafeShiftL
+                , testBit, setBit )
+import Data.Word( Word8, Word16 )
+
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as BC
+import qualified Data.ByteString.Lazy as L
+import qualified Data.Vector.Storable as V
+import qualified Data.Vector.Storable.Mutable as M
+
+import Data.Binary( Binary(..), encode )
+import Data.Binary.Get( Get
+                      , getWord8
+                      , getWord16le
+                      , getByteString
+                      , bytesRead
+                      , skip
+                      )
+
+import Data.Binary.Put( Put
+                      , putWord8
+                      , putWord16le
+                      , putByteString
+                      )
+
+import Codec.Picture.InternalHelper
+import Codec.Picture.Types
+import Codec.Picture.Metadata( Metadatas
+                             , SourceFormat( SourceGif )
+                             , basicMetadata )
+import Codec.Picture.Gif.Internal.LZW
+import Codec.Picture.Gif.Internal.LZWEncoding
+import Codec.Picture.BitWriter
+
+-- | Delay to wait before showing the next Gif image.
+-- The delay is expressed in 100th of seconds.
+type GifDelay = Int
+
+-- | Help to control the behaviour of GIF animation looping.
+data GifLooping =
+      -- | The animation will stop once the end is reached
+      LoopingNever
+      -- | The animation will restart once the end is reached
+    | LoopingForever
+      -- | The animation will repeat n times before stopping
+    | LoopingRepeat Word16
+
+
+-- | GIF image definition for encoding
+data GifEncode = GifEncode
+  { -- | Screen width
+    geWidth      :: Int
+  , -- | Screen height
+    geHeight     :: Int
+  , -- | Global palette, optional
+    gePalette    :: Maybe Palette
+  , -- | Background color index, optional. If given, a global palette is also required
+    geBackground :: Maybe Int
+  , -- | Looping behaviour
+    geLooping    :: GifLooping
+  , -- | Image frames
+    geFrames     :: [GifFrame]
+  }
+
+-- | An individual image frame in a GIF image
+data GifFrame = GifFrame
+  { -- | Image X offset in GIF canvas
+    gfXOffset     :: Int
+  , -- | Image Y offset in GIF canvas
+    gfYOffset     :: Int
+  , -- | Image local palette, optional if a global palette is given
+    gfPalette     :: Maybe Palette
+  , -- | Transparent color index, optional
+    gfTransparent :: Maybe Int
+  , -- | Frame transition delay, in 1/100ths of a second
+    gfDelay       :: GifDelay
+  , -- | Frame disposal method
+    gfDisposal    :: GifDisposalMethod
+  , -- | Image pixels
+    gfPixels      :: Image Pixel8
+  }
+
+
+{-
+   <GIF Data Stream> ::=     Header <Logical Screen> <Data>* Trailer
+
+   <Logical Screen> ::=      Logical Screen Descriptor [Global Color Table]
+
+   <Data> ::=                <Graphic Block>  |
+                             <Special-Purpose Block>
+
+   <Graphic Block> ::=       [Graphic Control Extension] <Graphic-Rendering Block>
+
+   <Graphic-Rendering Block> ::=  <Table-Based Image>  |
+                                  Plain Text Extension
+
+   <Table-Based Image> ::=   Image Descriptor [Local Color Table] Image Data
+
+   <Special-Purpose Block> ::=    Application Extension  |
+                                  Comment Extension
+ -}
+
+--------------------------------------------------
+----            GifVersion
+--------------------------------------------------
+data GifVersion = GIF87a | GIF89a
+
+gif87aSignature, gif89aSignature :: B.ByteString
+gif87aSignature = B.pack $ map (fromIntegral . fromEnum) "GIF87a"
+gif89aSignature = B.pack $ map (fromIntegral . fromEnum) "GIF89a"
+
+instance Binary GifVersion where
+    put GIF87a = putByteString gif87aSignature
+    put GIF89a = putByteString gif89aSignature
+
+    get = do
+        sig <- getByteString (B.length gif87aSignature)
+        case (sig == gif87aSignature, sig == gif89aSignature) of
+            (True, _)  -> pure GIF87a
+            (_ , True) -> pure GIF89a
+            _          -> fail $ "Invalid Gif signature : " ++ (toEnum . fromEnum <$> B.unpack sig)
+
+
+--------------------------------------------------
+----         LogicalScreenDescriptor
+--------------------------------------------------
+-- | Section 18 of spec-gif89a
+data LogicalScreenDescriptor = LogicalScreenDescriptor
+  { -- | Stored on 16 bits
+    screenWidth           :: !Word16
+    -- | Stored on 16 bits
+  , screenHeight          :: !Word16
+    -- | Stored on 8 bits
+  , backgroundIndex       :: !Word8
+
+  -- | Stored on 1 bit
+  , hasGlobalMap          :: !Bool
+  -- | Stored on 3 bits
+  , colorResolution       :: !Word8
+  -- | Stored on 1 bit
+  , isColorTableSorted    :: !Bool
+  -- | Stored on 3 bits
+  , colorTableSize        :: !Word8
+  }
+
+instance Binary LogicalScreenDescriptor where
+    put v = do
+      putWord16le $ screenWidth v
+      putWord16le $ screenHeight v
+      let globalMapField
+            | hasGlobalMap v = 0x80
+            | otherwise = 0
+
+          colorTableSortedField
+            | isColorTableSorted v = 0x08
+            | otherwise = 0
+
+          tableSizeField = (colorTableSize v - 1) .&. 7
+
+          colorResolutionField =
+            ((colorResolution v - 1) .&. 7) `unsafeShiftL` 4
+
+          packedField = globalMapField
+                     .|. colorTableSortedField
+                     .|. tableSizeField
+                     .|. colorResolutionField
+
+      putWord8 packedField
+      putWord8 0 -- aspect ratio
+      putWord8 $ backgroundIndex v
+
+    get = do
+        w <- getWord16le
+        h <- getWord16le
+        packedField  <- getWord8
+        backgroundColorIndex  <- getWord8
+        _aspectRatio  <- getWord8
+        return LogicalScreenDescriptor
+            { screenWidth           = w
+            , screenHeight          = h
+            , hasGlobalMap          = packedField `testBit` 7
+            , colorResolution       = (packedField `unsafeShiftR` 4) .&. 0x7 + 1
+            , isColorTableSorted    = packedField `testBit` 3
+            , colorTableSize        = (packedField .&. 0x7) + 1
+            , backgroundIndex       = backgroundColorIndex
+            }
+
+
+--------------------------------------------------
+----            ImageDescriptor
+--------------------------------------------------
+-- | Section 20 of spec-gif89a
+data ImageDescriptor = ImageDescriptor
+  { gDescPixelsFromLeft         :: !Word16
+  , gDescPixelsFromTop          :: !Word16
+  , gDescImageWidth             :: !Word16
+  , gDescImageHeight            :: !Word16
+  , gDescHasLocalMap            :: !Bool
+  , gDescIsInterlaced           :: !Bool
+  , gDescIsImgDescriptorSorted  :: !Bool
+  , gDescLocalColorTableSize    :: !Word8
+  }
+
+imageSeparator, extensionIntroducer, gifTrailer :: Word8
+imageSeparator      = 0x2C
+extensionIntroducer = 0x21
+gifTrailer          = 0x3B
+
+graphicControlLabel, commentLabel, plainTextLabel, applicationLabel :: Word8
+plainTextLabel = 0x01
+graphicControlLabel = 0xF9
+commentLabel = 0xFE
+applicationLabel    = 0xFF
+
+
+parseDataBlocks :: Get B.ByteString
+parseDataBlocks = B.concat <$> (getWord8 >>= aux)
+ where aux    0 = pure []
+       aux size = (:) <$> getByteString (fromIntegral size) <*> (getWord8 >>= aux)
+
+putDataBlocks :: B.ByteString -> Put
+putDataBlocks wholeString = putSlices wholeString >> putWord8 0
+  where putSlices str | B.length str == 0 = pure ()
+                      | B.length str > 0xFF =
+            let (before, after) = B.splitAt 0xFF str in
+            putWord8 0xFF >> putByteString before >> putSlices after
+        putSlices str =
+            putWord8 (fromIntegral $ B.length str) >> putByteString str
+
+data GifDisposalMethod
+    = DisposalAny
+    | DisposalDoNot
+    | DisposalRestoreBackground
+    | DisposalRestorePrevious
+    | DisposalUnknown Word8
+
+disposalMethodOfCode :: Word8 -> GifDisposalMethod
+disposalMethodOfCode v = case v of
+    0 -> DisposalAny
+    1 -> DisposalDoNot
+    2 -> DisposalRestoreBackground
+    3 -> DisposalRestorePrevious
+    n -> DisposalUnknown n
+
+codeOfDisposalMethod :: GifDisposalMethod -> Word8
+codeOfDisposalMethod v = case v of
+    DisposalAny -> 0
+    DisposalDoNot -> 1
+    DisposalRestoreBackground -> 2
+    DisposalRestorePrevious -> 3
+    DisposalUnknown n -> n
+
+data GraphicControlExtension = GraphicControlExtension
+    { gceDisposalMethod        :: !GifDisposalMethod -- ^ Stored on 3 bits
+    , gceUserInputFlag         :: !Bool
+    , gceTransparentFlag       :: !Bool
+    , gceDelay                 :: !Word16
+    , gceTransparentColorIndex :: !Word8
+    }
+
+instance Binary GraphicControlExtension where
+    put v = do
+        putWord8 extensionIntroducer
+        putWord8 graphicControlLabel
+        putWord8 0x4  -- size
+        let disposalCode = codeOfDisposalMethod $ gceDisposalMethod v
+            disposalField =
+                (disposalCode .&. 0x7) `unsafeShiftL` 2
+
+            userInputField
+                | gceUserInputFlag v = 0 `setBit` 1
+                | otherwise = 0
+
+            transparentField
+                | gceTransparentFlag v = 0 `setBit` 0
+                | otherwise = 0
+
+            packedFields =  disposalField
+                        .|. userInputField
+                        .|. transparentField
+
+        putWord8 packedFields
+        putWord16le $ gceDelay v
+        putWord8 $ gceTransparentColorIndex v
+        putWord8 0 -- blockTerminator
+
+    get = do
+        -- due to missing lookahead
+        {-_extensionLabel  <- getWord8-}
+        _size            <- getWord8
+        packedFields     <- getWord8
+        delay            <- getWord16le
+        idx              <- getWord8
+        _blockTerminator <- getWord8
+        return GraphicControlExtension
+            { gceDisposalMethod        = 
+                disposalMethodOfCode $
+                    (packedFields `unsafeShiftR` 2) .&. 0x07
+            , gceUserInputFlag         = packedFields `testBit` 1
+            , gceTransparentFlag       = packedFields `testBit` 0
+            , gceDelay                 = delay
+            , gceTransparentColorIndex = idx
+            }
+
+data GifImage = GifImage
+    { imgDescriptor   :: !ImageDescriptor
+    , imgLocalPalette :: !(Maybe Palette)
+    , imgLzwRootSize  :: !Word8
+    , imgData         :: B.ByteString
+    }
+
+instance Binary GifImage where
+    put img = do
+        let descriptor = imgDescriptor img
+        put descriptor
+        case ( imgLocalPalette img
+             , gDescHasLocalMap $ imgDescriptor img) of
+          (Nothing, _) -> return ()
+          (Just _, False) -> return ()
+          (Just p, True) ->
+              putPalette (fromIntegral $ gDescLocalColorTableSize descriptor) p
+        putWord8 $ imgLzwRootSize img
+        putDataBlocks $ imgData img
+
+    get = do
+        desc <- get
+        let hasLocalColorTable = gDescHasLocalMap desc
+        palette <- if hasLocalColorTable
+           then Just <$> getPalette (gDescLocalColorTableSize desc)
+           else pure Nothing
+
+        GifImage desc palette <$> getWord8 <*> parseDataBlocks
+
+data Block = BlockImage GifImage
+           | BlockGraphicControl GraphicControlExtension
+
+skipSubDataBlocks :: Get ()
+skipSubDataBlocks = do
+  s <- fromIntegral <$> getWord8
+  unless (s == 0) $
+    skip s >> skipSubDataBlocks
+
+parseGifBlocks :: Get [Block]
+parseGifBlocks = getWord8 >>= blockParse
+  where
+    blockParse v
+      | v == gifTrailer = pure []
+      | v == imageSeparator = (:) <$> (BlockImage <$> get) <*> parseGifBlocks
+      | v == extensionIntroducer = getWord8 >>= extensionParse
+
+    blockParse v = do
+      readPosition <- bytesRead
+      fail ("Unrecognized gif block " ++ show v ++ " @" ++ show readPosition)
+
+    extensionParse code
+     | code == graphicControlLabel =
+        (:) <$> (BlockGraphicControl <$> get) <*> parseGifBlocks
+     | code == commentLabel = skipSubDataBlocks >> parseGifBlocks
+     | code `elem` [plainTextLabel, applicationLabel] =
+        fromIntegral <$> getWord8 >>= skip >> skipSubDataBlocks >> parseGifBlocks
+     | otherwise = parseDataBlocks >> parseGifBlocks
+
+
+instance Binary ImageDescriptor where
+    put v = do
+        putWord8 imageSeparator
+        putWord16le $ gDescPixelsFromLeft v
+        putWord16le $ gDescPixelsFromTop v
+        putWord16le $ gDescImageWidth v
+        putWord16le $ gDescImageHeight v
+        let localMapField
+                | gDescHasLocalMap v = 0 `setBit` 7
+                | otherwise = 0
+
+            isInterlacedField
+                | gDescIsInterlaced v = 0 `setBit` 6
+                | otherwise = 0
+
+            isImageDescriptorSorted
+                | gDescIsImgDescriptorSorted v = 0 `setBit` 5
+                | otherwise = 0
+
+            localSize = gDescLocalColorTableSize v
+            tableSizeField
+                | localSize > 0 = (localSize - 1) .&. 0x7
+                | otherwise = 0
+
+            packedFields = localMapField
+                        .|. isInterlacedField
+                        .|. isImageDescriptorSorted
+                        .|. tableSizeField
+        putWord8 packedFields
+
+    get = do
+        -- due to missing lookahead
+        {-_imageSeparator <- getWord8-}
+        imgLeftPos <- getWord16le
+        imgTopPos  <- getWord16le
+        imgWidth   <- getWord16le
+        imgHeight  <- getWord16le
+        packedFields <- getWord8
+        return ImageDescriptor
+            { gDescPixelsFromLeft = imgLeftPos
+            , gDescPixelsFromTop  = imgTopPos
+            , gDescImageWidth     = imgWidth
+            , gDescImageHeight    = imgHeight
+            , gDescHasLocalMap    = packedFields `testBit` 7
+            , gDescIsInterlaced     = packedFields `testBit` 6
+            , gDescIsImgDescriptorSorted = packedFields `testBit` 5
+            , gDescLocalColorTableSize = (packedFields .&. 0x7) + 1
+            }
+
+
+--------------------------------------------------
+----            Palette
+--------------------------------------------------
+getPalette :: Word8 -> Get Palette
+getPalette bitDepth = 
+    Image size 1 . V.fromList <$> replicateM (size * 3) get
+  where size = 2 ^ (fromIntegral bitDepth :: Int)
+
+putPalette :: Int -> Palette -> Put
+putPalette size pal = do
+    V.mapM_ putWord8 (imageData pal)
+    replicateM_ missingColorComponent (putWord8 0)
+  where elemCount = 2 ^ size
+        missingColorComponent = (elemCount - imageWidth pal) * 3
+
+--------------------------------------------------
+----            GifImage
+--------------------------------------------------
+data GifHeader = GifHeader
+  { gifVersion          :: GifVersion
+  , gifScreenDescriptor :: LogicalScreenDescriptor
+  , gifGlobalMap        :: Maybe Palette
+  }
+
+instance Binary GifHeader where
+    put v = do
+      put $ gifVersion v
+      let descr = gifScreenDescriptor v
+      put descr
+      case gifGlobalMap v of
+        Just palette -> putPalette (fromIntegral $ colorTableSize descr) palette
+        Nothing      -> return ()
+
+    get = do
+        version    <- get
+        screenDesc <- get
+        
+        palette <- 
+          if hasGlobalMap screenDesc then
+            return <$> getPalette (colorTableSize screenDesc)
+          else
+            return Nothing
+
+        return GifHeader
+            { gifVersion = version
+            , gifScreenDescriptor = screenDesc
+            , gifGlobalMap = palette
+            }
+
+data GifFile = GifFile
+    { gifHeader      :: !GifHeader
+    , gifImages      :: [(Maybe GraphicControlExtension, GifImage)]
+    , gifLoopingBehaviour :: GifLooping
+    }
+
+putLooping :: GifLooping -> Put
+putLooping LoopingNever = return ()
+putLooping LoopingForever = putLooping $ LoopingRepeat 0
+putLooping (LoopingRepeat count) = do
+    putWord8 extensionIntroducer
+    putWord8 applicationLabel
+    putWord8 11 -- the size
+    putByteString $ BC.pack "NETSCAPE2.0"
+    putWord8 3 -- size of sub block
+    putWord8 1
+    putWord16le count
+    putWord8 0
+
+associateDescr :: [Block] -> [(Maybe GraphicControlExtension, GifImage)]
+associateDescr [] = []
+associateDescr [BlockGraphicControl _] = []
+associateDescr (BlockGraphicControl _ : rest@(BlockGraphicControl _ : _)) =
+    associateDescr rest
+associateDescr (BlockImage img:xs) = (Nothing, img) : associateDescr xs
+associateDescr (BlockGraphicControl ctrl : BlockImage img : xs) =
+    (Just ctrl, img) : associateDescr xs
+
+instance Binary GifFile where
+    put v = do
+        put $ gifHeader v
+        let putter (Nothing, i) = put i
+            putter (Just a, i) = put a >> put i
+        putLooping $ gifLoopingBehaviour v
+        mapM_ putter $ gifImages v
+        put gifTrailer
+
+    get = do
+        hdr <- get
+        blocks <- parseGifBlocks
+        return GifFile { gifHeader = hdr
+                       , gifImages = associateDescr blocks
+                       , gifLoopingBehaviour = LoopingNever
+                       }
+
+substituteColors :: Palette -> Image Pixel8 -> Image PixelRGB8
+substituteColors palette = pixelMap swaper
+  where swaper n = pixelAt palette (fromIntegral n) 0
+
+substituteColorsWithTransparency :: Int -> Image PixelRGBA8 -> Image Pixel8 -> Image PixelRGBA8
+substituteColorsWithTransparency transparent palette = pixelMap swaper where
+  swaper n | ix == transparent = PixelRGBA8 0 0 0 0
+           | otherwise = promotePixel $ pixelAt palette ix 0
+    where ix = fromIntegral n
+
+
+decodeImage :: GifImage -> Image Pixel8
+decodeImage img = runST $ runBoolReader $ do
+    outputVector <- lift . M.new $ width * height
+    decodeLzw (imgData img) 12 lzwRoot outputVector
+    frozenData <- lift $ V.unsafeFreeze outputVector
+    return . deinterlaceGif $ Image
+      { imageWidth = width
+      , imageHeight = height
+      , imageData = frozenData
+      }
+  where lzwRoot = fromIntegral $ imgLzwRootSize img
+        width = fromIntegral $ gDescImageWidth descriptor
+        height = fromIntegral $ gDescImageHeight descriptor
+        isInterlaced = gDescIsInterlaced descriptor
+        descriptor = imgDescriptor img
+
+        deinterlaceGif | not isInterlaced = id
+                       | otherwise = deinterlaceGifImage
+
+deinterlaceGifImage :: Image Pixel8 -> Image Pixel8
+deinterlaceGifImage img@(Image { imageWidth = w, imageHeight = h }) = generateImage generator w h
+   where lineIndices = gifInterlacingIndices h
+         generator x y = pixelAt img x y'
+            where y' = lineIndices V.! y
+
+gifInterlacingIndices :: Int -> V.Vector Int
+gifInterlacingIndices height = V.accum (\_ v -> v) (V.replicate height 0) indices
+    where indices = flip zip [0..] $
+                concat [ [0,     8 .. height - 1]
+                       , [4, 4 + 8 .. height - 1]
+                       , [2, 2 + 4 .. height - 1]
+                       , [1, 1 + 2 .. height - 1]
+                       ]
+
+paletteOf :: (ColorConvertible PixelRGB8 px)
+          => Image px -> GifImage -> Image px
+paletteOf global GifImage { imgLocalPalette = Nothing } = global
+paletteOf      _ GifImage { imgLocalPalette = Just p  } = promoteImage p
+
+getFrameDelays :: GifFile -> [GifDelay]
+getFrameDelays GifFile { gifImages = [] } = []
+getFrameDelays GifFile { gifImages = imgs } = map extractDelay imgs
+    where extractDelay (ext, _) =
+            case ext of
+                Nothing -> 0
+                Just e -> fromIntegral $ gceDelay e
+
+transparentColorOf :: Maybe GraphicControlExtension -> Int
+transparentColorOf Nothing = 300
+transparentColorOf (Just ext)
+  | gceTransparentFlag ext = fromIntegral $ gceTransparentColorIndex ext
+  | otherwise = 300
+
+hasTransparency :: Maybe GraphicControlExtension -> Bool
+hasTransparency Nothing = False
+hasTransparency (Just control) = gceTransparentFlag control
+
+decodeAllGifImages :: GifFile -> [PalettedImage]
+decodeAllGifImages GifFile { gifImages = [] } = []
+decodeAllGifImages GifFile { gifHeader = GifHeader { gifGlobalMap = palette
+                                                   , gifScreenDescriptor = wholeDescriptor }
+                           , gifImages = (firstControl, firstImage) : rest }
+  | not (hasTransparency firstControl) =
+      let backImage =
+              generateImage (\_ _ -> backgroundColor) globalWidth globalHeight
+          thisPalette = paletteOf globalPalette firstImage
+          baseImage = decodeImage firstImage
+          initState =
+            (thisPalette, firstControl, substituteColors thisPalette baseImage)
+          scanner = gifAnimationApplyer (globalWidth, globalHeight) thisPalette backImage
+          palette' = Palette'
+            { _paletteSize = imageWidth thisPalette
+            , _paletteData = imageData thisPalette
+            }
+      in
+      PalettedRGB8 baseImage palette' :
+        [TrueColorImage $ ImageRGB8 img | (_, _, img) <- tail $ scanl scanner initState rest]
+
+  | otherwise =
+      let backImage :: Image PixelRGBA8
+          backImage =
+            generateImage (\_ _ -> transparentBackground) globalWidth globalHeight
+
+          thisPalette :: Image PixelRGBA8
+          thisPalette = paletteOf (promoteImage globalPalette) firstImage
+
+          transparentCode = transparentColorOf firstControl
+          decoded = 
+            substituteColorsWithTransparency transparentCode thisPalette $
+                decodeImage firstImage
+
+          initState = (thisPalette, firstControl, decoded)
+          scanner =
+            gifAnimationApplyer (globalWidth, globalHeight) thisPalette backImage in
+      [TrueColorImage $ ImageRGBA8 img | (_, _, img) <- scanl scanner initState rest]
+
+    where
+      globalWidth = fromIntegral $ screenWidth wholeDescriptor
+      globalHeight = fromIntegral $ screenHeight wholeDescriptor
+      globalPalette = maybe greyPalette id palette
+
+      transparentBackground = PixelRGBA8 r g b 0
+          where PixelRGB8 r g b = backgroundColor
+
+      backgroundColor
+        | hasGlobalMap wholeDescriptor =
+            pixelAt globalPalette (fromIntegral $ backgroundIndex wholeDescriptor) 0
+        | otherwise = PixelRGB8 0 0 0
+
+gifAnimationApplyer :: forall px.  (ColorConvertible PixelRGB8 px)
+                    => (Int, Int) -> Image px -> Image px
+                    -> (Image px, Maybe GraphicControlExtension, Image px)
+                    -> (Maybe GraphicControlExtension, GifImage)
+                    -> (Image px, Maybe GraphicControlExtension, Image px)
+gifAnimationApplyer (globalWidth, globalHeight) globalPalette backgroundImage
+          (_, prevControl, img1)
+          (controlExt, img2@(GifImage { imgDescriptor = descriptor })) =
+            (thisPalette, controlExt, thisImage)
+  where
+    thisPalette :: Image px
+    thisPalette = paletteOf globalPalette img2
+
+    thisImage = generateImage pixeler globalWidth globalHeight
+    localWidth = fromIntegral $ gDescImageWidth descriptor
+    localHeight = fromIntegral $ gDescImageHeight descriptor
+
+    left = fromIntegral $ gDescPixelsFromLeft descriptor
+    top = fromIntegral $ gDescPixelsFromTop descriptor
+
+    isPixelInLocalImage x y =
+        x >= left && x < left + localWidth && y >= top && y < top + localHeight
+
+    decoded :: Image Pixel8
+    decoded = decodeImage img2
+
+    transparent :: Int
+    transparent = case controlExt of
+        Nothing  -> 300
+        Just ext -> if gceTransparentFlag ext
+            then fromIntegral $ gceTransparentColorIndex ext
+            else 300
+
+    oldImage = case gceDisposalMethod <$> prevControl of
+        Nothing -> img1
+        Just DisposalAny -> img1
+        Just DisposalDoNot -> img1
+        Just DisposalRestoreBackground -> backgroundImage
+        Just DisposalRestorePrevious -> img1
+        Just (DisposalUnknown _) -> img1
+
+    pixeler x y
+      | isPixelInLocalImage x y && code /= transparent = val where
+          code = fromIntegral $ pixelAt decoded (x - left) (y - top)
+          val = pixelAt thisPalette (fromIntegral code) 0
+    pixeler x y = pixelAt oldImage x y
+
+decodeFirstGifImage :: GifFile -> Either String (PalettedImage, Metadatas)
+decodeFirstGifImage img@GifFile { gifImages = (firstImage:_) } =
+    case decodeAllGifImages img { gifImages = [firstImage] } of
+      [] -> Left "No image after decoding"
+      (i:_) -> Right (i, basicMetadata SourceGif (screenWidth hdr) (screenHeight hdr))
+  where hdr = gifScreenDescriptor $ gifHeader img
+decodeFirstGifImage _ = Left "No image in gif file"
+
+-- | Transform a raw gif image to an image, without modifying the pixels. This
+-- function can output the following images:
+--
+--  * 'ImageRGB8'
+--
+--  * 'ImageRGBA8'
+--
+decodeGif :: B.ByteString -> Either String DynamicImage
+decodeGif img = decode img >>= (fmap (palettedToTrueColor . fst) . decodeFirstGifImage)
+
+-- | Transform a raw gif image to an image, without modifying the pixels.  This
+-- function can output the following images:
+--
+--  * 'ImageRGB8'
+--
+--  * 'ImageRGBA8'
+--
+-- Metadatas include Width & Height information.
+--
+decodeGifWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
+decodeGifWithMetadata img = first palettedToTrueColor <$> decodeGifWithPaletteAndMetadata img
+
+-- | Return the gif image with metadata and palette.
+-- The palette is only returned for the first image of an
+-- animation and has no transparency.
+decodeGifWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
+decodeGifWithPaletteAndMetadata img = decode img >>= decodeFirstGifImage
+
+-- | Transform a raw gif to a list of images, representing
+-- all the images of an animation.
+decodeGifImages :: B.ByteString -> Either String [DynamicImage]
+decodeGifImages img = fmap palettedToTrueColor . decodeAllGifImages <$> decode img
+
+-- | Extract a list of frame delays from a raw gif.
+getDelaysGifImages :: B.ByteString -> Either String [GifDelay]
+getDelaysGifImages img = getFrameDelays <$> decode img
+
+-- | Default palette to produce greyscale images.
+greyPalette :: Palette
+greyPalette = generateImage toGrey 256 1
+  where toGrey x _ = PixelRGB8 ix ix ix
+           where ix = fromIntegral x
+
+checkImageSizes :: GifEncode -> Either String ()
+checkImageSizes GifEncode { geWidth = width, geHeight = height, geFrames = frames }
+  | not $ isInBounds width && isInBounds height = Left "Invalid screen bounds"
+  | not $ null outOfBounds = Left $ "GIF frames with invalid bounds: " ++ show (map snd outOfBounds)
+  | otherwise = Right ()
+  where isInBounds dim = dim > 0 && dim <= 0xffff
+        outOfBounds = filter (not . isFrameInBounds . fst) $ zip frames [0 :: Int ..]
+        isFrameInBounds GifFrame { gfPixels = img } = isInBounds (imageWidth img) && isInBounds (imageHeight img)
+
+checkImagesInBounds :: GifEncode -> Either String ()
+checkImagesInBounds GifEncode { geWidth = width, geHeight = height, geFrames = frames } =
+  if null outOfBounds
+  then Right ()
+  else Left $ "GIF frames out of screen bounds: " ++ show (map snd outOfBounds)
+  where outOfBounds = filter (not . isInBounds . fst) $ zip frames [0 :: Int ..]
+        isInBounds GifFrame { gfXOffset = xOff, gfYOffset = yOff, gfPixels = img } =
+          xOff >= 0 && yOff >= 0 &&
+          xOff + imageWidth img <= width && yOff + imageHeight img <= height
+
+checkPaletteValidity :: GifEncode -> Either String ()
+checkPaletteValidity spec
+  | not $ isPaletteValid $ gePalette spec = Left "Invalid global palette size"
+  | not $ null invalidPalettes = Left $ "Invalid palette size in GIF frames: " ++ show (map snd invalidPalettes)
+  | otherwise = Right ()
+  where invalidPalettes = filter (not . isPaletteValid . gfPalette . fst) $ zip (geFrames spec) [0 :: Int ..]
+        isPaletteValid Nothing  = True
+        isPaletteValid (Just p) = let w = imageWidth p
+                                      h = imageHeight p
+                                  in h == 1 && w > 0 && w <= 256
+
+checkIndexAbsentFromPalette :: GifEncode -> Either String ()
+checkIndexAbsentFromPalette GifEncode { gePalette = global, geFrames = frames } =
+  if null missingPalette
+  then Right ()
+  else Left $ "GIF image frames with color indexes missing from palette: " ++ show (map snd missingPalette)
+  where missingPalette = filter (not . checkFrame . fst) $ zip frames [0 :: Int ..]
+        checkFrame frame = V.all (checkIndexInPalette global (gfPalette frame) . fromIntegral) $
+                           imageData $ gfPixels frame
+
+checkBackground :: GifEncode -> Either String ()
+checkBackground GifEncode { geBackground = Nothing } = Right ()
+checkBackground GifEncode { gePalette = global, geBackground = Just background } =
+  if checkIndexInPalette global Nothing background
+  then Right ()
+  else Left "GIF background index absent from global palette"
+
+checkTransparencies :: GifEncode -> Either String ()
+checkTransparencies GifEncode { gePalette = global, geFrames = frames } =
+  if null missingTransparency
+  then Right ()
+  else Left $ "GIF transparent index absent from palettes for frames: " ++ show (map snd missingTransparency)
+  where missingTransparency = filter (not . transparencyOK . fst) $ zip frames [0 :: Int ..]
+        transparencyOK GifFrame { gfTransparent = Nothing } = True
+        transparencyOK GifFrame { gfPalette = local, gfTransparent = Just transparent } =
+          checkIndexInPalette global local transparent
+
+checkIndexInPalette :: Maybe Palette -> Maybe Palette -> Int -> Bool
+checkIndexInPalette Nothing       Nothing      _  = False
+checkIndexInPalette _             (Just local) ix = ix < imageWidth local
+checkIndexInPalette (Just global) _            ix = ix < imageWidth global
+
+checkGifImageSizes :: [(a, b, Image px)] -> Bool
+checkGifImageSizes [] = False
+checkGifImageSizes ((_, _, img) : rest) = all checkDimension rest
+   where width = imageWidth img
+         height = imageHeight img
+
+         checkDimension (_,_,Image { imageWidth = w, imageHeight = h }) =
+             w == width && h == height
+
+computeColorTableSize :: Palette -> Int
+computeColorTableSize Image { imageWidth = itemCount } = go 1
+  where go k | 2 ^ k >= itemCount = k
+             | otherwise = go $ k + 1
+
+-- | Encode a complex gif to a bytestring.
+--
+-- * There must be at least one image.
+--
+-- * The screen and every frame dimensions must be between 1 and 65535.
+--
+-- * Every frame image must fit within the screen bounds.
+--
+-- * Every palette must have between one and 256 colors.
+--
+-- * There must be a global palette or every image must have a local palette.
+--
+-- * The background color index must be present in the global palette.
+--
+-- * Every frame's transparent color index, if set, must be present in the palette used by that frame.
+--
+-- * Every color index used in an image must be present in the palette used by that frame.
+--
+encodeComplexGifImage :: GifEncode -> Either String L.ByteString
+encodeComplexGifImage spec = do
+  when (null $ geFrames spec) $ Left "No GIF frames"
+  checkImageSizes spec
+  checkImagesInBounds spec
+  checkPaletteValidity spec
+  checkBackground spec
+  checkTransparencies spec
+  checkIndexAbsentFromPalette spec
+
+  Right $ encode allFile
+  where
+    GifEncode { geWidth      = width
+              , geHeight     = height
+              , gePalette    = globalPalette
+              , geBackground = background
+              , geLooping    = looping
+              , geFrames     = frames
+              } = spec
+    allFile = GifFile
+      { gifHeader = GifHeader
+        { gifVersion          = version
+        , gifScreenDescriptor = logicalScreen
+        , gifGlobalMap        = globalPalette
+        }
+      , gifImages           = toSerialize
+      , gifLoopingBehaviour = looping
+      }
+
+    version = case frames of
+      [] -> GIF87a
+      [_] -> GIF87a
+      _:_:_ -> GIF89a
+
+    logicalScreen = LogicalScreenDescriptor
+      { screenWidth        = fromIntegral width
+      , screenHeight       = fromIntegral height
+      , backgroundIndex    = maybe 0 fromIntegral background
+      , hasGlobalMap       = maybe False (const True) globalPalette
+      , colorResolution    = 8
+      , isColorTableSorted = False
+      -- Imply a 8 bit global palette size if there's no explicit global palette.
+      , colorTableSize     = maybe 8 (fromIntegral . computeColorTableSize) globalPalette
+      }
+
+    toSerialize = [(controlExtension delay transparent disposal, GifImage
+                     { imgDescriptor = imageDescriptor left top localPalette img
+                     , imgLocalPalette = localPalette
+                     , imgLzwRootSize = fromIntegral lzwKeySize
+                     , imgData = B.concat . L.toChunks . lzwEncode lzwKeySize $ imageData img
+                     })
+                  | GifFrame { gfXOffset     = left
+                             , gfYOffset     = top
+                             , gfPalette     = localPalette
+                             , gfTransparent = transparent
+                             , gfDelay       = delay
+                             , gfDisposal    = disposal
+                             , gfPixels      = img } <- frames
+                  , let palette = case (globalPalette, localPalette) of
+                          (_, Just local)        -> local
+                          (Just global, Nothing) -> global
+                          (Nothing, Nothing)     -> error "No palette for image" -- redundant, we guard for this
+                    -- Some decoders (looking at you, GIMP) don't handle initial LZW key size of 1 correctly.
+                    -- We'll waste some space for the sake of interoperability
+                  , let lzwKeySize = max 2 $ computeColorTableSize palette
+                  ]
+
+    controlExtension 0     Nothing     DisposalAny = Nothing
+    controlExtension delay transparent disposal    = Just GraphicControlExtension
+      { gceDisposalMethod        = disposal
+      , gceUserInputFlag         = False
+      , gceTransparentFlag       = maybe False (const True) transparent
+      , gceDelay                 = fromIntegral delay
+      , gceTransparentColorIndex = maybe 0 fromIntegral transparent
+      }
+
+    imageDescriptor left top localPalette img = ImageDescriptor
+      { gDescPixelsFromLeft         = fromIntegral left
+      , gDescPixelsFromTop          = fromIntegral top
+      , gDescImageWidth             = fromIntegral $ imageWidth img
+      , gDescImageHeight            = fromIntegral $ imageHeight img
+      , gDescHasLocalMap            = maybe False (const True) localPalette
+      , gDescIsInterlaced           = False
+      , gDescIsImgDescriptorSorted  = False
+      , gDescLocalColorTableSize    = maybe 0 (fromIntegral . computeColorTableSize) localPalette
+      }
+
+-- | Encode a gif animation to a bytestring.
+--
+-- * Every image must have the same size
+--
+-- * Every palette must have between one and 256 colors.
+--
+encodeGifImages :: GifLooping -> [(Palette, GifDelay, Image Pixel8)]
+                -> Either String L.ByteString
+encodeGifImages _ [] = Left "No image in list"
+encodeGifImages _ imageList
+    | not $ checkGifImageSizes imageList = Left "Gif images have different size"
+encodeGifImages looping imageList@((firstPalette, _,firstImage):_) =
+  encodeComplexGifImage $ GifEncode (imageWidth firstImage) (imageHeight firstImage) (Just firstPalette) Nothing looping frames
+  where
+    frames = [ GifFrame 0 0 localPalette Nothing delay DisposalAny image
+             | (palette, delay, image) <- imageList
+             , let localPalette = if paletteEqual palette then Nothing else Just palette ]
+
+    paletteEqual p = imageData firstPalette == imageData p
+
+-- | Encode a greyscale image to a bytestring.
+encodeGifImage :: Image Pixel8 -> L.ByteString
+encodeGifImage img = case encodeGifImages LoopingNever [(greyPalette, 0, img)] of
+    Left err -> error $ "Impossible:" ++ err
+    Right v -> v
+
+-- | Encode an image with a given palette.
+-- Can return errors if the palette is ill-formed.
+--
+-- * A palette must have between 1 and 256 colors
+--
+encodeGifImageWithPalette :: Image Pixel8 -> Palette -> Either String L.ByteString
+encodeGifImageWithPalette img palette =
+    encodeGifImages LoopingNever [(palette, 0, img)]
+
+-- | Write a greyscale in a gif file on the disk.
+writeGifImage :: FilePath -> Image Pixel8 -> IO ()
+writeGifImage file = L.writeFile file . encodeGifImage
+
+-- | Write a list of images as a gif animation in a file.
+--
+-- * Every image must have the same size
+--
+-- * Every palette must have between one and 256 colors.
+--
+writeGifImages :: FilePath -> GifLooping -> [(Palette, GifDelay, Image Pixel8)]
+               -> Either String (IO ())
+writeGifImages file looping lst = L.writeFile file <$> encodeGifImages looping lst
+
+-- | Write a gif image with a palette to a file.
+--
+-- * A palette must have between 1 and 256 colors
+--
+writeGifImageWithPalette :: FilePath -> Image Pixel8 -> Palette
+                         -> Either String (IO ())
+writeGifImageWithPalette file img palette =
+    L.writeFile file <$> encodeGifImageWithPalette img palette
+
+writeComplexGifImage :: FilePath -> GifEncode -> Either String (IO ())
+writeComplexGifImage file spec = L.writeFile file <$> encodeComplexGifImage spec
diff --git a/src/Codec/Picture/Gif/Internal/LZW.hs b/src/Codec/Picture/Gif/Internal/LZW.hs
--- a/src/Codec/Picture/Gif/Internal/LZW.hs
+++ b/src/Codec/Picture/Gif/Internal/LZW.hs
@@ -1,194 +1,194 @@
-{-# LANGUAGE CPP #-}
-module Codec.Picture.Gif.Internal.LZW( decodeLzw, decodeLzwTiff ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>) )
-#endif
-
-import Data.Word( Word8 )
-import Control.Monad( when, unless )
-
-import Data.Bits( (.&.) )
-
-import Control.Monad.ST( ST )
-import Control.Monad.Trans.Class( MonadTrans, lift )
-
-import Foreign.Storable ( Storable )
-
-import qualified Data.ByteString as B
-import qualified Data.Vector.Storable.Mutable as M
-
-import Codec.Picture.BitWriter
-
-{-# INLINE (.!!!.) #-}
-(.!!!.) :: (Storable a) => M.STVector s a -> Int -> ST s a
-(.!!!.) = M.unsafeRead 
-        {-M.read-}
-
-{-# INLINE (..!!!..) #-}
-(..!!!..) :: (MonadTrans t, Storable a)
-          => M.STVector s a -> Int -> t (ST s) a
-(..!!!..) v idx = lift $ v .!!!. idx
-
-{-# INLINE (.<-.) #-}
-(.<-.) :: (Storable a) => M.STVector s a -> Int -> a -> ST s ()
-(.<-.) = M.unsafeWrite 
-         {-M.write-}
-
-{-# INLINE (..<-..) #-}
-(..<-..) :: (MonadTrans t, Storable a)
-         => M.STVector s a -> Int -> a -> t (ST s) ()
-(..<-..) v idx = lift . (v .<-. idx)
-
-
-duplicateData :: (MonadTrans t, Storable a)
-              => M.STVector s a -> M.STVector s a
-              -> Int -> Int -> Int -> t (ST s) ()
-duplicateData src dest sourceIndex size destIndex = lift $ aux sourceIndex destIndex
-  where endIndex = sourceIndex + size
-        aux i _ | i == endIndex  = return ()
-        aux i j = do
-          src .!!!. i >>= (dest .<-. j)
-          aux (i + 1) (j + 1)
-
-rangeSetter :: (Storable a, Num a)
-            => Int -> M.STVector s a
-            -> ST s (M.STVector s a)
-rangeSetter count vec = aux 0
-  where aux n | n == count = return vec
-        aux n = (vec .<-. n) (fromIntegral n) >> aux (n + 1)
-
-decodeLzw :: B.ByteString -> Int -> Int -> M.STVector s Word8
-          -> BoolReader s ()
-decodeLzw str maxBitKey initialKey outVec = do
-    setDecodedString str
-    lzw GifVariant maxBitKey initialKey 0 outVec
-
-isOldTiffLZW :: B.ByteString -> Bool
-isOldTiffLZW str = firstByte == 0 && secondByte == 1
-    where firstByte = str `B.index` 0
-          secondByte = (str `B.index` 1) .&. 1
-
-decodeLzwTiff :: B.ByteString -> M.STVector s Word8 -> Int
-              -> BoolReader s()
-decodeLzwTiff str outVec initialWriteIdx = do
-    if isOldTiffLZW str then
-      setDecodedString str
-    else
-      setDecodedStringMSB str
-    let variant | isOldTiffLZW str = OldTiffVariant
-                | otherwise = TiffVariant
-    lzw variant 12 9 initialWriteIdx outVec
-
-data TiffVariant =
-      GifVariant
-    | TiffVariant
-    | OldTiffVariant
-    deriving Eq
-
--- | Gif image constraint from spec-gif89a, code size max : 12 bits.
-lzw :: TiffVariant -> Int -> Int -> Int -> M.STVector s Word8
-    -> BoolReader s ()
-lzw variant nMaxBitKeySize initialKeySize initialWriteIdx outVec = do
-    -- Allocate buffer of maximum size.
-    lzwData <- lift (M.replicate maxDataSize 0) >>= resetArray
-    lzwOffsetTable <- lift (M.replicate tableEntryCount 0) >>= resetArray
-    lzwSizeTable <- lift $ M.replicate tableEntryCount 0
-    lift $ lzwSizeTable `M.set` 1
-
-    let firstVal code = do
-            dataOffset <- lzwOffsetTable ..!!!.. code
-            lzwData ..!!!.. dataOffset
-
-        writeString at code = do
-            dataOffset <- lzwOffsetTable ..!!!.. code
-            dataSize   <- lzwSizeTable   ..!!!.. code
-
-            when (at + dataSize <= maxWrite) $
-                 duplicateData lzwData outVec dataOffset dataSize at
-
-            return dataSize
-
-        addString pos at code val = do
-            dataOffset <- lzwOffsetTable ..!!!.. code
-            dataSize   <- lzwSizeTable   ..!!!.. code
-
-            when (pos < tableEntryCount) $ do
-              (lzwOffsetTable ..<-.. pos) at
-              (lzwSizeTable ..<-.. pos) $ dataSize + 1
-
-            when (at + dataSize + 1 <= maxDataSize) $ do
-              duplicateData lzwData lzwData dataOffset dataSize at
-              (lzwData ..<-.. (at + dataSize)) val
-
-            return $ dataSize + 1
-
-        maxWrite = M.length outVec
-        loop outWriteIdx writeIdx dicWriteIdx codeSize oldCode code
-          | outWriteIdx >= maxWrite = return ()
-          | code == endOfInfo = return ()
-          | code == clearCode = do
-              toOutput <- getNextCode startCodeSize
-              unless (toOutput == endOfInfo) $ do
-                dataSize <- writeString outWriteIdx toOutput
-                getNextCode startCodeSize >>=
-                  loop (outWriteIdx + dataSize)
-                       firstFreeIndex firstFreeIndex startCodeSize toOutput
-
-          | otherwise =  do
-              (written, dicAdd) <-
-                   if code >= writeIdx then do
-                     c <- firstVal oldCode
-                     wroteSize <- writeString outWriteIdx oldCode
-                     (outVec ..<-.. (outWriteIdx + wroteSize)) c
-                     addedSize <- addString writeIdx dicWriteIdx oldCode c
-                     return (wroteSize + 1, addedSize)
-                   else do
-                     wroteSize <- writeString outWriteIdx code
-                     c <- firstVal code
-                     addedSize <- addString writeIdx dicWriteIdx oldCode c
-                     return (wroteSize, addedSize)
-
-              let new_code_size = updateCodeSize codeSize $ writeIdx + 1
-              getNextCode new_code_size >>=
-                loop (outWriteIdx + written)
-                     (writeIdx + 1)
-                     (dicWriteIdx + dicAdd)
-                     new_code_size
-                     code
-
-    getNextCode startCodeSize >>=
-        loop initialWriteIdx firstFreeIndex firstFreeIndex startCodeSize 0
-
-  where tableEntryCount =  2 ^ min 12 nMaxBitKeySize
-        maxDataSize = tableEntryCount `div` 2 * (1 + tableEntryCount) + 1
-
-        isNewTiff = variant == TiffVariant
-        (switchOffset,  isTiffVariant) = case variant of
-            GifVariant -> (0, False)
-            TiffVariant -> (1, True)
-            OldTiffVariant -> (0, True)
-
-        initialElementCount = 2 ^ initialKeySize :: Int
-        clearCode | isTiffVariant = 256
-                  | otherwise = initialElementCount
-
-        endOfInfo | isTiffVariant = 257
-                  | otherwise = clearCode + 1
-
-        startCodeSize 
-                  | isTiffVariant = initialKeySize
-                  | otherwise = initialKeySize + 1
-
-        firstFreeIndex = endOfInfo + 1
-
-        resetArray a = lift $ rangeSetter initialElementCount a
-
-        updateCodeSize codeSize writeIdx
-            | writeIdx == 2 ^ codeSize - switchOffset = min 12 $ codeSize + 1
-            | otherwise = codeSize
-
-        getNextCode s 
-            | isNewTiff = fromIntegral <$> getNextBitsMSBFirst s
-            | otherwise = fromIntegral <$> getNextBitsLSBFirst s
-
+{-# LANGUAGE CPP #-}
+module Codec.Picture.Gif.Internal.LZW( decodeLzw, decodeLzwTiff ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>) )
+#endif
+
+import Data.Word( Word8 )
+import Control.Monad( when, unless )
+
+import Data.Bits( (.&.) )
+
+import Control.Monad.ST( ST )
+import Control.Monad.Trans.Class( MonadTrans, lift )
+
+import Foreign.Storable ( Storable )
+
+import qualified Data.ByteString as B
+import qualified Data.Vector.Storable.Mutable as M
+
+import Codec.Picture.BitWriter
+
+{-# INLINE (.!!!.) #-}
+(.!!!.) :: (Storable a) => M.STVector s a -> Int -> ST s a
+(.!!!.) = M.unsafeRead 
+        {-M.read-}
+
+{-# INLINE (..!!!..) #-}
+(..!!!..) :: (MonadTrans t, Storable a)
+          => M.STVector s a -> Int -> t (ST s) a
+(..!!!..) v idx = lift $ v .!!!. idx
+
+{-# INLINE (.<-.) #-}
+(.<-.) :: (Storable a) => M.STVector s a -> Int -> a -> ST s ()
+(.<-.) = M.unsafeWrite 
+         {-M.write-}
+
+{-# INLINE (..<-..) #-}
+(..<-..) :: (MonadTrans t, Storable a)
+         => M.STVector s a -> Int -> a -> t (ST s) ()
+(..<-..) v idx = lift . (v .<-. idx)
+
+
+duplicateData :: (MonadTrans t, Storable a)
+              => M.STVector s a -> M.STVector s a
+              -> Int -> Int -> Int -> t (ST s) ()
+duplicateData src dest sourceIndex size destIndex = lift $ aux sourceIndex destIndex
+  where endIndex = sourceIndex + size
+        aux i _ | i == endIndex  = return ()
+        aux i j = do
+          src .!!!. i >>= (dest .<-. j)
+          aux (i + 1) (j + 1)
+
+rangeSetter :: (Storable a, Num a)
+            => Int -> M.STVector s a
+            -> ST s (M.STVector s a)
+rangeSetter count vec = aux 0
+  where aux n | n == count = return vec
+        aux n = (vec .<-. n) (fromIntegral n) >> aux (n + 1)
+
+decodeLzw :: B.ByteString -> Int -> Int -> M.STVector s Word8
+          -> BoolReader s ()
+decodeLzw str maxBitKey initialKey outVec = do
+    setDecodedString str
+    lzw GifVariant maxBitKey initialKey 0 outVec
+
+isOldTiffLZW :: B.ByteString -> Bool
+isOldTiffLZW str = firstByte == 0 && secondByte == 1
+    where firstByte = str `B.index` 0
+          secondByte = (str `B.index` 1) .&. 1
+
+decodeLzwTiff :: B.ByteString -> M.STVector s Word8 -> Int
+              -> BoolReader s()
+decodeLzwTiff str outVec initialWriteIdx = do
+    if isOldTiffLZW str then
+      setDecodedString str
+    else
+      setDecodedStringMSB str
+    let variant | isOldTiffLZW str = OldTiffVariant
+                | otherwise = TiffVariant
+    lzw variant 12 9 initialWriteIdx outVec
+
+data TiffVariant =
+      GifVariant
+    | TiffVariant
+    | OldTiffVariant
+    deriving Eq
+
+-- | Gif image constraint from spec-gif89a, code size max : 12 bits.
+lzw :: TiffVariant -> Int -> Int -> Int -> M.STVector s Word8
+    -> BoolReader s ()
+lzw variant nMaxBitKeySize initialKeySize initialWriteIdx outVec = do
+    -- Allocate buffer of maximum size.
+    lzwData <- lift (M.replicate maxDataSize 0) >>= resetArray
+    lzwOffsetTable <- lift (M.replicate tableEntryCount 0) >>= resetArray
+    lzwSizeTable <- lift $ M.replicate tableEntryCount 0
+    lift $ lzwSizeTable `M.set` 1
+
+    let firstVal code = do
+            dataOffset <- lzwOffsetTable ..!!!.. code
+            lzwData ..!!!.. dataOffset
+
+        writeString at code = do
+            dataOffset <- lzwOffsetTable ..!!!.. code
+            dataSize   <- lzwSizeTable   ..!!!.. code
+
+            when (at + dataSize <= maxWrite) $
+                 duplicateData lzwData outVec dataOffset dataSize at
+
+            return dataSize
+
+        addString pos at code val = do
+            dataOffset <- lzwOffsetTable ..!!!.. code
+            dataSize   <- lzwSizeTable   ..!!!.. code
+
+            when (pos < tableEntryCount) $ do
+              (lzwOffsetTable ..<-.. pos) at
+              (lzwSizeTable ..<-.. pos) $ dataSize + 1
+
+            when (at + dataSize + 1 <= maxDataSize) $ do
+              duplicateData lzwData lzwData dataOffset dataSize at
+              (lzwData ..<-.. (at + dataSize)) val
+
+            return $ dataSize + 1
+
+        maxWrite = M.length outVec
+        loop outWriteIdx writeIdx dicWriteIdx codeSize oldCode code
+          | outWriteIdx >= maxWrite = return ()
+          | code == endOfInfo = return ()
+          | code == clearCode = do
+              toOutput <- getNextCode startCodeSize
+              unless (toOutput == endOfInfo) $ do
+                dataSize <- writeString outWriteIdx toOutput
+                getNextCode startCodeSize >>=
+                  loop (outWriteIdx + dataSize)
+                       firstFreeIndex firstFreeIndex startCodeSize toOutput
+
+          | otherwise =  do
+              (written, dicAdd) <-
+                   if code >= writeIdx then do
+                     c <- firstVal oldCode
+                     wroteSize <- writeString outWriteIdx oldCode
+                     (outVec ..<-.. (outWriteIdx + wroteSize)) c
+                     addedSize <- addString writeIdx dicWriteIdx oldCode c
+                     return (wroteSize + 1, addedSize)
+                   else do
+                     wroteSize <- writeString outWriteIdx code
+                     c <- firstVal code
+                     addedSize <- addString writeIdx dicWriteIdx oldCode c
+                     return (wroteSize, addedSize)
+
+              let new_code_size = updateCodeSize codeSize $ writeIdx + 1
+              getNextCode new_code_size >>=
+                loop (outWriteIdx + written)
+                     (writeIdx + 1)
+                     (dicWriteIdx + dicAdd)
+                     new_code_size
+                     code
+
+    getNextCode startCodeSize >>=
+        loop initialWriteIdx firstFreeIndex firstFreeIndex startCodeSize 0
+
+  where tableEntryCount =  2 ^ min 12 nMaxBitKeySize
+        maxDataSize = tableEntryCount `div` 2 * (1 + tableEntryCount) + 1
+
+        isNewTiff = variant == TiffVariant
+        (switchOffset,  isTiffVariant) = case variant of
+            GifVariant -> (0, False)
+            TiffVariant -> (1, True)
+            OldTiffVariant -> (0, True)
+
+        initialElementCount = 2 ^ initialKeySize :: Int
+        clearCode | isTiffVariant = 256
+                  | otherwise = initialElementCount
+
+        endOfInfo | isTiffVariant = 257
+                  | otherwise = clearCode + 1
+
+        startCodeSize 
+                  | isTiffVariant = initialKeySize
+                  | otherwise = initialKeySize + 1
+
+        firstFreeIndex = endOfInfo + 1
+
+        resetArray a = lift $ rangeSetter initialElementCount a
+
+        updateCodeSize codeSize writeIdx
+            | writeIdx == 2 ^ codeSize - switchOffset = min 12 $ codeSize + 1
+            | otherwise = codeSize
+
+        getNextCode s 
+            | isNewTiff = fromIntegral <$> getNextBitsMSBFirst s
+            | otherwise = fromIntegral <$> getNextBitsLSBFirst s
+
diff --git a/src/Codec/Picture/Gif/Internal/LZWEncoding.hs b/src/Codec/Picture/Gif/Internal/LZWEncoding.hs
--- a/src/Codec/Picture/Gif/Internal/LZWEncoding.hs
+++ b/src/Codec/Picture/Gif/Internal/LZWEncoding.hs
@@ -1,101 +1,101 @@
-{-# LANGUAGE BangPatterns, CPP #-}
-module Codec.Picture.Gif.Internal.LZWEncoding( lzwEncode ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>) )
-import Data.Monoid( mempty )
-#endif
-
-import Control.Monad.ST( runST )
-import qualified Data.ByteString.Lazy as L
-import Data.Maybe( fromMaybe )
-import Data.Word( Word8 )
-
-#if MIN_VERSION_containers(0,5,0)
-import qualified Data.IntMap.Strict as I
-#else
-import qualified Data.IntMap as I
-#endif
-import qualified Data.Vector.Storable as V
-
-import Codec.Picture.BitWriter
-
-type Trie = I.IntMap TrieNode
-
-data TrieNode = TrieNode
-    { trieIndex :: {-# UNPACK #-} !Int
-    , trieSub   :: !Trie
-    }
-
-emptyNode :: TrieNode
-emptyNode = TrieNode
-    { trieIndex = -1
-    , trieSub = mempty
-    }
-
-initialTrie :: Trie
-initialTrie = I.fromList
-    [(i, emptyNode { trieIndex = i }) | i <- [0 .. 255]]
-
-lookupUpdate :: V.Vector Word8 -> Int -> Int -> Trie -> (Int, Int, Trie)
-lookupUpdate vector freeIndex firstIndex trie =
-    matchUpdate $ go trie 0 firstIndex 
-  where
-    matchUpdate (lzwOutputIndex, nextReadIndex, sub) =
-        (lzwOutputIndex, nextReadIndex, fromMaybe trie sub)
-
-    maxi = V.length vector
-    go !currentTrie !prevIndex !index
-      | index >= maxi = (prevIndex, index, Nothing)
-      | otherwise = case I.lookup val currentTrie of
-          Just (TrieNode ix subTable) ->
-              let (lzwOutputIndex, nextReadIndex, newTable) =
-                        go subTable ix $ index + 1
-                  tableUpdater t =
-                      I.insert val (TrieNode ix t) currentTrie
-              in
-              (lzwOutputIndex, nextReadIndex, tableUpdater <$> newTable)
-
-          Nothing | index == maxi -> (prevIndex, index, Nothing)
-                  | otherwise -> (prevIndex, index, Just $ I.insert val newNode currentTrie)
-
-      where val = fromIntegral $ vector `V.unsafeIndex` index
-            newNode = emptyNode { trieIndex = freeIndex }
-
-lzwEncode :: Int -> V.Vector Word8 -> L.ByteString
-lzwEncode initialKeySize vec = runST $ do
-    bitWriter <- newWriteStateRef 
-
-    let updateCodeSize 12 writeIdx _
-            | writeIdx == 2 ^ (12 :: Int) - 1 = do
-               writeBitsGif bitWriter (fromIntegral clearCode) 12
-               return (startCodeSize, firstFreeIndex, initialTrie)
-
-        updateCodeSize codeSize writeIdx trie
-            | writeIdx == 2 ^ codeSize =
-                return (codeSize + 1, writeIdx + 1, trie)
-            | otherwise = return (codeSize, writeIdx + 1, trie)
-
-        go readIndex (codeSize, _, _) | readIndex >= maxi =
-            writeBitsGif bitWriter (fromIntegral endOfInfo) codeSize
-        go !readIndex (!codeSize, !writeIndex, !trie) = do
-            let (indexToWrite, endIndex, trie') =
-                    lookuper writeIndex readIndex trie
-            writeBitsGif bitWriter (fromIntegral indexToWrite) codeSize
-            updateCodeSize codeSize writeIndex trie'
-                >>= go endIndex 
-
-    writeBitsGif bitWriter (fromIntegral clearCode) startCodeSize
-    go 0 (startCodeSize, firstFreeIndex, initialTrie)
-
-    finalizeBoolWriterGif bitWriter
-  where
-    maxi = V.length vec
-
-    startCodeSize = initialKeySize + 1
-
-    clearCode = 2 ^ initialKeySize :: Int
-    endOfInfo = clearCode + 1
-    firstFreeIndex = endOfInfo + 1
-    
-    lookuper = lookupUpdate vec
+{-# LANGUAGE BangPatterns, CPP #-}
+module Codec.Picture.Gif.Internal.LZWEncoding( lzwEncode ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>) )
+import Data.Monoid( mempty )
+#endif
+
+import Control.Monad.ST( runST )
+import qualified Data.ByteString.Lazy as L
+import Data.Maybe( fromMaybe )
+import Data.Word( Word8 )
+
+#if MIN_VERSION_containers(0,5,0)
+import qualified Data.IntMap.Strict as I
+#else
+import qualified Data.IntMap as I
+#endif
+import qualified Data.Vector.Storable as V
+
+import Codec.Picture.BitWriter
+
+type Trie = I.IntMap TrieNode
+
+data TrieNode = TrieNode
+    { trieIndex :: {-# UNPACK #-} !Int
+    , trieSub   :: !Trie
+    }
+
+emptyNode :: TrieNode
+emptyNode = TrieNode
+    { trieIndex = -1
+    , trieSub = mempty
+    }
+
+initialTrie :: Trie
+initialTrie = I.fromList
+    [(i, emptyNode { trieIndex = i }) | i <- [0 .. 255]]
+
+lookupUpdate :: V.Vector Word8 -> Int -> Int -> Trie -> (Int, Int, Trie)
+lookupUpdate vector freeIndex firstIndex trie =
+    matchUpdate $ go trie 0 firstIndex 
+  where
+    matchUpdate (lzwOutputIndex, nextReadIndex, sub) =
+        (lzwOutputIndex, nextReadIndex, fromMaybe trie sub)
+
+    maxi = V.length vector
+    go !currentTrie !prevIndex !index
+      | index >= maxi = (prevIndex, index, Nothing)
+      | otherwise = case I.lookup val currentTrie of
+          Just (TrieNode ix subTable) ->
+              let (lzwOutputIndex, nextReadIndex, newTable) =
+                        go subTable ix $ index + 1
+                  tableUpdater t =
+                      I.insert val (TrieNode ix t) currentTrie
+              in
+              (lzwOutputIndex, nextReadIndex, tableUpdater <$> newTable)
+
+          Nothing | index == maxi -> (prevIndex, index, Nothing)
+                  | otherwise -> (prevIndex, index, Just $ I.insert val newNode currentTrie)
+
+      where val = fromIntegral $ vector `V.unsafeIndex` index
+            newNode = emptyNode { trieIndex = freeIndex }
+
+lzwEncode :: Int -> V.Vector Word8 -> L.ByteString
+lzwEncode initialKeySize vec = runST $ do
+    bitWriter <- newWriteStateRef 
+
+    let updateCodeSize 12 writeIdx _
+            | writeIdx == 2 ^ (12 :: Int) - 1 = do
+               writeBitsGif bitWriter (fromIntegral clearCode) 12
+               return (startCodeSize, firstFreeIndex, initialTrie)
+
+        updateCodeSize codeSize writeIdx trie
+            | writeIdx == 2 ^ codeSize =
+                return (codeSize + 1, writeIdx + 1, trie)
+            | otherwise = return (codeSize, writeIdx + 1, trie)
+
+        go readIndex (codeSize, _, _) | readIndex >= maxi =
+            writeBitsGif bitWriter (fromIntegral endOfInfo) codeSize
+        go !readIndex (!codeSize, !writeIndex, !trie) = do
+            let (indexToWrite, endIndex, trie') =
+                    lookuper writeIndex readIndex trie
+            writeBitsGif bitWriter (fromIntegral indexToWrite) codeSize
+            updateCodeSize codeSize writeIndex trie'
+                >>= go endIndex 
+
+    writeBitsGif bitWriter (fromIntegral clearCode) startCodeSize
+    go 0 (startCodeSize, firstFreeIndex, initialTrie)
+
+    finalizeBoolWriterGif bitWriter
+  where
+    maxi = V.length vec
+
+    startCodeSize = initialKeySize + 1
+
+    clearCode = 2 ^ initialKeySize :: Int
+    endOfInfo = clearCode + 1
+    firstFreeIndex = endOfInfo + 1
+    
+    lookuper = lookupUpdate vec
diff --git a/src/Codec/Picture/HDR.hs b/src/Codec/Picture/HDR.hs
--- a/src/Codec/Picture/HDR.hs
+++ b/src/Codec/Picture/HDR.hs
@@ -1,534 +1,534 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE TupleSections   #-}
--- | Module dedicated of Radiance file decompression (.hdr or .pic) file.
--- Radiance file format is used for High dynamic range imaging.
-module Codec.Picture.HDR( decodeHDR
-                        , decodeHDRWithMetadata
-                        , encodeHDR
-                        , encodeRawHDR
-                        , encodeRLENewStyleHDR
-                        , writeHDR
-                        , writeRLENewStyleHDR
-                        ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure, (<*>), (<$>) )
-#endif
-
-import Data.Bits( Bits, (.&.), (.|.), unsafeShiftL, unsafeShiftR )
-import Data.Char( ord, chr, isDigit )
-import Data.Word( Word8 )
-
-#if !MIN_VERSION_base(4,11,0)
-import Data.Monoid( (<>) )
-#endif
-
-import Control.Monad( when, foldM, foldM_, forM, forM_, unless )
-import Control.Monad.Trans.Class( lift )
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as L
-import qualified Data.ByteString.Char8 as BC
-
-import Data.List( partition )
-import Data.Binary( Binary( .. ), encode )
-import Data.Binary.Get( Get, getByteString, getWord8 )
-import Data.Binary.Put( putByteString, putLazyByteString )
-
-import Control.Monad.ST( ST, runST )
-import Foreign.Storable ( Storable )
-import Control.Monad.Primitive ( PrimState, PrimMonad )
-import qualified Data.Vector.Storable as V
-import qualified Data.Vector.Storable.Mutable as M
-
-import Codec.Picture.Metadata( Metadatas
-                             , SourceFormat( SourceHDR )
-                             , basicMetadata )
-import Codec.Picture.InternalHelper
-import Codec.Picture.Types
-import Codec.Picture.VectorByteConversion
-
-#if MIN_VERSION_transformers(0, 4, 0)
-import Control.Monad.Trans.Except( ExceptT, throwE, runExceptT )
-#else
--- Transfomers 0.3 compat
-import Control.Monad.Trans.Error( Error, ErrorT, throwError, runErrorT )
-
-type ExceptT = ErrorT
-
-throwE :: (Monad m, Error e) => e -> ErrorT e m a
-throwE = throwError
-
-runExceptT :: ErrorT e m a -> m (Either e a)
-runExceptT = runErrorT
-#endif
-
-{-# INLINE (.<<.) #-}
-(.<<.), (.>>.) :: (Bits a) => a -> Int -> a
-(.<<.) = unsafeShiftL
-(.>>.) = unsafeShiftR
-
-{-# INLINE (.<-.) #-}
-(.<-.) :: (PrimMonad m, Storable a)
-       => M.STVector (PrimState m) a -> Int -> a -> m ()
-(.<-.) = M.write 
-         {-M.unsafeWrite-}
-
-type HDRReader s a = ExceptT String (ST s) a
-
-data RGBE = RGBE !Word8 !Word8 !Word8 !Word8
-
-instance Binary RGBE where
-    put (RGBE r g b e) = put r >> put g >> put b >> put e
-    get = RGBE <$> get <*> get <*> get <*> get
-
-checkLineLength :: RGBE -> Int
-checkLineLength (RGBE _ _ a b) =
-    (fromIntegral a .<<. 8) .|. fromIntegral b
-
-isNewRunLengthMarker :: RGBE -> Bool
-isNewRunLengthMarker (RGBE 2 2 _ _) = True
-isNewRunLengthMarker _ = False
-
-data RadianceFormat =
-      FormatRGBE
-    | FormatXYZE
-
-radiance32bitRleRGBEFormat, radiance32bitRleXYZEFromat :: B.ByteString
-radiance32bitRleRGBEFormat = BC.pack "32-bit_rle_rgbe"
-radiance32bitRleXYZEFromat = BC.pack "32-bit_rle_xyze"
-
-instance Binary RadianceFormat where
-  put FormatRGBE = putByteString radiance32bitRleRGBEFormat
-  put FormatXYZE = putByteString radiance32bitRleXYZEFromat
-
-  get = getByteString (B.length radiance32bitRleRGBEFormat) >>= format
-    where format sig
-            | sig == radiance32bitRleRGBEFormat = pure FormatRGBE
-            | sig == radiance32bitRleXYZEFromat = pure FormatXYZE
-            | otherwise = fail "Unrecognized Radiance format"
-
-toRGBE :: PixelRGBF -> RGBE
-toRGBE (PixelRGBF r g b)
-    | d <= 1e-32 = RGBE 0 0 0 0
-    | otherwise = RGBE (fix r) (fix g) (fix b) (fromIntegral $ e + 128)
-  where d = maximum [r, g, b]
-        e = exponent d
-        coeff = significand d *  255.9999 / d
-        fix v = truncate $ v * coeff
-
-
-dropUntil :: Word8 -> Get ()
-dropUntil c = getWord8 >>= inner
-  where inner val | val == c = pure ()
-        inner _ = getWord8 >>= inner
-
-getUntil :: (Word8 -> Bool) -> B.ByteString -> Get B.ByteString
-getUntil f initialAcc = getWord8 >>= inner initialAcc
-  where inner acc c | f c = pure acc
-        inner acc c = getWord8 >>= inner (B.snoc acc c)
-
-data RadianceHeader = RadianceHeader
-  { radianceInfos :: [(B.ByteString, B.ByteString)]
-  , radianceFormat :: RadianceFormat
-  , radianceHeight :: !Int
-  , radianceWidth  :: !Int
-  , radianceData   :: L.ByteString
-  }
-
-radianceFileSignature :: B.ByteString
-radianceFileSignature = BC.pack "#?RADIANCE\n"
-
-unpackColor :: L.ByteString -> Int -> RGBE
-unpackColor str idx = RGBE (at 0) (at 1) (at 2) (at 3)
-  where at n = L.index str . fromIntegral $ idx + n
-
-storeColor :: M.STVector s Word8 -> Int -> RGBE -> ST s ()
-storeColor vec idx (RGBE r g b e) = do
-    (vec .<-. (idx + 0)) r
-    (vec .<-. (idx + 1)) g
-    (vec .<-. (idx + 2)) b
-    (vec .<-. (idx + 3)) e
-
-parsePair :: Char -> Get (B.ByteString, B.ByteString)
-parsePair firstChar = do
-    let eol c = c == fromIntegral (ord '\n')
-    line <- getUntil eol B.empty
-    case BC.split '=' line of
-      [] -> pure (BC.singleton firstChar, B.empty)
-      [val] -> pure (BC.singleton firstChar, val)
-      [key, val] -> pure (BC.singleton firstChar <> key, val)
-      (key : vals) -> pure (BC.singleton firstChar <> key, B.concat vals)
-
-decodeInfos :: Get [(B.ByteString, B.ByteString)]
-decodeInfos = do
-    char <- getChar8
-    case char of
-      -- comment
-      '#' -> dropUntil (fromIntegral $ ord '\n') >> decodeInfos
-      -- end of header, no more information
-      '\n' -> pure []
-      -- Classical parsing
-      c -> (:) <$> parsePair c <*> decodeInfos
-
-
--- | Decode an HDR (radiance) image, the resulting image can be:
---
---  * 'ImageRGBF'
---
-decodeHDR :: B.ByteString -> Either String DynamicImage
-decodeHDR = fmap fst . decodeHDRWithMetadata
-
--- | Equivalent to decodeHDR but with aditional metadatas.
-decodeHDRWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
-decodeHDRWithMetadata str = runST $ runExceptT $
-  case runGet decodeHeader $ L.fromChunks [str] of
-    Left err -> throwE err
-    Right rez ->
-      let meta = basicMetadata SourceHDR (abs $ radianceWidth rez) (abs $ radianceHeight rez) in
-      (, meta) . ImageRGBF <$> (decodeRadiancePicture rez >>= lift . unsafeFreezeImage)
-
-getChar8 :: Get Char
-getChar8 = chr . fromIntegral <$> getWord8
-
-isSign :: Char -> Bool
-isSign c = c == '+' || c == '-'
-
-isAxisLetter :: Char -> Bool
-isAxisLetter c = c == 'X' || c == 'Y'
-
-decodeNum :: Get Int
-decodeNum = do
-    sign <- getChar8
-    letter <- getChar8
-    space <- getChar8
-
-    unless (isSign sign && isAxisLetter letter && space == ' ')
-           (fail "Invalid radiance size declaration")
-
-    let numDec acc c | isDigit c =
-            getChar8 >>= numDec (acc * 10 + ord c - ord '0')
-        numDec acc _
-            | sign == '-' = pure $ negate acc
-            | otherwise = pure acc
-
-    getChar8 >>= numDec 0
-
-copyPrevColor :: M.STVector s Word8 -> Int -> ST s ()
-copyPrevColor scanLine idx = do
-    r <- scanLine `M.unsafeRead` (idx - 4)
-    g <- scanLine `M.unsafeRead` (idx - 3)
-    b <- scanLine `M.unsafeRead` (idx - 2)
-    e <- scanLine `M.unsafeRead` (idx - 1)
-
-    (scanLine `M.unsafeWrite` (idx + 0)) r
-    (scanLine `M.unsafeWrite` (idx + 1)) g
-    (scanLine `M.unsafeWrite` (idx + 2)) b
-    (scanLine `M.unsafeWrite` (idx + 3)) e
-
-oldStyleRLE :: L.ByteString -> Int -> M.STVector s Word8
-            -> HDRReader s Int
-oldStyleRLE inputData initialIdx scanLine = inner initialIdx 0 0
-  where maxOutput = M.length scanLine
-        maxInput = fromIntegral $ L.length inputData
-
-        inner readIdx writeIdx _
-            | readIdx >= maxInput || writeIdx >= maxOutput = pure readIdx
-        inner readIdx writeIdx shift = do
-          let color@(RGBE r g b e) = unpackColor inputData readIdx
-              isRun = r == 1 && g == 1 && b == 1
-
-          if not isRun
-            then do
-              lift $ storeColor scanLine writeIdx color
-              inner (readIdx + 4) (writeIdx + 4) 0
-         
-            else do
-              let count = fromIntegral e .<<. shift
-              lift $ forM_ [0 .. count] $ \i -> copyPrevColor scanLine (writeIdx + 4 * i)
-              inner (readIdx + 4) (writeIdx + 4 * count) (shift + 8)
-
-newStyleRLE :: L.ByteString -> Int -> M.STVector s Word8
-            -> HDRReader s Int
-newStyleRLE inputData initialIdx scanline = foldM inner initialIdx [0 .. 3]
-  where dataAt idx
-            | fromIntegral idx >= maxInput = throwE $ "Read index out of bound (" ++ show idx ++ ")"
-            | otherwise = pure $ L.index inputData (fromIntegral idx)
-
-        maxOutput = M.length scanline
-        maxInput = fromIntegral $ L.length inputData
-        stride = 4
-
-
-        strideSet count destIndex _ | endIndex > maxOutput + stride =
-          throwE $ "Out of bound HDR scanline " ++ show endIndex ++ " (max " ++ show maxOutput ++ ")"
-            where endIndex = destIndex + count * stride
-        strideSet count destIndex val = aux destIndex count
-            where aux i 0 =  pure i
-                  aux i c = do
-                    lift $ (scanline .<-. i) val
-                    aux (i + stride) (c - 1)
-
-
-        strideCopy _ count destIndex
-            | writeEndBound > maxOutput + stride = throwE "Out of bound HDR scanline"
-                where writeEndBound = destIndex + count * stride
-        strideCopy sourceIndex count destIndex = aux sourceIndex destIndex count
-          where aux _ j 0 = pure j
-                aux i j c = do
-                    val <- dataAt i
-                    lift $ (scanline .<-. j) val
-                    aux (i + 1) (j + stride) (c - 1)
-
-        inner readIdx writeIdx
-            | readIdx >= maxInput || writeIdx >= maxOutput = pure readIdx
-        inner readIdx writeIdx = do
-          code <- dataAt readIdx
-          if code > 128
-            then do
-              let repeatCount = fromIntegral code .&. 0x7F
-              newVal <- dataAt $ readIdx + 1
-              endIndex <- strideSet repeatCount writeIdx newVal
-              inner (readIdx + 2) endIndex 
-
-            else do
-              let iCode = fromIntegral code
-              endIndex <- strideCopy (readIdx + 1) iCode writeIdx
-              inner (readIdx + iCode + 1) endIndex
-
-instance Binary RadianceHeader where
-    get = decodeHeader
-    put hdr = do
-        putByteString radianceFileSignature
-        putByteString $ BC.pack "FORMAT="
-        put $ radianceFormat hdr
-        let sizeString =
-              BC.pack $ "\n\n-Y " ++ show (radianceHeight hdr)
-                        ++ " +X " ++ show (radianceWidth hdr) ++ "\n"
-        putByteString sizeString
-        putLazyByteString $ radianceData hdr
-
-
-decodeHeader :: Get RadianceHeader
-decodeHeader = do
-    sig <- getByteString $ B.length radianceFileSignature
-    when (sig /= radianceFileSignature)
-         (fail "Invalid radiance file signature")
-
-    infos <- decodeInfos
-    let formatKey = BC.pack "FORMAT"
-    case partition (\(k,_) -> k /= formatKey) infos of
-      (_, []) -> fail "No radiance format specified"
-      (info, [(_, formatString)]) ->
-        case runGet get $ L.fromChunks [formatString] of
-          Left err -> fail err
-          Right format -> do
-              (n1, n2, b) <- (,,) <$> decodeNum
-                                  <*> decodeNum
-                                  <*> getRemainingBytes
-              return . RadianceHeader info format n1 n2 $ L.fromChunks [b]
-
-      _ -> fail "Multiple radiance format specified"
-
-toFloat :: RGBE -> PixelRGBF
-toFloat (RGBE r g b e) = PixelRGBF rf gf bf
-  where f = encodeFloat 1 $ fromIntegral e - (128 + 8)
-        rf = (fromIntegral r + 0.0) * f
-        gf = (fromIntegral g + 0.0) * f
-        bf = (fromIntegral b + 0.0) * f
-
-encodeScanlineColor :: M.STVector s Word8
-                    -> M.STVector s Word8
-                    -> Int
-                    -> ST s Int
-encodeScanlineColor vec outVec outIdx = do
-    val <- vec `M.unsafeRead` 0
-    runLength 1 0 val 1 outIdx
-  where maxIndex = M.length vec
-
-        pushRun len val at = do
-            (outVec `M.unsafeWrite` at) $ fromIntegral $ len .|. 0x80
-            (outVec `M.unsafeWrite` (at + 1)) val
-            return $ at + 2
-
-        pushData start len at = do
-            (outVec `M.unsafeWrite` at) $ fromIntegral len
-            let first = start - len
-                end = start - 1
-                offset = at - first + 1
-            forM_ [first .. end] $ \i -> do
-                v <- vec `M.unsafeRead` i
-                (outVec `M.unsafeWrite` (offset + i)) v
-
-            return $ at + len + 1
-
-        -- End of scanline, empty the thing
-        runLength run cpy prev idx at | idx >= maxIndex =
-            case (run, cpy) of
-                (0, 0) -> pure at
-                (0, n) -> pushData idx n at
-                (n, 0) -> pushRun n prev at
-                (_, _) -> error "HDR - Run length algorithm is wrong"
-
-        -- full runlength, we must write the packet
-        runLength r@127   _ prev idx at = do
-            val <- vec `M.unsafeRead` idx
-            pushRun r prev at >>=
-                runLength 1 0 val (idx + 1)
-
-        -- full copy, we must write the packet
-        runLength   _ c@127    _ idx at = do
-            val <- vec `M.unsafeRead` idx
-            pushData idx c at >>=
-                runLength 1 0 val (idx + 1)
-
-        runLength n 0 prev idx at = do
-            val <- vec `M.unsafeRead` idx
-            case val == prev of
-               True -> runLength (n + 1) 0 prev (idx + 1) at
-               False | n < 4 -> runLength 0 (n + 1) val (idx + 1) at
-               False ->
-                    pushRun n prev at >>=
-                        runLength 1 0 val (idx + 1)
-
-        runLength 0 n prev idx at = do
-            val <- vec `M.unsafeRead` idx
-            if val /= prev
-               then runLength 0 (n + 1) val (idx + 1) at
-               else
-                pushData (idx - 1) (n - 1) at >>=
-                    runLength (2 :: Int) 0 val (idx + 1)
-
-        runLength _ _ _ _ _ =
-            error "HDR RLE inconsistent state"
-
--- | Write an High dynamic range image into a radiance
--- image file on disk.
-writeHDR :: FilePath -> Image PixelRGBF -> IO ()
-writeHDR filename img = L.writeFile filename $ encodeHDR img
-
--- | Write a RLE encoded High dynamic range image into a radiance
--- image file on disk.
-writeRLENewStyleHDR :: FilePath -> Image PixelRGBF -> IO ()
-writeRLENewStyleHDR filename img =
-    L.writeFile filename $ encodeRLENewStyleHDR img
-
--- | Encode an High dynamic range image into a radiance image
--- file format.
--- Alias for encodeRawHDR
-encodeHDR :: Image PixelRGBF -> L.ByteString
-encodeHDR = encodeRawHDR
-
--- | Encode an High dynamic range image into a radiance image
--- file format. without compression
-encodeRawHDR :: Image PixelRGBF -> L.ByteString
-encodeRawHDR pic = encode descriptor
-  where
-    newImage = pixelMap rgbeInRgba pic
-    -- we are cheating to death here, the layout we want
-    -- correspond to the layout of pixelRGBA8, so we
-    -- convert
-    rgbeInRgba pixel = PixelRGBA8 r g b e
-      where RGBE r g b e = toRGBE pixel
-
-    descriptor = RadianceHeader
-        { radianceInfos = []
-        , radianceFormat = FormatRGBE
-        , radianceHeight = imageHeight pic
-        , radianceWidth  = imageWidth pic
-        , radianceData = L.fromChunks [toByteString $ imageData newImage]
-        }
-
-
--- | Encode an High dynamic range image into a radiance image
--- file format using a light RLE compression. Some problems
--- seem to arise with some image viewer.
-encodeRLENewStyleHDR :: Image PixelRGBF -> L.ByteString
-encodeRLENewStyleHDR pic = encode $ runST $ do
-    let w = imageWidth pic
-        h = imageHeight pic
-
-    scanLineR <- M.new w :: ST s (M.STVector s Word8)
-    scanLineG <- M.new w
-    scanLineB <- M.new w
-    scanLineE <- M.new w
-
-    encoded <-
-        forM [0 .. h - 1] $ \line -> do
-            buff <- M.new $ w * 4 + w `div` 127 + 2
-            let columner col | col >= w = return ()
-                columner col = do
-                      let RGBE r g b e = toRGBE $ pixelAt pic col line
-                      (scanLineR `M.unsafeWrite` col) r
-                      (scanLineG `M.unsafeWrite` col) g
-                      (scanLineB `M.unsafeWrite` col) b
-                      (scanLineE `M.unsafeWrite` col) e
-
-                      columner (col + 1)
-
-            columner 0
-
-            (buff `M.unsafeWrite` 0) 2
-            (buff `M.unsafeWrite` 1) 2
-            (buff `M.unsafeWrite` 2) $ fromIntegral ((w .>>. 8) .&. 0xFF)
-            (buff `M.unsafeWrite` 3) $ fromIntegral (w .&. 0xFF)
-
-            i1 <- encodeScanlineColor scanLineR buff 4        
-            i2 <- encodeScanlineColor scanLineG buff i1
-            i3 <- encodeScanlineColor scanLineB buff i2
-            endIndex <- encodeScanlineColor scanLineE buff i3
-
-            (\v -> blitVector v 0 endIndex) <$> V.unsafeFreeze buff
-
-    pure RadianceHeader
-        { radianceInfos = []
-        , radianceFormat = FormatRGBE
-        , radianceHeight = h
-        , radianceWidth  = w
-        , radianceData = L.fromChunks encoded 
-        }
-    
-
-decodeRadiancePicture :: RadianceHeader -> HDRReader s (MutableImage s PixelRGBF)
-decodeRadiancePicture hdr = do
-    let width = abs $ radianceWidth hdr
-        height = abs $ radianceHeight hdr
-        packedData = radianceData hdr
-
-    scanLine <- lift $ M.new $ width * 4
-    resultBuffer <- lift $ M.new $ width * height * 3
-
-    let scanLineImage = MutableImage
-                      { mutableImageWidth = width
-                      , mutableImageHeight = 1
-                      , mutableImageData = scanLine
-                      }
-
-        finalImage = MutableImage
-                   { mutableImageWidth = width
-                   , mutableImageHeight = height
-                   , mutableImageData = resultBuffer
-                   }
-
-    let scanLineExtractor readIdx line = do
-          let color = unpackColor packedData readIdx
-              inner | isNewRunLengthMarker color = do
-                          let calcSize = checkLineLength color
-                          when (calcSize /= width)
-                               (throwE "Invalid sanline size")
-                          pure $ \idx -> newStyleRLE packedData (idx + 4)
-                    | otherwise = pure $ oldStyleRLE packedData
-          f <- inner
-          newRead <- f readIdx scanLine
-          forM_ [0 .. width - 1] $ \i -> do
-              -- mokay, it's a hack, but I don't want to define a
-              -- pixel instance of RGBE...
-              PixelRGBA8 r g b e <- lift $ readPixel scanLineImage i 0
-              lift $ writePixel finalImage i line . toFloat $ RGBE r g b e
-
-          return newRead
-
-    foldM_ scanLineExtractor 0 [0 .. height - 1]
-
-    return finalImage
-
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE TupleSections   #-}
+-- | Module dedicated of Radiance file decompression (.hdr or .pic) file.
+-- Radiance file format is used for High dynamic range imaging.
+module Codec.Picture.HDR( decodeHDR
+                        , decodeHDRWithMetadata
+                        , encodeHDR
+                        , encodeRawHDR
+                        , encodeRLENewStyleHDR
+                        , writeHDR
+                        , writeRLENewStyleHDR
+                        ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure, (<*>), (<$>) )
+#endif
+
+import Data.Bits( Bits, (.&.), (.|.), unsafeShiftL, unsafeShiftR )
+import Data.Char( ord, chr, isDigit )
+import Data.Word( Word8 )
+
+#if !MIN_VERSION_base(4,11,0)
+import Data.Monoid( (<>) )
+#endif
+
+import Control.Monad( when, foldM, foldM_, forM, forM_, unless )
+import Control.Monad.Trans.Class( lift )
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as L
+import qualified Data.ByteString.Char8 as BC
+
+import Data.List( partition )
+import Data.Binary( Binary( .. ), encode )
+import Data.Binary.Get( Get, getByteString, getWord8 )
+import Data.Binary.Put( putByteString, putLazyByteString )
+
+import Control.Monad.ST( ST, runST )
+import Foreign.Storable ( Storable )
+import Control.Monad.Primitive ( PrimState, PrimMonad )
+import qualified Data.Vector.Storable as V
+import qualified Data.Vector.Storable.Mutable as M
+
+import Codec.Picture.Metadata( Metadatas
+                             , SourceFormat( SourceHDR )
+                             , basicMetadata )
+import Codec.Picture.InternalHelper
+import Codec.Picture.Types
+import Codec.Picture.VectorByteConversion
+
+#if MIN_VERSION_transformers(0, 4, 0)
+import Control.Monad.Trans.Except( ExceptT, throwE, runExceptT )
+#else
+-- Transformers 0.3 compat
+import Control.Monad.Trans.Error( Error, ErrorT, throwError, runErrorT )
+
+type ExceptT = ErrorT
+
+throwE :: (Monad m, Error e) => e -> ErrorT e m a
+throwE = throwError
+
+runExceptT :: ErrorT e m a -> m (Either e a)
+runExceptT = runErrorT
+#endif
+
+{-# INLINE (.<<.) #-}
+(.<<.), (.>>.) :: (Bits a) => a -> Int -> a
+(.<<.) = unsafeShiftL
+(.>>.) = unsafeShiftR
+
+{-# INLINE (.<-.) #-}
+(.<-.) :: (PrimMonad m, Storable a)
+       => M.STVector (PrimState m) a -> Int -> a -> m ()
+(.<-.) = M.write 
+         {-M.unsafeWrite-}
+
+type HDRReader s a = ExceptT String (ST s) a
+
+data RGBE = RGBE !Word8 !Word8 !Word8 !Word8
+
+instance Binary RGBE where
+    put (RGBE r g b e) = put r >> put g >> put b >> put e
+    get = RGBE <$> get <*> get <*> get <*> get
+
+checkLineLength :: RGBE -> Int
+checkLineLength (RGBE _ _ a b) =
+    (fromIntegral a .<<. 8) .|. fromIntegral b
+
+isNewRunLengthMarker :: RGBE -> Bool
+isNewRunLengthMarker (RGBE 2 2 _ _) = True
+isNewRunLengthMarker _ = False
+
+data RadianceFormat =
+      FormatRGBE
+    | FormatXYZE
+
+radiance32bitRleRGBEFormat, radiance32bitRleXYZEFromat :: B.ByteString
+radiance32bitRleRGBEFormat = BC.pack "32-bit_rle_rgbe"
+radiance32bitRleXYZEFromat = BC.pack "32-bit_rle_xyze"
+
+instance Binary RadianceFormat where
+  put FormatRGBE = putByteString radiance32bitRleRGBEFormat
+  put FormatXYZE = putByteString radiance32bitRleXYZEFromat
+
+  get = getByteString (B.length radiance32bitRleRGBEFormat) >>= format
+    where format sig
+            | sig == radiance32bitRleRGBEFormat = pure FormatRGBE
+            | sig == radiance32bitRleXYZEFromat = pure FormatXYZE
+            | otherwise = fail "Unrecognized Radiance format"
+
+toRGBE :: PixelRGBF -> RGBE
+toRGBE (PixelRGBF r g b)
+    | d <= 1e-32 = RGBE 0 0 0 0
+    | otherwise = RGBE (fix r) (fix g) (fix b) (fromIntegral $ e + 128)
+  where d = maximum [r, g, b]
+        e = exponent d
+        coeff = significand d *  255.9999 / d
+        fix v = truncate $ v * coeff
+
+
+dropUntil :: Word8 -> Get ()
+dropUntil c = getWord8 >>= inner
+  where inner val | val == c = pure ()
+        inner _ = getWord8 >>= inner
+
+getUntil :: (Word8 -> Bool) -> B.ByteString -> Get B.ByteString
+getUntil f initialAcc = getWord8 >>= inner initialAcc
+  where inner acc c | f c = pure acc
+        inner acc c = getWord8 >>= inner (B.snoc acc c)
+
+data RadianceHeader = RadianceHeader
+  { radianceInfos :: [(B.ByteString, B.ByteString)]
+  , radianceFormat :: RadianceFormat
+  , radianceHeight :: !Int
+  , radianceWidth  :: !Int
+  , radianceData   :: L.ByteString
+  }
+
+radianceFileSignature :: B.ByteString
+radianceFileSignature = BC.pack "#?RADIANCE\n"
+
+unpackColor :: L.ByteString -> Int -> RGBE
+unpackColor str idx = RGBE (at 0) (at 1) (at 2) (at 3)
+  where at n = L.index str . fromIntegral $ idx + n
+
+storeColor :: M.STVector s Word8 -> Int -> RGBE -> ST s ()
+storeColor vec idx (RGBE r g b e) = do
+    (vec .<-. (idx + 0)) r
+    (vec .<-. (idx + 1)) g
+    (vec .<-. (idx + 2)) b
+    (vec .<-. (idx + 3)) e
+
+parsePair :: Char -> Get (B.ByteString, B.ByteString)
+parsePair firstChar = do
+    let eol c = c == fromIntegral (ord '\n')
+    line <- getUntil eol B.empty
+    case BC.split '=' line of
+      [] -> pure (BC.singleton firstChar, B.empty)
+      [val] -> pure (BC.singleton firstChar, val)
+      [key, val] -> pure (BC.singleton firstChar <> key, val)
+      (key : vals) -> pure (BC.singleton firstChar <> key, B.concat vals)
+
+decodeInfos :: Get [(B.ByteString, B.ByteString)]
+decodeInfos = do
+    char <- getChar8
+    case char of
+      -- comment
+      '#' -> dropUntil (fromIntegral $ ord '\n') >> decodeInfos
+      -- end of header, no more information
+      '\n' -> pure []
+      -- Classical parsing
+      c -> (:) <$> parsePair c <*> decodeInfos
+
+
+-- | Decode an HDR (radiance) image, the resulting image can be:
+--
+--  * 'ImageRGBF'
+--
+decodeHDR :: B.ByteString -> Either String DynamicImage
+decodeHDR = fmap fst . decodeHDRWithMetadata
+
+-- | Equivalent to decodeHDR but with additional metadatas.
+decodeHDRWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
+decodeHDRWithMetadata str = runST $ runExceptT $
+  case runGet decodeHeader $ L.fromChunks [str] of
+    Left err -> throwE err
+    Right rez ->
+      let meta = basicMetadata SourceHDR (abs $ radianceWidth rez) (abs $ radianceHeight rez) in
+      (, meta) . ImageRGBF <$> (decodeRadiancePicture rez >>= lift . unsafeFreezeImage)
+
+getChar8 :: Get Char
+getChar8 = chr . fromIntegral <$> getWord8
+
+isSign :: Char -> Bool
+isSign c = c == '+' || c == '-'
+
+isAxisLetter :: Char -> Bool
+isAxisLetter c = c == 'X' || c == 'Y'
+
+decodeNum :: Get Int
+decodeNum = do
+    sign <- getChar8
+    letter <- getChar8
+    space <- getChar8
+
+    unless (isSign sign && isAxisLetter letter && space == ' ')
+           (fail "Invalid radiance size declaration")
+
+    let numDec acc c | isDigit c =
+            getChar8 >>= numDec (acc * 10 + ord c - ord '0')
+        numDec acc _
+            | sign == '-' = pure $ negate acc
+            | otherwise = pure acc
+
+    getChar8 >>= numDec 0
+
+copyPrevColor :: M.STVector s Word8 -> Int -> ST s ()
+copyPrevColor scanLine idx = do
+    r <- scanLine `M.unsafeRead` (idx - 4)
+    g <- scanLine `M.unsafeRead` (idx - 3)
+    b <- scanLine `M.unsafeRead` (idx - 2)
+    e <- scanLine `M.unsafeRead` (idx - 1)
+
+    (scanLine `M.unsafeWrite` (idx + 0)) r
+    (scanLine `M.unsafeWrite` (idx + 1)) g
+    (scanLine `M.unsafeWrite` (idx + 2)) b
+    (scanLine `M.unsafeWrite` (idx + 3)) e
+
+oldStyleRLE :: L.ByteString -> Int -> M.STVector s Word8
+            -> HDRReader s Int
+oldStyleRLE inputData initialIdx scanLine = inner initialIdx 0 0
+  where maxOutput = M.length scanLine
+        maxInput = fromIntegral $ L.length inputData
+
+        inner readIdx writeIdx _
+            | readIdx >= maxInput || writeIdx >= maxOutput = pure readIdx
+        inner readIdx writeIdx shift = do
+          let color@(RGBE r g b e) = unpackColor inputData readIdx
+              isRun = r == 1 && g == 1 && b == 1
+
+          if not isRun
+            then do
+              lift $ storeColor scanLine writeIdx color
+              inner (readIdx + 4) (writeIdx + 4) 0
+         
+            else do
+              let count = fromIntegral e .<<. shift
+              lift $ forM_ [0 .. count] $ \i -> copyPrevColor scanLine (writeIdx + 4 * i)
+              inner (readIdx + 4) (writeIdx + 4 * count) (shift + 8)
+
+newStyleRLE :: L.ByteString -> Int -> M.STVector s Word8
+            -> HDRReader s Int
+newStyleRLE inputData initialIdx scanline = foldM inner initialIdx [0 .. 3]
+  where dataAt idx
+            | fromIntegral idx >= maxInput = throwE $ "Read index out of bound (" ++ show idx ++ ")"
+            | otherwise = pure $ L.index inputData (fromIntegral idx)
+
+        maxOutput = M.length scanline
+        maxInput = fromIntegral $ L.length inputData
+        stride = 4
+
+
+        strideSet count destIndex _ | endIndex > maxOutput + stride =
+          throwE $ "Out of bound HDR scanline " ++ show endIndex ++ " (max " ++ show maxOutput ++ ")"
+            where endIndex = destIndex + count * stride
+        strideSet count destIndex val = aux destIndex count
+            where aux i 0 =  pure i
+                  aux i c = do
+                    lift $ (scanline .<-. i) val
+                    aux (i + stride) (c - 1)
+
+
+        strideCopy _ count destIndex
+            | writeEndBound > maxOutput + stride = throwE "Out of bound HDR scanline"
+                where writeEndBound = destIndex + count * stride
+        strideCopy sourceIndex count destIndex = aux sourceIndex destIndex count
+          where aux _ j 0 = pure j
+                aux i j c = do
+                    val <- dataAt i
+                    lift $ (scanline .<-. j) val
+                    aux (i + 1) (j + stride) (c - 1)
+
+        inner readIdx writeIdx
+            | readIdx >= maxInput || writeIdx >= maxOutput = pure readIdx
+        inner readIdx writeIdx = do
+          code <- dataAt readIdx
+          if code > 128
+            then do
+              let repeatCount = fromIntegral code .&. 0x7F
+              newVal <- dataAt $ readIdx + 1
+              endIndex <- strideSet repeatCount writeIdx newVal
+              inner (readIdx + 2) endIndex 
+
+            else do
+              let iCode = fromIntegral code
+              endIndex <- strideCopy (readIdx + 1) iCode writeIdx
+              inner (readIdx + iCode + 1) endIndex
+
+instance Binary RadianceHeader where
+    get = decodeHeader
+    put hdr = do
+        putByteString radianceFileSignature
+        putByteString $ BC.pack "FORMAT="
+        put $ radianceFormat hdr
+        let sizeString =
+              BC.pack $ "\n\n-Y " ++ show (radianceHeight hdr)
+                        ++ " +X " ++ show (radianceWidth hdr) ++ "\n"
+        putByteString sizeString
+        putLazyByteString $ radianceData hdr
+
+
+decodeHeader :: Get RadianceHeader
+decodeHeader = do
+    sig <- getByteString $ B.length radianceFileSignature
+    when (sig /= radianceFileSignature)
+         (fail "Invalid radiance file signature")
+
+    infos <- decodeInfos
+    let formatKey = BC.pack "FORMAT"
+    case partition (\(k,_) -> k /= formatKey) infos of
+      (_, []) -> fail "No radiance format specified"
+      (info, [(_, formatString)]) ->
+        case runGet get $ L.fromChunks [formatString] of
+          Left err -> fail err
+          Right format -> do
+              (n1, n2, b) <- (,,) <$> decodeNum
+                                  <*> decodeNum
+                                  <*> getRemainingBytes
+              return . RadianceHeader info format n1 n2 $ L.fromChunks [b]
+
+      _ -> fail "Multiple radiance format specified"
+
+toFloat :: RGBE -> PixelRGBF
+toFloat (RGBE r g b e) = PixelRGBF rf gf bf
+  where f = encodeFloat 1 $ fromIntegral e - (128 + 8)
+        rf = (fromIntegral r + 0.0) * f
+        gf = (fromIntegral g + 0.0) * f
+        bf = (fromIntegral b + 0.0) * f
+
+encodeScanlineColor :: M.STVector s Word8
+                    -> M.STVector s Word8
+                    -> Int
+                    -> ST s Int
+encodeScanlineColor vec outVec outIdx = do
+    val <- vec `M.unsafeRead` 0
+    runLength 1 0 val 1 outIdx
+  where maxIndex = M.length vec
+
+        pushRun len val at = do
+            (outVec `M.unsafeWrite` at) $ fromIntegral $ len .|. 0x80
+            (outVec `M.unsafeWrite` (at + 1)) val
+            return $ at + 2
+
+        pushData start len at = do
+            (outVec `M.unsafeWrite` at) $ fromIntegral len
+            let first = start - len
+                end = start - 1
+                offset = at - first + 1
+            forM_ [first .. end] $ \i -> do
+                v <- vec `M.unsafeRead` i
+                (outVec `M.unsafeWrite` (offset + i)) v
+
+            return $ at + len + 1
+
+        -- End of scanline, empty the thing
+        runLength run cpy prev idx at | idx >= maxIndex =
+            case (run, cpy) of
+                (0, 0) -> pure at
+                (0, n) -> pushData idx n at
+                (n, 0) -> pushRun n prev at
+                (_, _) -> error "HDR - Run length algorithm is wrong"
+
+        -- full runlength, we must write the packet
+        runLength r@127   _ prev idx at = do
+            val <- vec `M.unsafeRead` idx
+            pushRun r prev at >>=
+                runLength 1 0 val (idx + 1)
+
+        -- full copy, we must write the packet
+        runLength   _ c@127    _ idx at = do
+            val <- vec `M.unsafeRead` idx
+            pushData idx c at >>=
+                runLength 1 0 val (idx + 1)
+
+        runLength n 0 prev idx at = do
+            val <- vec `M.unsafeRead` idx
+            case val == prev of
+               True -> runLength (n + 1) 0 prev (idx + 1) at
+               False | n < 4 -> runLength 0 (n + 1) val (idx + 1) at
+               False ->
+                    pushRun n prev at >>=
+                        runLength 1 0 val (idx + 1)
+
+        runLength 0 n prev idx at = do
+            val <- vec `M.unsafeRead` idx
+            if val /= prev
+               then runLength 0 (n + 1) val (idx + 1) at
+               else
+                pushData (idx - 1) (n - 1) at >>=
+                    runLength (2 :: Int) 0 val (idx + 1)
+
+        runLength _ _ _ _ _ =
+            error "HDR RLE inconsistent state"
+
+-- | Write an High dynamic range image into a radiance
+-- image file on disk.
+writeHDR :: FilePath -> Image PixelRGBF -> IO ()
+writeHDR filename img = L.writeFile filename $ encodeHDR img
+
+-- | Write a RLE encoded High dynamic range image into a radiance
+-- image file on disk.
+writeRLENewStyleHDR :: FilePath -> Image PixelRGBF -> IO ()
+writeRLENewStyleHDR filename img =
+    L.writeFile filename $ encodeRLENewStyleHDR img
+
+-- | Encode an High dynamic range image into a radiance image
+-- file format.
+-- Alias for encodeRawHDR
+encodeHDR :: Image PixelRGBF -> L.ByteString
+encodeHDR = encodeRawHDR
+
+-- | Encode an High dynamic range image into a radiance image
+-- file format. without compression
+encodeRawHDR :: Image PixelRGBF -> L.ByteString
+encodeRawHDR pic = encode descriptor
+  where
+    newImage = pixelMap rgbeInRgba pic
+    -- we are cheating to death here, the layout we want
+    -- correspond to the layout of pixelRGBA8, so we
+    -- convert
+    rgbeInRgba pixel = PixelRGBA8 r g b e
+      where RGBE r g b e = toRGBE pixel
+
+    descriptor = RadianceHeader
+        { radianceInfos = []
+        , radianceFormat = FormatRGBE
+        , radianceHeight = imageHeight pic
+        , radianceWidth  = imageWidth pic
+        , radianceData = L.fromChunks [toByteString $ imageData newImage]
+        }
+
+
+-- | Encode an High dynamic range image into a radiance image
+-- file format using a light RLE compression. Some problems
+-- seem to arise with some image viewer.
+encodeRLENewStyleHDR :: Image PixelRGBF -> L.ByteString
+encodeRLENewStyleHDR pic = encode $ runST $ do
+    let w = imageWidth pic
+        h = imageHeight pic
+
+    scanLineR <- M.new w :: ST s (M.STVector s Word8)
+    scanLineG <- M.new w
+    scanLineB <- M.new w
+    scanLineE <- M.new w
+
+    encoded <-
+        forM [0 .. h - 1] $ \line -> do
+            buff <- M.new $ w * 4 + w `div` 127 + 2
+            let columner col | col >= w = return ()
+                columner col = do
+                      let RGBE r g b e = toRGBE $ pixelAt pic col line
+                      (scanLineR `M.unsafeWrite` col) r
+                      (scanLineG `M.unsafeWrite` col) g
+                      (scanLineB `M.unsafeWrite` col) b
+                      (scanLineE `M.unsafeWrite` col) e
+
+                      columner (col + 1)
+
+            columner 0
+
+            (buff `M.unsafeWrite` 0) 2
+            (buff `M.unsafeWrite` 1) 2
+            (buff `M.unsafeWrite` 2) $ fromIntegral ((w .>>. 8) .&. 0xFF)
+            (buff `M.unsafeWrite` 3) $ fromIntegral (w .&. 0xFF)
+
+            i1 <- encodeScanlineColor scanLineR buff 4        
+            i2 <- encodeScanlineColor scanLineG buff i1
+            i3 <- encodeScanlineColor scanLineB buff i2
+            endIndex <- encodeScanlineColor scanLineE buff i3
+
+            (\v -> blitVector v 0 endIndex) <$> V.unsafeFreeze buff
+
+    pure RadianceHeader
+        { radianceInfos = []
+        , radianceFormat = FormatRGBE
+        , radianceHeight = h
+        , radianceWidth  = w
+        , radianceData = L.fromChunks encoded 
+        }
+    
+
+decodeRadiancePicture :: RadianceHeader -> HDRReader s (MutableImage s PixelRGBF)
+decodeRadiancePicture hdr = do
+    let width = abs $ radianceWidth hdr
+        height = abs $ radianceHeight hdr
+        packedData = radianceData hdr
+
+    scanLine <- lift $ M.new $ width * 4
+    resultBuffer <- lift $ M.new $ width * height * 3
+
+    let scanLineImage = MutableImage
+                      { mutableImageWidth = width
+                      , mutableImageHeight = 1
+                      , mutableImageData = scanLine
+                      }
+
+        finalImage = MutableImage
+                   { mutableImageWidth = width
+                   , mutableImageHeight = height
+                   , mutableImageData = resultBuffer
+                   }
+
+    let scanLineExtractor readIdx line = do
+          let color = unpackColor packedData readIdx
+              inner | isNewRunLengthMarker color = do
+                          let calcSize = checkLineLength color
+                          when (calcSize /= width)
+                               (throwE "Invalid sanline size")
+                          pure $ \idx -> newStyleRLE packedData (idx + 4)
+                    | otherwise = pure $ oldStyleRLE packedData
+          f <- inner
+          newRead <- f readIdx scanLine
+          forM_ [0 .. width - 1] $ \i -> do
+              -- mokay, it's a hack, but I don't want to define a
+              -- pixel instance of RGBE...
+              PixelRGBA8 r g b e <- lift $ readPixel scanLineImage i 0
+              lift $ writePixel finalImage i line . toFloat $ RGBE r g b e
+
+          return newRead
+
+    foldM_ scanLineExtractor 0 [0 .. height - 1]
+
+    return finalImage
+
diff --git a/src/Codec/Picture/InternalHelper.hs b/src/Codec/Picture/InternalHelper.hs
--- a/src/Codec/Picture/InternalHelper.hs
+++ b/src/Codec/Picture/InternalHelper.hs
@@ -1,32 +1,32 @@
-{-# LANGUAGE CPP #-}
-module Codec.Picture.InternalHelper ( runGet
-                                    , runGetStrict
-                                    , decode
-                                    , getRemainingBytes
-                                    , getRemainingLazyBytes ) where
-
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as L
-import Data.Binary( Binary( get ) )
-import Data.Binary.Get( Get
-                      , getRemainingLazyByteString
-                      )
-import qualified Data.Binary.Get as G
-
-decode :: (Binary a) => B.ByteString -> Either String a
-decode = runGetStrict get
-
-runGet :: Get a -> L.ByteString -> Either String a
-runGet act = unpack . G.runGetOrFail act
-    where unpack (Left (_, _, str)) = Left str
-          unpack (Right (_, _, element)) = Right element
-
-runGetStrict :: Get a -> B.ByteString -> Either String a
-runGetStrict act buffer = runGet act $ L.fromChunks [buffer]
-
-getRemainingBytes :: Get B.ByteString
-getRemainingBytes = L.toStrict <$> getRemainingLazyByteString
-
-getRemainingLazyBytes :: Get L.ByteString
-getRemainingLazyBytes = getRemainingLazyByteString
-
+{-# LANGUAGE CPP #-}
+module Codec.Picture.InternalHelper ( runGet
+                                    , runGetStrict
+                                    , decode
+                                    , getRemainingBytes
+                                    , getRemainingLazyBytes ) where
+
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as L
+import Data.Binary( Binary( get ) )
+import Data.Binary.Get( Get
+                      , getRemainingLazyByteString
+                      )
+import qualified Data.Binary.Get as G
+
+decode :: (Binary a) => B.ByteString -> Either String a
+decode = runGetStrict get
+
+runGet :: Get a -> L.ByteString -> Either String a
+runGet act = unpack . G.runGetOrFail act
+    where unpack (Left (_, _, str)) = Left str
+          unpack (Right (_, _, element)) = Right element
+
+runGetStrict :: Get a -> B.ByteString -> Either String a
+runGetStrict act buffer = runGet act $ L.fromChunks [buffer]
+
+getRemainingBytes :: Get B.ByteString
+getRemainingBytes = L.toStrict <$> getRemainingLazyByteString
+
+getRemainingLazyBytes :: Get L.ByteString
+getRemainingLazyBytes = getRemainingLazyByteString
+
diff --git a/src/Codec/Picture/Jpg.hs b/src/Codec/Picture/Jpg.hs
--- a/src/Codec/Picture/Jpg.hs
+++ b/src/Codec/Picture/Jpg.hs
@@ -740,7 +740,7 @@
                         }, VS.singleton 0)
       where sizes = VU.fromListN 16 $ map (fromIntegral . length) tableDef
 
--- | Encode an image in jpeg at a reasonnable quality level.
+-- | Encode an image in jpeg at a reasonable quality level.
 -- If you want better quality or reduced file size, you should
 -- use `encodeJpegAtQuality`
 encodeJpeg :: Image PixelYCbCr8 -> L.ByteString
@@ -780,7 +780,7 @@
 
 -- | Record gathering all information to encode a component
 -- from the source image. Previously was a huge tuple
--- burried in the code
+-- buried in the code
 data EncoderState = EncoderState
   { _encComponentIndex :: !Int
   , _encBlockWidth     :: !Int
diff --git a/src/Codec/Picture/Jpg/Internal/Common.hs b/src/Codec/Picture/Jpg/Internal/Common.hs
--- a/src/Codec/Picture/Jpg/Internal/Common.hs
+++ b/src/Codec/Picture/Jpg/Internal/Common.hs
@@ -1,240 +1,240 @@
-{-# LANGUAGE BangPatterns #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE CPP #-}
-module Codec.Picture.Jpg.Internal.Common
-    ( DctCoefficients
-    , JpgUnpackerParameter( .. )
-    , decodeInt
-    , dcCoefficientDecode
-    , deQuantize
-    , decodeRrrrSsss
-    , zigZagReorderForward 
-    , zigZagReorderForwardv
-    , zigZagReorder
-    , inverseDirectCosineTransform
-    , unpackInt
-    , unpackMacroBlock
-    , rasterMap
-    , decodeMacroBlock
-    , decodeRestartInterval
-    , toBlockSize
-    ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure, (<$>) )
-#endif
-
-import Control.Monad( when )
-import Control.Monad.ST( ST, runST )
-import Data.Bits( unsafeShiftL, unsafeShiftR, (.&.) )
-import Data.Int( Int16, Int32 )
-import Data.Maybe( fromMaybe )
-import Data.Word( Word8 )
-import qualified Data.Vector.Storable as VS
-import qualified Data.Vector.Storable.Mutable as M
-import Foreign.Storable ( Storable )
-
-import Codec.Picture.Types
-import Codec.Picture.BitWriter
-import Codec.Picture.Jpg.Internal.Types
-import Codec.Picture.Jpg.Internal.FastIdct
-import Codec.Picture.Jpg.Internal.DefaultTable
-
--- | Same as for DcCoefficient, to provide nicer type signatures
-type DctCoefficients = DcCoefficient
-
-data JpgUnpackerParameter = JpgUnpackerParameter
-    { dcHuffmanTree        :: !HuffmanPackedTree
-    , acHuffmanTree        :: !HuffmanPackedTree
-    , componentIndex       :: {-# UNPACK #-} !Int
-    , restartInterval      :: {-# UNPACK #-} !Int
-    , componentWidth       :: {-# UNPACK #-} !Int
-    , componentHeight      :: {-# UNPACK #-} !Int
-    , subSampling          :: !(Int, Int)
-    , coefficientRange     :: !(Int, Int)
-    , successiveApprox     :: !(Int, Int)
-    , readerIndex          :: {-# UNPACK #-} !Int
-      -- | When in progressive mode, we can have many
-      -- color in a scan or only one. The indices changes
-      -- on this fact, when mixed, there is whole 
-      -- MCU for all color components, spanning multiple
-      -- block lines. With only one color component we use
-      -- the normal raster order.
-    , indiceVector         :: {-# UNPACK #-} !Int
-    , blockIndex           :: {-# UNPACK #-} !Int
-    , blockMcuX            :: {-# UNPACK #-} !Int
-    , blockMcuY            :: {-# UNPACK #-} !Int
-    }
-    deriving Show
-
-toBlockSize :: Int -> Int
-toBlockSize v = (v + 7) `div` 8
-
-decodeRestartInterval :: BoolReader s Int32
-decodeRestartInterval = return (-1) {-  do
-  bits <- replicateM 8 getNextBitJpg
-  if bits == replicate 8 True
-     then do
-         marker <- replicateM 8 getNextBitJpg
-         return $ packInt marker
-     else return (-1)
-        -}
-
-{-# INLINE decodeInt #-}
-decodeInt :: Int -> BoolReader s Int32
-decodeInt ssss = do
-    signBit <- getNextBitJpg
-    let dataRange = 1 `unsafeShiftL` fromIntegral (ssss - 1)
-        leftBitCount = ssss - 1
-    -- First following bits store the sign of the coefficient, and counted in
-    -- SSSS, so the bit count for the int, is ssss - 1
-    if signBit
-       then (\w -> dataRange + fromIntegral w) <$> unpackInt leftBitCount
-       else (\w -> 1 - dataRange * 2 + fromIntegral w) <$> unpackInt leftBitCount
-
-decodeRrrrSsss :: HuffmanPackedTree -> BoolReader s (Int, Int)
-decodeRrrrSsss tree = do
-    rrrrssss <- huffmanPackedDecode tree
-    let rrrr = (rrrrssss `unsafeShiftR` 4) .&. 0xF
-        ssss =  rrrrssss .&. 0xF
-    pure (fromIntegral rrrr, fromIntegral ssss)
-
-dcCoefficientDecode :: HuffmanPackedTree -> BoolReader s DcCoefficient
-dcCoefficientDecode dcTree = do
-    ssss <- huffmanPackedDecode dcTree
-    if ssss == 0
-       then return 0
-       else fromIntegral <$> decodeInt (fromIntegral ssss)
-
--- | Apply a quantization matrix to a macroblock
-{-# INLINE deQuantize #-}
-deQuantize :: MacroBlock Int16 -> MutableMacroBlock s Int16
-           -> ST s (MutableMacroBlock s Int16)
-deQuantize table block = update 0
-    where update 64 = return block
-          update i = do
-              val <- block `M.unsafeRead` i
-              let finalValue = val * (table `VS.unsafeIndex` i)
-              (block `M.unsafeWrite` i) finalValue
-              update $ i + 1
-
-inverseDirectCosineTransform :: MutableMacroBlock s Int16
-                             -> ST s (MutableMacroBlock s Int16)
-inverseDirectCosineTransform mBlock =
-    fastIdct mBlock >>= mutableLevelShift
-
-zigZagOrder :: MacroBlock Int
-zigZagOrder = makeMacroBlock $ concat
-    [[ 0, 1, 5, 6,14,15,27,28]
-    ,[ 2, 4, 7,13,16,26,29,42]
-    ,[ 3, 8,12,17,25,30,41,43]
-    ,[ 9,11,18,24,31,40,44,53]
-    ,[10,19,23,32,39,45,52,54]
-    ,[20,22,33,38,46,51,55,60]
-    ,[21,34,37,47,50,56,59,61]
-    ,[35,36,48,49,57,58,62,63]
-    ]
-
-zigZagReorderForwardv :: (Storable a, Num a) => VS.Vector a -> VS.Vector a
-zigZagReorderForwardv vec = runST $ do
-    v <- M.new 64
-    mv <- VS.thaw vec
-    zigZagReorderForward v mv >>= VS.freeze
-
-zigZagOrderForward :: MacroBlock Int
-zigZagOrderForward = VS.generate 64 inv
-  where inv i = fromMaybe 0 $ VS.findIndex (i ==) zigZagOrder
-
-zigZagReorderForward :: (Storable a)
-                     => MutableMacroBlock s a
-                     -> MutableMacroBlock s a
-                     -> ST s (MutableMacroBlock s a)
-{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Int32
-                                           -> MutableMacroBlock s Int32
-                                           -> ST s (MutableMacroBlock s Int32) #-}
-{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Int16
-                                           -> MutableMacroBlock s Int16
-                                           -> ST s (MutableMacroBlock s Int16) #-}
-{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Word8
-                                           -> MutableMacroBlock s Word8
-                                           -> ST s (MutableMacroBlock s Word8) #-}
-zigZagReorderForward zigzaged block = ordering zigZagOrderForward >> return zigzaged
-  where ordering !table = reorder (0 :: Int)
-          where reorder !i | i >= 64 = return ()
-                reorder i  = do
-                     let idx = table `VS.unsafeIndex` i
-                     v <- block `M.unsafeRead` idx
-                     (zigzaged `M.unsafeWrite` i) v
-                     reorder (i + 1)
-
-zigZagReorder :: MutableMacroBlock s Int16 -> MutableMacroBlock s Int16
-              -> ST s (MutableMacroBlock s Int16)
-zigZagReorder zigzaged block = do
-    let update i =  do
-            let idx = zigZagOrder `VS.unsafeIndex` i
-            v <- block `M.unsafeRead` idx
-            (zigzaged `M.unsafeWrite` i) v
-
-        reorder 63 = update 63
-        reorder i  = update i >> reorder (i + 1)
-
-    reorder (0 :: Int)
-    return zigzaged
-
--- | Unpack an int of the given size encoded from MSB to LSB.
-unpackInt :: Int -> BoolReader s Int32
-unpackInt = getNextIntJpg
-
-{-# INLINE rasterMap #-}
-rasterMap :: (Monad m)
-          => Int -> Int -> (Int -> Int -> m ())
-          -> m ()
-rasterMap width height f = liner 0
-  where liner y | y >= height = return ()
-        liner y = columner 0
-          where columner x | x >= width = liner (y + 1)
-                columner x = f x y >> columner (x + 1)
-
-pixelClamp :: Int16 -> Word8
-pixelClamp n = fromIntegral . min 255 $ max 0 n
-
--- | Given a size coefficient (how much a pixel span horizontally
--- and vertically), the position of the macroblock, return a list
--- of indices and value to be stored in an array (like the final
--- image)
-unpackMacroBlock :: Int    -- ^ Component count
-                 -> Int -- ^ Width coefficient
-                 -> Int -- ^ Height coefficient
-                 -> Int -- ^ Component index
-                 -> Int -- ^ x
-                 -> Int -- ^ y
-                 -> MutableImage s PixelYCbCr8
-                 -> MutableMacroBlock s Int16
-                 -> ST s ()
-unpackMacroBlock compCount wCoeff hCoeff compIdx x y
-                 (MutableImage { mutableImageWidth = imgWidth,
-                                 mutableImageHeight = imgHeight, mutableImageData = img })
-                 block = rasterMap dctBlockSize dctBlockSize unpacker
-  where unpacker i j = do
-          let yBase = y * dctBlockSize + j * hCoeff
-          compVal <- pixelClamp <$> (block `M.unsafeRead` (i + j * dctBlockSize))
-          rasterMap wCoeff hCoeff $ \wDup hDup -> do
-             let xBase = x * dctBlockSize + i * wCoeff
-                 xPos = xBase + wDup
-                 yPos = yBase + hDup
-
-             when (xPos < imgWidth && yPos < imgHeight)
-                  (do let mutableIdx = (xPos + yPos * imgWidth) * compCount + compIdx
-                      (img `M.unsafeWrite` mutableIdx) compVal)
-
--- | This is one of the most important function of the decoding,
--- it form the barebone decoding pipeline for macroblock. It's all
--- there is to know for macro block transformation
-decodeMacroBlock :: MacroBlock DctCoefficients
-                 -> MutableMacroBlock s Int16
-                 -> MutableMacroBlock s Int16
-                 -> ST s (MutableMacroBlock s Int16)
-decodeMacroBlock quantizationTable zigZagBlock block =
-    deQuantize quantizationTable block >>= zigZagReorder zigZagBlock
-                                       >>= inverseDirectCosineTransform
-
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE CPP #-}
+module Codec.Picture.Jpg.Internal.Common
+    ( DctCoefficients
+    , JpgUnpackerParameter( .. )
+    , decodeInt
+    , dcCoefficientDecode
+    , deQuantize
+    , decodeRrrrSsss
+    , zigZagReorderForward 
+    , zigZagReorderForwardv
+    , zigZagReorder
+    , inverseDirectCosineTransform
+    , unpackInt
+    , unpackMacroBlock
+    , rasterMap
+    , decodeMacroBlock
+    , decodeRestartInterval
+    , toBlockSize
+    ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure, (<$>) )
+#endif
+
+import Control.Monad( when )
+import Control.Monad.ST( ST, runST )
+import Data.Bits( unsafeShiftL, unsafeShiftR, (.&.) )
+import Data.Int( Int16, Int32 )
+import Data.Maybe( fromMaybe )
+import Data.Word( Word8 )
+import qualified Data.Vector.Storable as VS
+import qualified Data.Vector.Storable.Mutable as M
+import Foreign.Storable ( Storable )
+
+import Codec.Picture.Types
+import Codec.Picture.BitWriter
+import Codec.Picture.Jpg.Internal.Types
+import Codec.Picture.Jpg.Internal.FastIdct
+import Codec.Picture.Jpg.Internal.DefaultTable
+
+-- | Same as for DcCoefficient, to provide nicer type signatures
+type DctCoefficients = DcCoefficient
+
+data JpgUnpackerParameter = JpgUnpackerParameter
+    { dcHuffmanTree        :: !HuffmanPackedTree
+    , acHuffmanTree        :: !HuffmanPackedTree
+    , componentIndex       :: {-# UNPACK #-} !Int
+    , restartInterval      :: {-# UNPACK #-} !Int
+    , componentWidth       :: {-# UNPACK #-} !Int
+    , componentHeight      :: {-# UNPACK #-} !Int
+    , subSampling          :: !(Int, Int)
+    , coefficientRange     :: !(Int, Int)
+    , successiveApprox     :: !(Int, Int)
+    , readerIndex          :: {-# UNPACK #-} !Int
+      -- | When in progressive mode, we can have many
+      -- color in a scan or only one. The indices changes
+      -- on this fact, when mixed, there is whole 
+      -- MCU for all color components, spanning multiple
+      -- block lines. With only one color component we use
+      -- the normal raster order.
+    , indiceVector         :: {-# UNPACK #-} !Int
+    , blockIndex           :: {-# UNPACK #-} !Int
+    , blockMcuX            :: {-# UNPACK #-} !Int
+    , blockMcuY            :: {-# UNPACK #-} !Int
+    }
+    deriving Show
+
+toBlockSize :: Int -> Int
+toBlockSize v = (v + 7) `div` 8
+
+decodeRestartInterval :: BoolReader s Int32
+decodeRestartInterval = return (-1) {-  do
+  bits <- replicateM 8 getNextBitJpg
+  if bits == replicate 8 True
+     then do
+         marker <- replicateM 8 getNextBitJpg
+         return $ packInt marker
+     else return (-1)
+        -}
+
+{-# INLINE decodeInt #-}
+decodeInt :: Int -> BoolReader s Int32
+decodeInt ssss = do
+    signBit <- getNextBitJpg
+    let dataRange = 1 `unsafeShiftL` fromIntegral (ssss - 1)
+        leftBitCount = ssss - 1
+    -- First following bits store the sign of the coefficient, and counted in
+    -- SSSS, so the bit count for the int, is ssss - 1
+    if signBit
+       then (\w -> dataRange + fromIntegral w) <$> unpackInt leftBitCount
+       else (\w -> 1 - dataRange * 2 + fromIntegral w) <$> unpackInt leftBitCount
+
+decodeRrrrSsss :: HuffmanPackedTree -> BoolReader s (Int, Int)
+decodeRrrrSsss tree = do
+    rrrrssss <- huffmanPackedDecode tree
+    let rrrr = (rrrrssss `unsafeShiftR` 4) .&. 0xF
+        ssss =  rrrrssss .&. 0xF
+    pure (fromIntegral rrrr, fromIntegral ssss)
+
+dcCoefficientDecode :: HuffmanPackedTree -> BoolReader s DcCoefficient
+dcCoefficientDecode dcTree = do
+    ssss <- huffmanPackedDecode dcTree
+    if ssss == 0
+       then return 0
+       else fromIntegral <$> decodeInt (fromIntegral ssss)
+
+-- | Apply a quantization matrix to a macroblock
+{-# INLINE deQuantize #-}
+deQuantize :: MacroBlock Int16 -> MutableMacroBlock s Int16
+           -> ST s (MutableMacroBlock s Int16)
+deQuantize table block = update 0
+    where update 64 = return block
+          update i = do
+              val <- block `M.unsafeRead` i
+              let finalValue = val * (table `VS.unsafeIndex` i)
+              (block `M.unsafeWrite` i) finalValue
+              update $ i + 1
+
+inverseDirectCosineTransform :: MutableMacroBlock s Int16
+                             -> ST s (MutableMacroBlock s Int16)
+inverseDirectCosineTransform mBlock =
+    fastIdct mBlock >>= mutableLevelShift
+
+zigZagOrder :: MacroBlock Int
+zigZagOrder = makeMacroBlock $ concat
+    [[ 0, 1, 5, 6,14,15,27,28]
+    ,[ 2, 4, 7,13,16,26,29,42]
+    ,[ 3, 8,12,17,25,30,41,43]
+    ,[ 9,11,18,24,31,40,44,53]
+    ,[10,19,23,32,39,45,52,54]
+    ,[20,22,33,38,46,51,55,60]
+    ,[21,34,37,47,50,56,59,61]
+    ,[35,36,48,49,57,58,62,63]
+    ]
+
+zigZagReorderForwardv :: (Storable a, Num a) => VS.Vector a -> VS.Vector a
+zigZagReorderForwardv vec = runST $ do
+    v <- M.new 64
+    mv <- VS.thaw vec
+    zigZagReorderForward v mv >>= VS.freeze
+
+zigZagOrderForward :: MacroBlock Int
+zigZagOrderForward = VS.generate 64 inv
+  where inv i = fromMaybe 0 $ VS.findIndex (i ==) zigZagOrder
+
+zigZagReorderForward :: (Storable a)
+                     => MutableMacroBlock s a
+                     -> MutableMacroBlock s a
+                     -> ST s (MutableMacroBlock s a)
+{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Int32
+                                           -> MutableMacroBlock s Int32
+                                           -> ST s (MutableMacroBlock s Int32) #-}
+{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Int16
+                                           -> MutableMacroBlock s Int16
+                                           -> ST s (MutableMacroBlock s Int16) #-}
+{-# SPECIALIZE INLINE zigZagReorderForward :: MutableMacroBlock s Word8
+                                           -> MutableMacroBlock s Word8
+                                           -> ST s (MutableMacroBlock s Word8) #-}
+zigZagReorderForward zigzaged block = ordering zigZagOrderForward >> return zigzaged
+  where ordering !table = reorder (0 :: Int)
+          where reorder !i | i >= 64 = return ()
+                reorder i  = do
+                     let idx = table `VS.unsafeIndex` i
+                     v <- block `M.unsafeRead` idx
+                     (zigzaged `M.unsafeWrite` i) v
+                     reorder (i + 1)
+
+zigZagReorder :: MutableMacroBlock s Int16 -> MutableMacroBlock s Int16
+              -> ST s (MutableMacroBlock s Int16)
+zigZagReorder zigzaged block = do
+    let update i =  do
+            let idx = zigZagOrder `VS.unsafeIndex` i
+            v <- block `M.unsafeRead` idx
+            (zigzaged `M.unsafeWrite` i) v
+
+        reorder 63 = update 63
+        reorder i  = update i >> reorder (i + 1)
+
+    reorder (0 :: Int)
+    return zigzaged
+
+-- | Unpack an int of the given size encoded from MSB to LSB.
+unpackInt :: Int -> BoolReader s Int32
+unpackInt = getNextIntJpg
+
+{-# INLINE rasterMap #-}
+rasterMap :: (Monad m)
+          => Int -> Int -> (Int -> Int -> m ())
+          -> m ()
+rasterMap width height f = liner 0
+  where liner y | y >= height = return ()
+        liner y = columner 0
+          where columner x | x >= width = liner (y + 1)
+                columner x = f x y >> columner (x + 1)
+
+pixelClamp :: Int16 -> Word8
+pixelClamp n = fromIntegral . min 255 $ max 0 n
+
+-- | Given a size coefficient (how much a pixel span horizontally
+-- and vertically), the position of the macroblock, return a list
+-- of indices and value to be stored in an array (like the final
+-- image)
+unpackMacroBlock :: Int    -- ^ Component count
+                 -> Int -- ^ Width coefficient
+                 -> Int -- ^ Height coefficient
+                 -> Int -- ^ Component index
+                 -> Int -- ^ x
+                 -> Int -- ^ y
+                 -> MutableImage s PixelYCbCr8
+                 -> MutableMacroBlock s Int16
+                 -> ST s ()
+unpackMacroBlock compCount wCoeff hCoeff compIdx x y
+                 (MutableImage { mutableImageWidth = imgWidth,
+                                 mutableImageHeight = imgHeight, mutableImageData = img })
+                 block = rasterMap dctBlockSize dctBlockSize unpacker
+  where unpacker i j = do
+          let yBase = y * dctBlockSize + j * hCoeff
+          compVal <- pixelClamp <$> (block `M.unsafeRead` (i + j * dctBlockSize))
+          rasterMap wCoeff hCoeff $ \wDup hDup -> do
+             let xBase = x * dctBlockSize + i * wCoeff
+                 xPos = xBase + wDup
+                 yPos = yBase + hDup
+
+             when (xPos < imgWidth && yPos < imgHeight)
+                  (do let mutableIdx = (xPos + yPos * imgWidth) * compCount + compIdx
+                      (img `M.unsafeWrite` mutableIdx) compVal)
+
+-- | This is one of the most important function of the decoding,
+-- it form the barebone decoding pipeline for macroblock. It's all
+-- there is to know for macro block transformation
+decodeMacroBlock :: MacroBlock DctCoefficients
+                 -> MutableMacroBlock s Int16
+                 -> MutableMacroBlock s Int16
+                 -> ST s (MutableMacroBlock s Int16)
+decodeMacroBlock quantizationTable zigZagBlock block =
+    deQuantize quantizationTable block >>= zigZagReorder zigZagBlock
+                                       >>= inverseDirectCosineTransform
+
diff --git a/src/Codec/Picture/Jpg/Internal/DefaultTable.hs b/src/Codec/Picture/Jpg/Internal/DefaultTable.hs
--- a/src/Codec/Picture/Jpg/Internal/DefaultTable.hs
+++ b/src/Codec/Picture/Jpg/Internal/DefaultTable.hs
@@ -99,7 +99,7 @@
             where shifted = code `unsafeShiftL` 1
 
 -- | Represent a compact array of 8 * 8 values. The size
--- is not guarenteed by type system, but if makeMacroBlock is
+-- is not guaranteed by type system, but if makeMacroBlock is
 -- used, everything should be fine size-wise
 type MacroBlock a = SV.Vector a
 
diff --git a/src/Codec/Picture/Jpg/Internal/FastDct.hs b/src/Codec/Picture/Jpg/Internal/FastDct.hs
--- a/src/Codec/Picture/Jpg/Internal/FastDct.hs
+++ b/src/Codec/Picture/Jpg/Internal/FastDct.hs
@@ -1,218 +1,218 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE TypeFamilies #-}
-module Codec.Picture.Jpg.Internal.FastDct( referenceDct, fastDctLibJpeg ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>) )
-#endif
-
-import Data.Int( Int16, Int32 )
-import Data.Bits( unsafeShiftR, unsafeShiftL )
-import Control.Monad.ST( ST )
-
-import qualified Data.Vector.Storable.Mutable as M
-
-import Codec.Picture.Jpg.Internal.Types
-import Control.Monad( forM, forM_ )
-
--- | Reference implementation of the DCT, directly implementing the formula
--- of ITU-81. It's slow as hell, perform to many operations, but is accurate
--- and a good reference point.
-referenceDct :: MutableMacroBlock s Int32
-             -> MutableMacroBlock s Int16
-             -> ST s (MutableMacroBlock s Int32)
-referenceDct workData block = do
-  forM_ [(u, v) | u <- [0 :: Int .. dctBlockSize - 1], v <- [0..dctBlockSize - 1]] $ \(u,v) -> do
-    val <- at (u,v)
-    (workData `M.unsafeWrite` (v * dctBlockSize + u)) . truncate $ (1 / 4) * c u * c v * val
-
-  return workData
- where -- at :: (Int, Int) -> ST s Float
-   at (u,v) = do
-     toSum <-
-        forM [(x,y) | x <- [0..dctBlockSize - 1], y <- [0..dctBlockSize - 1 :: Int]] $ \(x,y) -> do
-            sample <- fromIntegral <$> (block `M.unsafeRead` (y * dctBlockSize + x))
-            return $ sample * cos ((2 * fromIntegral x + 1) * fromIntegral u * (pi :: Float)/ 16) 
-                            * cos ((2 * fromIntegral y + 1) * fromIntegral v * pi / 16)
-     return $ sum toSum
-
-   c 0 = 1 / sqrt 2
-   c _ = 1
-
-pASS1_BITS, cONST_BITS :: Int
-cONST_BITS = 13
-pASS1_BITS =  2
-
-
-fIX_0_298631336, fIX_0_390180644, fIX_0_541196100,
-    fIX_0_765366865, fIX_0_899976223, fIX_1_175875602,
-    fIX_1_501321110, fIX_1_847759065, fIX_1_961570560,
-    fIX_2_053119869, fIX_2_562915447, fIX_3_072711026 :: Int32
-fIX_0_298631336 = 2446    -- FIX(0.298631336) */
-fIX_0_390180644 = 3196    -- FIX(0.390180644) */
-fIX_0_541196100 = 4433    -- FIX(0.541196100) */
-fIX_0_765366865 = 6270    -- FIX(0.765366865) */
-fIX_0_899976223 = 7373    -- FIX(0.899976223) */
-fIX_1_175875602 = 9633    -- FIX(1.175875602) */
-fIX_1_501321110 = 12299    -- FIX(1.501321110) */
-fIX_1_847759065 = 15137    -- FIX(1.847759065) */
-fIX_1_961570560 = 16069    -- FIX(1.961570560) */
-fIX_2_053119869 = 16819    -- FIX(2.053119869) */
-fIX_2_562915447 = 20995    -- FIX(2.562915447) */
-fIX_3_072711026 = 25172    -- FIX(3.072711026) */
-
-cENTERJSAMPLE :: Int32
-cENTERJSAMPLE = 128
-
--- | Fast DCT extracted from libjpeg
-fastDctLibJpeg :: MutableMacroBlock s Int32
-        -> MutableMacroBlock s Int16
-        -> ST s (MutableMacroBlock s Int32)
-fastDctLibJpeg workData sample_block = do
- firstPass workData  0
- secondPass workData 7
- {-_ <- mutate (\_ a -> a `quot` 8) workData-}
- return workData
-  where -- Pass 1: process rows.
-        -- Note results are scaled up by sqrt(8) compared to a true DCT;
-        -- furthermore, we scale the results by 2**PASS1_BITS.
-        firstPass         _ i | i == dctBlockSize = return ()
-        firstPass dataBlock i = do
-            let baseIdx = i * dctBlockSize
-                readAt idx = fromIntegral <$> sample_block `M.unsafeRead` (baseIdx + idx)
-                mult = (*)
-                writeAt idx = dataBlock `M.unsafeWrite` (baseIdx + idx)
-                writeAtPos idx n = (dataBlock `M.unsafeWrite` (baseIdx + idx))
-                                    (n `unsafeShiftR` (cONST_BITS - pASS1_BITS))
-
-            blk0 <- readAt 0
-            blk1 <- readAt 1
-            blk2 <- readAt 2
-            blk3 <- readAt 3
-            blk4 <- readAt 4
-            blk5 <- readAt 5
-            blk6 <- readAt 6
-            blk7 <- readAt 7
-
-            let tmp0 = blk0 + blk7
-                tmp1 = blk1 + blk6
-                tmp2 = blk2 + blk5
-                tmp3 = blk3 + blk4
-
-                tmp10 = tmp0 + tmp3
-                tmp12 = tmp0 - tmp3
-                tmp11 = tmp1 + tmp2
-                tmp13 = tmp1 - tmp2
-
-                tmp0' = blk0 - blk7
-                tmp1' = blk1 - blk6
-                tmp2' = blk2 - blk5
-                tmp3' = blk3 - blk4
-
-            -- Stage 4 and output
-            writeAt 0 $ (tmp10 + tmp11 - dctBlockSize * cENTERJSAMPLE) `unsafeShiftL` pASS1_BITS
-            writeAt 4 $ (tmp10 - tmp11) `unsafeShiftL` pASS1_BITS
-
-            let z1 = mult (tmp12 + tmp13) fIX_0_541196100
-                     + (1 `unsafeShiftL` (cONST_BITS - pASS1_BITS - 1))
-
-            writeAtPos 2 $ z1 + mult tmp12 fIX_0_765366865
-            writeAtPos 6 $ z1 - mult tmp13 fIX_1_847759065
-
-            let tmp10' = tmp0' + tmp3'
-                tmp11' = tmp1' + tmp2'
-                tmp12' = tmp0' + tmp2'
-                tmp13' = tmp1' + tmp3'
-                z1' = mult (tmp12' + tmp13') fIX_1_175875602 --  c3 */
-                        -- Add fudge factor here for final descale. */
-                        + (1 `unsafeShiftL` (cONST_BITS - pASS1_BITS-1))
-                tmp0'' = mult tmp0' fIX_1_501321110
-                tmp1'' = mult tmp1' fIX_3_072711026
-                tmp2'' = mult tmp2' fIX_2_053119869
-                tmp3'' = mult tmp3' fIX_0_298631336
-
-                tmp10'' = mult tmp10' (- fIX_0_899976223)
-                tmp11'' = mult tmp11' (- fIX_2_562915447)
-                tmp12'' = mult tmp12' (- fIX_0_390180644) + z1'
-                tmp13'' = mult tmp13' (- fIX_1_961570560) + z1'
-
-            writeAtPos 1 $ tmp0'' + tmp10'' + tmp12''
-            writeAtPos 3 $ tmp1'' + tmp11'' + tmp13''
-            writeAtPos 5 $ tmp2'' + tmp11'' + tmp12''
-            writeAtPos 7 $ tmp3'' + tmp10'' + tmp13''
-
-            firstPass dataBlock $ i + 1
-
-        -- Pass 2: process columns.
-        -- We remove the PASS1_BITS scaling, but leave the results scaled up
-        -- by an overall factor of 8.
-        secondPass :: M.STVector s Int32 -> Int -> ST s ()
-        secondPass _     (-1) = return ()
-        secondPass block i = do
-            let readAt idx = block `M.unsafeRead` ((7 - i) + idx * dctBlockSize)
-                mult = (*)
-                writeAt idx = block `M.unsafeWrite` (dctBlockSize * idx + (7 - i))
-                writeAtPos idx n = (block `M.unsafeWrite` (dctBlockSize * idx + (7 - i))) $ n `unsafeShiftR` (cONST_BITS + pASS1_BITS + 3)
-            blk0 <- readAt 0
-            blk1 <- readAt 1
-            blk2 <- readAt 2
-            blk3 <- readAt 3
-            blk4 <- readAt 4
-            blk5 <- readAt 5
-            blk6 <- readAt 6
-            blk7 <- readAt 7
-
-            let tmp0 = blk0 + blk7
-                tmp1 = blk1 + blk6
-                tmp2 = blk2 + blk5
-                tmp3 = blk3 + blk4
-
-                -- Add fudge factor here for final descale. */
-                tmp10 = tmp0 + tmp3 + (1 `unsafeShiftL` (pASS1_BITS-1))
-                tmp12 = tmp0 - tmp3
-                tmp11 = tmp1 + tmp2
-                tmp13 = tmp1 - tmp2
-
-                tmp0' = blk0 - blk7
-                tmp1' = blk1 - blk6
-                tmp2' = blk2 - blk5
-                tmp3' = blk3 - blk4
-
-            writeAt 0 $ (tmp10 + tmp11) `unsafeShiftR` (pASS1_BITS + 3)
-            writeAt 4 $ (tmp10 - tmp11) `unsafeShiftR` (pASS1_BITS + 3)
-
-            let z1 = mult (tmp12 + tmp13) fIX_0_541196100
-                    + (1 `unsafeShiftL` (cONST_BITS + pASS1_BITS - 1))
-
-            writeAtPos 2 $ z1 + mult tmp12 fIX_0_765366865
-            writeAtPos 6 $ z1 - mult tmp13 fIX_1_847759065
-
-            let tmp10' = tmp0' + tmp3'
-                tmp11' = tmp1' + tmp2'
-                tmp12' = tmp0' + tmp2'
-                tmp13' = tmp1' + tmp3'
-
-                z1' = mult (tmp12' + tmp13') fIX_1_175875602
-                    -- Add fudge factor here for final descale. */
-                   + 1 `unsafeShiftL` (cONST_BITS+pASS1_BITS-1);
-
-                tmp0''  = mult tmp0'    fIX_1_501321110
-                tmp1''  = mult tmp1'    fIX_3_072711026
-                tmp2''  = mult tmp2'    fIX_2_053119869
-                tmp3''  = mult tmp3'    fIX_0_298631336
-                tmp10'' = mult tmp10' (- fIX_0_899976223)
-                tmp11'' = mult tmp11' (- fIX_2_562915447)
-                tmp12'' = mult tmp12' (- fIX_0_390180644)
-                            + z1'
-                tmp13'' = mult tmp13' (- fIX_1_961570560)
-                            + z1'
-            writeAtPos 1 $ tmp0'' + tmp10'' + tmp12''
-            writeAtPos 3 $ tmp1'' + tmp11'' + tmp13''
-            writeAtPos 5 $ tmp2'' + tmp11'' + tmp12''
-            writeAtPos 7 $ tmp3'' + tmp10'' + tmp13''
-
-            secondPass block (i - 1)
-
-{-# ANN module "HLint: ignore Use camelCase" #-}
-{-# ANN module "HLint: ignore Reduce duplication" #-}
-
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE TypeFamilies #-}
+module Codec.Picture.Jpg.Internal.FastDct( referenceDct, fastDctLibJpeg ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>) )
+#endif
+
+import Data.Int( Int16, Int32 )
+import Data.Bits( unsafeShiftR, unsafeShiftL )
+import Control.Monad.ST( ST )
+
+import qualified Data.Vector.Storable.Mutable as M
+
+import Codec.Picture.Jpg.Internal.Types
+import Control.Monad( forM, forM_ )
+
+-- | Reference implementation of the DCT, directly implementing the formula
+-- of ITU-81. It's slow as hell, perform to many operations, but is accurate
+-- and a good reference point.
+referenceDct :: MutableMacroBlock s Int32
+             -> MutableMacroBlock s Int16
+             -> ST s (MutableMacroBlock s Int32)
+referenceDct workData block = do
+  forM_ [(u, v) | u <- [0 :: Int .. dctBlockSize - 1], v <- [0..dctBlockSize - 1]] $ \(u,v) -> do
+    val <- at (u,v)
+    (workData `M.unsafeWrite` (v * dctBlockSize + u)) . truncate $ (1 / 4) * c u * c v * val
+
+  return workData
+ where -- at :: (Int, Int) -> ST s Float
+   at (u,v) = do
+     toSum <-
+        forM [(x,y) | x <- [0..dctBlockSize - 1], y <- [0..dctBlockSize - 1 :: Int]] $ \(x,y) -> do
+            sample <- fromIntegral <$> (block `M.unsafeRead` (y * dctBlockSize + x))
+            return $ sample * cos ((2 * fromIntegral x + 1) * fromIntegral u * (pi :: Float)/ 16) 
+                            * cos ((2 * fromIntegral y + 1) * fromIntegral v * pi / 16)
+     return $ sum toSum
+
+   c 0 = 1 / sqrt 2
+   c _ = 1
+
+pASS1_BITS, cONST_BITS :: Int
+cONST_BITS = 13
+pASS1_BITS =  2
+
+
+fIX_0_298631336, fIX_0_390180644, fIX_0_541196100,
+    fIX_0_765366865, fIX_0_899976223, fIX_1_175875602,
+    fIX_1_501321110, fIX_1_847759065, fIX_1_961570560,
+    fIX_2_053119869, fIX_2_562915447, fIX_3_072711026 :: Int32
+fIX_0_298631336 = 2446    -- FIX(0.298631336) */
+fIX_0_390180644 = 3196    -- FIX(0.390180644) */
+fIX_0_541196100 = 4433    -- FIX(0.541196100) */
+fIX_0_765366865 = 6270    -- FIX(0.765366865) */
+fIX_0_899976223 = 7373    -- FIX(0.899976223) */
+fIX_1_175875602 = 9633    -- FIX(1.175875602) */
+fIX_1_501321110 = 12299    -- FIX(1.501321110) */
+fIX_1_847759065 = 15137    -- FIX(1.847759065) */
+fIX_1_961570560 = 16069    -- FIX(1.961570560) */
+fIX_2_053119869 = 16819    -- FIX(2.053119869) */
+fIX_2_562915447 = 20995    -- FIX(2.562915447) */
+fIX_3_072711026 = 25172    -- FIX(3.072711026) */
+
+cENTERJSAMPLE :: Int32
+cENTERJSAMPLE = 128
+
+-- | Fast DCT extracted from libjpeg
+fastDctLibJpeg :: MutableMacroBlock s Int32
+        -> MutableMacroBlock s Int16
+        -> ST s (MutableMacroBlock s Int32)
+fastDctLibJpeg workData sample_block = do
+ firstPass workData  0
+ secondPass workData 7
+ {-_ <- mutate (\_ a -> a `quot` 8) workData-}
+ return workData
+  where -- Pass 1: process rows.
+        -- Note results are scaled up by sqrt(8) compared to a true DCT;
+        -- furthermore, we scale the results by 2**PASS1_BITS.
+        firstPass         _ i | i == dctBlockSize = return ()
+        firstPass dataBlock i = do
+            let baseIdx = i * dctBlockSize
+                readAt idx = fromIntegral <$> sample_block `M.unsafeRead` (baseIdx + idx)
+                mult = (*)
+                writeAt idx = dataBlock `M.unsafeWrite` (baseIdx + idx)
+                writeAtPos idx n = (dataBlock `M.unsafeWrite` (baseIdx + idx))
+                                    (n `unsafeShiftR` (cONST_BITS - pASS1_BITS))
+
+            blk0 <- readAt 0
+            blk1 <- readAt 1
+            blk2 <- readAt 2
+            blk3 <- readAt 3
+            blk4 <- readAt 4
+            blk5 <- readAt 5
+            blk6 <- readAt 6
+            blk7 <- readAt 7
+
+            let tmp0 = blk0 + blk7
+                tmp1 = blk1 + blk6
+                tmp2 = blk2 + blk5
+                tmp3 = blk3 + blk4
+
+                tmp10 = tmp0 + tmp3
+                tmp12 = tmp0 - tmp3
+                tmp11 = tmp1 + tmp2
+                tmp13 = tmp1 - tmp2
+
+                tmp0' = blk0 - blk7
+                tmp1' = blk1 - blk6
+                tmp2' = blk2 - blk5
+                tmp3' = blk3 - blk4
+
+            -- Stage 4 and output
+            writeAt 0 $ (tmp10 + tmp11 - dctBlockSize * cENTERJSAMPLE) `unsafeShiftL` pASS1_BITS
+            writeAt 4 $ (tmp10 - tmp11) `unsafeShiftL` pASS1_BITS
+
+            let z1 = mult (tmp12 + tmp13) fIX_0_541196100
+                     + (1 `unsafeShiftL` (cONST_BITS - pASS1_BITS - 1))
+
+            writeAtPos 2 $ z1 + mult tmp12 fIX_0_765366865
+            writeAtPos 6 $ z1 - mult tmp13 fIX_1_847759065
+
+            let tmp10' = tmp0' + tmp3'
+                tmp11' = tmp1' + tmp2'
+                tmp12' = tmp0' + tmp2'
+                tmp13' = tmp1' + tmp3'
+                z1' = mult (tmp12' + tmp13') fIX_1_175875602 --  c3 */
+                        -- Add fudge factor here for final descale. */
+                        + (1 `unsafeShiftL` (cONST_BITS - pASS1_BITS-1))
+                tmp0'' = mult tmp0' fIX_1_501321110
+                tmp1'' = mult tmp1' fIX_3_072711026
+                tmp2'' = mult tmp2' fIX_2_053119869
+                tmp3'' = mult tmp3' fIX_0_298631336
+
+                tmp10'' = mult tmp10' (- fIX_0_899976223)
+                tmp11'' = mult tmp11' (- fIX_2_562915447)
+                tmp12'' = mult tmp12' (- fIX_0_390180644) + z1'
+                tmp13'' = mult tmp13' (- fIX_1_961570560) + z1'
+
+            writeAtPos 1 $ tmp0'' + tmp10'' + tmp12''
+            writeAtPos 3 $ tmp1'' + tmp11'' + tmp13''
+            writeAtPos 5 $ tmp2'' + tmp11'' + tmp12''
+            writeAtPos 7 $ tmp3'' + tmp10'' + tmp13''
+
+            firstPass dataBlock $ i + 1
+
+        -- Pass 2: process columns.
+        -- We remove the PASS1_BITS scaling, but leave the results scaled up
+        -- by an overall factor of 8.
+        secondPass :: M.STVector s Int32 -> Int -> ST s ()
+        secondPass _     (-1) = return ()
+        secondPass block i = do
+            let readAt idx = block `M.unsafeRead` ((7 - i) + idx * dctBlockSize)
+                mult = (*)
+                writeAt idx = block `M.unsafeWrite` (dctBlockSize * idx + (7 - i))
+                writeAtPos idx n = (block `M.unsafeWrite` (dctBlockSize * idx + (7 - i))) $ n `unsafeShiftR` (cONST_BITS + pASS1_BITS + 3)
+            blk0 <- readAt 0
+            blk1 <- readAt 1
+            blk2 <- readAt 2
+            blk3 <- readAt 3
+            blk4 <- readAt 4
+            blk5 <- readAt 5
+            blk6 <- readAt 6
+            blk7 <- readAt 7
+
+            let tmp0 = blk0 + blk7
+                tmp1 = blk1 + blk6
+                tmp2 = blk2 + blk5
+                tmp3 = blk3 + blk4
+
+                -- Add fudge factor here for final descale. */
+                tmp10 = tmp0 + tmp3 + (1 `unsafeShiftL` (pASS1_BITS-1))
+                tmp12 = tmp0 - tmp3
+                tmp11 = tmp1 + tmp2
+                tmp13 = tmp1 - tmp2
+
+                tmp0' = blk0 - blk7
+                tmp1' = blk1 - blk6
+                tmp2' = blk2 - blk5
+                tmp3' = blk3 - blk4
+
+            writeAt 0 $ (tmp10 + tmp11) `unsafeShiftR` (pASS1_BITS + 3)
+            writeAt 4 $ (tmp10 - tmp11) `unsafeShiftR` (pASS1_BITS + 3)
+
+            let z1 = mult (tmp12 + tmp13) fIX_0_541196100
+                    + (1 `unsafeShiftL` (cONST_BITS + pASS1_BITS - 1))
+
+            writeAtPos 2 $ z1 + mult tmp12 fIX_0_765366865
+            writeAtPos 6 $ z1 - mult tmp13 fIX_1_847759065
+
+            let tmp10' = tmp0' + tmp3'
+                tmp11' = tmp1' + tmp2'
+                tmp12' = tmp0' + tmp2'
+                tmp13' = tmp1' + tmp3'
+
+                z1' = mult (tmp12' + tmp13') fIX_1_175875602
+                    -- Add fudge factor here for final descale. */
+                   + 1 `unsafeShiftL` (cONST_BITS+pASS1_BITS-1);
+
+                tmp0''  = mult tmp0'    fIX_1_501321110
+                tmp1''  = mult tmp1'    fIX_3_072711026
+                tmp2''  = mult tmp2'    fIX_2_053119869
+                tmp3''  = mult tmp3'    fIX_0_298631336
+                tmp10'' = mult tmp10' (- fIX_0_899976223)
+                tmp11'' = mult tmp11' (- fIX_2_562915447)
+                tmp12'' = mult tmp12' (- fIX_0_390180644)
+                            + z1'
+                tmp13'' = mult tmp13' (- fIX_1_961570560)
+                            + z1'
+            writeAtPos 1 $ tmp0'' + tmp10'' + tmp12''
+            writeAtPos 3 $ tmp1'' + tmp11'' + tmp13''
+            writeAtPos 5 $ tmp2'' + tmp11'' + tmp12''
+            writeAtPos 7 $ tmp3'' + tmp10'' + tmp13''
+
+            secondPass block (i - 1)
+
+{-# ANN module "HLint: ignore Use camelCase" #-}
+{-# ANN module "HLint: ignore Reduce duplication" #-}
+
diff --git a/src/Codec/Picture/Jpg/Internal/Metadata.hs b/src/Codec/Picture/Jpg/Internal/Metadata.hs
--- a/src/Codec/Picture/Jpg/Internal/Metadata.hs
+++ b/src/Codec/Picture/Jpg/Internal/Metadata.hs
@@ -1,41 +1,41 @@
-{-# LANGUAGE CPP #-}
-module Codec.Picture.Jpg.Internal.Metadata ( extractMetadatas, encodeMetadatas ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure )
-import Data.Monoid( mempty )
-import Data.Word( Word )
-#endif
-
-import Data.Word( Word16 )
-import Data.Maybe( fromMaybe )
-import qualified Codec.Picture.Metadata as Met
-import Codec.Picture.Metadata( Metadatas )
-import Codec.Picture.Jpg.Internal.Types
-
-scalerOfUnit :: JFifUnit -> Met.Keys Word -> Word16 -> Metadatas -> Metadatas
-scalerOfUnit unit k v = case unit of
-  JFifUnitUnknown -> id
-  JFifPixelsPerInch -> Met.insert k (fromIntegral v)
-  JFifPixelsPerCentimeter ->
-    Met.insert k (Met.dotsPerCentiMeterToDotPerInch $ fromIntegral v)
-
-extractMetadatas :: JpgJFIFApp0 -> Metadatas
-extractMetadatas jfif = 
-    inserter Met.DpiX (_jfifDpiX jfif)
-        $ inserter Met.DpiY (_jfifDpiY jfif) mempty
-  where
-    inserter = scalerOfUnit $ _jfifUnit jfif
-
-
-encodeMetadatas :: Metadatas -> [JpgFrame]
-encodeMetadatas metas = fromMaybe [] $ do
-  dpiX <- Met.lookup Met.DpiX metas
-  dpiY <- Met.lookup Met.DpiY metas
-  pure . pure . JpgJFIF $ JpgJFIFApp0
-    { _jfifUnit      = JFifPixelsPerInch
-    , _jfifDpiX      = fromIntegral dpiX
-    , _jfifDpiY      = fromIntegral dpiY
-    , _jfifThumbnail = Nothing
-    }
-
+{-# LANGUAGE CPP #-}
+module Codec.Picture.Jpg.Internal.Metadata ( extractMetadatas, encodeMetadatas ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure )
+import Data.Monoid( mempty )
+import Data.Word( Word )
+#endif
+
+import Data.Word( Word16 )
+import Data.Maybe( fromMaybe )
+import qualified Codec.Picture.Metadata as Met
+import Codec.Picture.Metadata( Metadatas )
+import Codec.Picture.Jpg.Internal.Types
+
+scalerOfUnit :: JFifUnit -> Met.Keys Word -> Word16 -> Metadatas -> Metadatas
+scalerOfUnit unit k v = case unit of
+  JFifUnitUnknown -> id
+  JFifPixelsPerInch -> Met.insert k (fromIntegral v)
+  JFifPixelsPerCentimeter ->
+    Met.insert k (Met.dotsPerCentiMeterToDotPerInch $ fromIntegral v)
+
+extractMetadatas :: JpgJFIFApp0 -> Metadatas
+extractMetadatas jfif = 
+    inserter Met.DpiX (_jfifDpiX jfif)
+        $ inserter Met.DpiY (_jfifDpiY jfif) mempty
+  where
+    inserter = scalerOfUnit $ _jfifUnit jfif
+
+
+encodeMetadatas :: Metadatas -> [JpgFrame]
+encodeMetadatas metas = fromMaybe [] $ do
+  dpiX <- Met.lookup Met.DpiX metas
+  dpiY <- Met.lookup Met.DpiY metas
+  pure . pure . JpgJFIF $ JpgJFIFApp0
+    { _jfifUnit      = JFifPixelsPerInch
+    , _jfifDpiX      = fromIntegral dpiX
+    , _jfifDpiY      = fromIntegral dpiY
+    , _jfifThumbnail = Nothing
+    }
+
diff --git a/src/Codec/Picture/Jpg/Internal/Progressive.hs b/src/Codec/Picture/Jpg/Internal/Progressive.hs
--- a/src/Codec/Picture/Jpg/Internal/Progressive.hs
+++ b/src/Codec/Picture/Jpg/Internal/Progressive.hs
@@ -1,332 +1,332 @@
-{-# LANGUAGE TupleSections #-}
-{-# LANGUAGE TypeSynonymInstances #-}
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE CPP #-}
-module Codec.Picture.Jpg.Internal.Progressive
-    ( JpgUnpackerParameter( .. )
-    , progressiveUnpack
-    ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure, (<$>) )
-#endif
-
-import Control.Monad( when, unless, forM_ )
-import Control.Monad.ST( ST )
-import Control.Monad.Trans( lift )
-import Data.Bits( (.&.), (.|.), unsafeShiftL )
-import Data.Int( Int16, Int32 )
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as L
-import qualified Data.Vector as V
-import qualified Data.Vector.Storable as VS
-import Data.Vector( (!) )
-import qualified Data.Vector.Mutable as M
-import qualified Data.Vector.Storable.Mutable as MS
-
-import Codec.Picture.Types
-import Codec.Picture.BitWriter
-import Codec.Picture.Jpg.Internal.Common
-import Codec.Picture.Jpg.Internal.Types
-import Codec.Picture.Jpg.Internal.DefaultTable
-
-createMcuLineIndices :: JpgComponent -> Int -> Int -> V.Vector (VS.Vector Int)
-createMcuLineIndices param imgWidth mcuWidth =
- V.fromList $ VS.fromList <$> [indexSolo, indexMulti]
-  where compW = fromIntegral $ horizontalSamplingFactor param
-        compH = fromIntegral $ verticalSamplingFactor param
-        imageBlockSize = toBlockSize imgWidth
-
-        -- if the displayed MCU block is only displayed in half (like with
-        -- width 500 then we loose one macroblock of the MCU at the end of
-        -- the line. Previous implementation which naively used full mcu
-        -- was wrong. Only taking into account visible macroblocks
-        indexSolo = [base + x
-            | y <- [0 .. compH - 1]
-            , let base = y * mcuWidth * compW
-            , x <- [0 .. imageBlockSize - 1]]
-
-        indexMulti =
-            [(mcu + y * mcuWidth) * compW + x
-                | mcu <- [0 .. mcuWidth - 1]
-                , y <- [0 .. compH - 1]
-                , x <- [0 .. compW - 1] ]
-
-decodeFirstDC :: JpgUnpackerParameter
-              -> MS.STVector s Int16
-              -> MutableMacroBlock s Int16
-              -> Int32
-              -> BoolReader s Int32
-decodeFirstDC params dcCoeffs block eobrun = unpack >> pure eobrun
-  where unpack = do
-          (dcDeltaCoefficient) <- dcCoefficientDecode $ dcHuffmanTree params
-          previousDc <- lift $ dcCoeffs `MS.unsafeRead` componentIndex params
-          let neoDcCoefficient = previousDc + dcDeltaCoefficient
-              approxLow = fst $ successiveApprox params
-              scaledDc = neoDcCoefficient `unsafeShiftL` approxLow
-          lift $ (block `MS.unsafeWrite` 0) scaledDc 
-          lift $ (dcCoeffs `MS.unsafeWrite` componentIndex params) neoDcCoefficient
-
-decodeRefineDc :: JpgUnpackerParameter
-               -> a
-               -> MutableMacroBlock s Int16
-               -> Int32
-               -> BoolReader s Int32
-decodeRefineDc params _ block eobrun = unpack >> pure eobrun
-  where approxLow = fst $ successiveApprox params
-        plusOne = 1 `unsafeShiftL` approxLow
-        unpack = do
-            bit <- getNextBitJpg
-            when bit . lift $ do
-                v <- block `MS.unsafeRead` 0
-                (block `MS.unsafeWrite` 0) $ v .|. plusOne
-
-decodeFirstAc :: JpgUnpackerParameter
-              -> a
-              -> MutableMacroBlock s Int16
-              -> Int32
-              -> BoolReader s Int32
-decodeFirstAc _params _ _block eobrun | eobrun > 0 = pure $ eobrun - 1
-decodeFirstAc params _ block _ = unpack startIndex
-  where (startIndex, maxIndex) = coefficientRange params
-        (low, _) = successiveApprox params
-        unpack n | n > maxIndex = pure 0
-        unpack n = do
-            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
-            case rrrrssss of
-                (0xF, 0) -> unpack $ n + 16
-                (  0, 0) -> return 0
-                (  r, 0) -> eobrun <$> unpackInt r
-                    where eobrun lowBits = (1 `unsafeShiftL` r) - 1 + lowBits
-                (  r, s) -> do
-                    let n' = n + r
-                    val <- (`unsafeShiftL` low) <$> decodeInt s
-                    lift . (block `MS.unsafeWrite` n') $ fromIntegral val
-                    unpack $ n' + 1
-
-decodeRefineAc :: forall a s. JpgUnpackerParameter
-               -> a
-               -> MutableMacroBlock s Int16
-               -> Int32
-               -> BoolReader s Int32
-decodeRefineAc params _ block eobrun
-        | eobrun == 0 = unpack startIndex
-        | otherwise   = performEobRun startIndex >> return (eobrun - 1)
-  where (startIndex, maxIndex) = coefficientRange params
-        (low, _) = successiveApprox params
-        plusOne = 1 `unsafeShiftL` low
-        minusOne = (-1) `unsafeShiftL` low
-
-        getBitVal = do
-            v <- getNextBitJpg
-            pure $ if v then plusOne else minusOne
-
-        performEobRun idx | idx > maxIndex = pure ()
-        performEobRun idx = do
-          coeff <- lift $ block `MS.unsafeRead` idx
-          if coeff /= 0 then do
-            bit <- getNextBitJpg
-            case (bit, (coeff .&. plusOne) == 0) of
-               (False, _)    -> performEobRun $ idx + 1
-               (True, False) -> performEobRun $ idx + 1
-               (True, True) -> do
-                   let newVal | coeff >= 0 = coeff + plusOne
-                              | otherwise = coeff + minusOne
-                   lift $ (block `MS.unsafeWrite` idx) newVal
-                   performEobRun $ idx + 1
-          else
-            performEobRun $ idx + 1
-
-        unpack idx | idx > maxIndex = pure 0
-        unpack idx = do
-            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
-            case rrrrssss of
-              (0xF, 0) -> do
-                idx' <- updateCoeffs 0xF idx
-                unpack $ idx' + 1
-
-              (  r, 0) -> do
-                  lowBits <- unpackInt r
-                  let newEobRun = (1 `unsafeShiftL` r) + lowBits - 1
-                  performEobRun idx
-                  pure newEobRun
-
-              (  r, _) -> do
-                  val <- getBitVal
-                  idx' <- updateCoeffs (fromIntegral r) idx
-                  when (idx' <= maxIndex) $
-                       lift $ (block `MS.unsafeWrite` idx') val
-                  unpack $ idx' + 1
-
-        updateCoeffs :: Int -> Int -> BoolReader s Int
-        updateCoeffs r idx
-            | r   < 0        = pure $ idx - 1
-            | idx > maxIndex = pure idx
-        updateCoeffs r idx = do
-          coeff <- lift $ block `MS.unsafeRead` idx
-          if coeff /= 0 then do
-            bit <- getNextBitJpg
-            when (bit && coeff .&. plusOne == 0) $ do
-              let writeCoeff | coeff >= 0 = coeff + plusOne
-                             | otherwise = coeff + minusOne
-              lift $ (block `MS.unsafeWrite` idx) writeCoeff
-            updateCoeffs r $ idx + 1
-          else
-            updateCoeffs (r - 1) $ idx + 1
-
-type Unpacker s =
-    JpgUnpackerParameter -> MS.STVector s Int16 -> MutableMacroBlock s Int16 -> Int32
-        -> BoolReader s Int32
-
-
-prepareUnpacker :: [([(JpgUnpackerParameter, a)], L.ByteString)]
-                -> ST s ( V.Vector (V.Vector (JpgUnpackerParameter, Unpacker s))
-                        , M.STVector s BoolState)
-prepareUnpacker lst = do
-    let boolStates = V.fromList $ map snd infos
-    vec <- V.unsafeThaw boolStates
-    return (V.fromList $ map fst infos, vec)
-  where infos = map prepare lst
-        prepare ([], _) = error "progressiveUnpack, no component"
-        prepare (whole@((param, _) : _) , byteString) =
-         (V.fromList $ map (\(p,_) -> (p, unpacker)) whole, boolReader)
-           where unpacker = selection (successiveApprox param) (coefficientRange param)
-                 boolReader = initBoolStateJpg . B.concat $ L.toChunks byteString
-
-                 selection (_, 0) (0, _) = decodeFirstDC
-                 selection (_, 0) _      = decodeFirstAc
-                 selection _      (0, _) = decodeRefineDc
-                 selection _      _      = decodeRefineAc
-
-data ComponentData s = ComponentData
-  { componentIndices    :: V.Vector (VS.Vector Int)
-  , componentBlocks     :: V.Vector (MutableMacroBlock s Int16)
-  , componentId         :: !Int
-  , componentBlockCount :: !Int
-  }
-
--- | Iteration from 0 to n in monadic context, without data
--- keeping.
-lineMap :: (Monad m) => Int -> (Int -> m ()) -> m ()
-{-# INLINE lineMap #-}
-lineMap count f = go 0
-  where go n | n >= count = return ()
-        go n = f n >> go (n + 1)
-
-progressiveUnpack :: (Int, Int)
-                  -> JpgFrameHeader
-                  -> V.Vector (MacroBlock Int16)
-                  -> [([(JpgUnpackerParameter, a)], L.ByteString)]
-                  -> ST s (MutableImage s PixelYCbCr8)
-progressiveUnpack (maxiW, maxiH) frame quants lst = do
-    (unpackers, readers) <- prepareUnpacker lst
-    allBlocks <- mapM allocateWorkingBlocks . zip [0..] $ jpgComponents frame
-                    :: ST s [ComponentData s]
-    let scanCount = length lst
-        restartIntervalValue = case lst of
-                ((p,_):_,_): _ -> restartInterval p
-                _ -> -1
-    dcCoeffs <- MS.replicate imgComponentCount 0
-    eobRuns <- MS.replicate (length lst) 0
-    workBlock <- createEmptyMutableMacroBlock
-    writeIndices <- MS.replicate imgComponentCount (0 :: Int)
-    restartIntervals <- MS.replicate scanCount restartIntervalValue
-    let elementCount = imgWidth * imgHeight * fromIntegral imgComponentCount
-    img <- MutableImage imgWidth imgHeight <$> MS.replicate elementCount 128
-
-    let processRestartInterval =
-          forM_ [0 .. scanCount - 1] $ \ix -> do
-            v <- restartIntervals `MS.read` ix
-            if v == 0 then do
-              -- reset DC prediction
-              when (ix == 0) (MS.set dcCoeffs 0)
-              reader <- readers `M.read` ix
-              (_, updated) <- runBoolReaderWith reader $
-                  byteAlignJpg >> decodeRestartInterval
-              (readers `M.write` ix) updated 
-              (eobRuns `MS.unsafeWrite` ix) 0
-              (restartIntervals `MS.unsafeWrite` ix) $ restartIntervalValue - 1
-            else
-              (restartIntervals `MS.unsafeWrite` ix) $ v - 1
-
-
-    lineMap imageMcuHeight $ \mmY -> do
-      -- Reset all blocks to 0
-      forM_ allBlocks $ V.mapM_ (`MS.set` 0) .  componentBlocks
-      MS.set writeIndices 0
-
-      lineMap imageMcuWidth $ \_mmx -> do
-        processRestartInterval 
-        V.forM_ unpackers $ V.mapM_ $ \(unpackParam, unpacker) -> do
-            boolState <- readers `M.read` readerIndex unpackParam
-            eobrun <- eobRuns `MS.read` readerIndex unpackParam
-            let componentNumber = componentIndex unpackParam
-            writeIndex <- writeIndices `MS.read` componentNumber
-            let componentData = allBlocks !! componentNumber
-                -- We get back the correct block indices for the number of component
-                -- in the current scope (precalculated)
-                indexVector =
-                    componentIndices componentData ! indiceVector unpackParam
-                maxIndexLength = VS.length indexVector
-            unless (writeIndex + blockIndex unpackParam >= maxIndexLength) $ do
-               let realIndex = indexVector VS.! (writeIndex + blockIndex unpackParam)
-                   writeBlock = componentBlocks componentData ! realIndex
-               (eobrun', state) <-
-                   runBoolReaderWith boolState $
-                       unpacker unpackParam dcCoeffs writeBlock eobrun
-
-               (readers `M.write` readerIndex unpackParam) state
-               (eobRuns `MS.write` readerIndex unpackParam) eobrun'
-
-        -- Update the write indices
-        forM_ allBlocks $ \comp -> do
-          writeIndex <- writeIndices `MS.read` componentId comp
-          let newIndex = writeIndex + componentBlockCount comp
-          (writeIndices `MS.write` componentId comp) newIndex
-
-      forM_ allBlocks $ \compData -> do
-        let compBlocks = componentBlocks compData
-            cId = componentId compData
-            comp = jpgComponents frame !! cId
-            quantId =
-                fromIntegral $ quantizationTableDest comp
-            table = quants ! min 3 quantId
-            compW = fromIntegral $ horizontalSamplingFactor comp
-            compH = fromIntegral $ verticalSamplingFactor comp
-            cw8 = maxiW - fromIntegral (horizontalSamplingFactor comp) + 1
-            ch8 = maxiH - fromIntegral (verticalSamplingFactor comp) + 1
-
-        rasterMap (imageMcuWidth * compW) compH $ \rx y -> do
-            let ry = mmY * maxiH + y
-                block = compBlocks ! (y * imageMcuWidth * compW + rx)
-            transformed <- decodeMacroBlock table workBlock block
-            unpackMacroBlock imgComponentCount
-                    cw8 ch8 cId (rx * cw8) ry
-                    img transformed
-
-    return img
-
-  where imgComponentCount = length $ jpgComponents frame
-
-        imgWidth = fromIntegral $ jpgWidth frame
-        imgHeight = fromIntegral $ jpgHeight frame
-
-        imageBlockWidth = toBlockSize imgWidth
-        imageBlockHeight = toBlockSize imgHeight
-
-        imageMcuWidth =  (imageBlockWidth + (maxiW - 1)) `div` maxiW
-        imageMcuHeight = (imageBlockHeight + (maxiH - 1)) `div` maxiH
-
-        allocateWorkingBlocks (ix, comp) = do
-            let blockCount = hSample * vSample * imageMcuWidth * 2
-            blocks <- V.replicateM blockCount createEmptyMutableMacroBlock
-            return ComponentData 
-                { componentBlocks = blocks
-                , componentIndices = createMcuLineIndices comp imgWidth imageMcuWidth
-                , componentBlockCount = hSample * vSample
-                , componentId = ix
-                }
-            where hSample = fromIntegral $ horizontalSamplingFactor comp
-                  vSample = fromIntegral $ verticalSamplingFactor comp
-
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE CPP #-}
+module Codec.Picture.Jpg.Internal.Progressive
+    ( JpgUnpackerParameter( .. )
+    , progressiveUnpack
+    ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure, (<$>) )
+#endif
+
+import Control.Monad( when, unless, forM_ )
+import Control.Monad.ST( ST )
+import Control.Monad.Trans( lift )
+import Data.Bits( (.&.), (.|.), unsafeShiftL )
+import Data.Int( Int16, Int32 )
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as L
+import qualified Data.Vector as V
+import qualified Data.Vector.Storable as VS
+import Data.Vector( (!) )
+import qualified Data.Vector.Mutable as M
+import qualified Data.Vector.Storable.Mutable as MS
+
+import Codec.Picture.Types
+import Codec.Picture.BitWriter
+import Codec.Picture.Jpg.Internal.Common
+import Codec.Picture.Jpg.Internal.Types
+import Codec.Picture.Jpg.Internal.DefaultTable
+
+createMcuLineIndices :: JpgComponent -> Int -> Int -> V.Vector (VS.Vector Int)
+createMcuLineIndices param imgWidth mcuWidth =
+ V.fromList $ VS.fromList <$> [indexSolo, indexMulti]
+  where compW = fromIntegral $ horizontalSamplingFactor param
+        compH = fromIntegral $ verticalSamplingFactor param
+        imageBlockSize = toBlockSize imgWidth
+
+        -- if the displayed MCU block is only displayed in half (like with
+        -- width 500 then we loose one macroblock of the MCU at the end of
+        -- the line. Previous implementation which naively used full mcu
+        -- was wrong. Only taking into account visible macroblocks
+        indexSolo = [base + x
+            | y <- [0 .. compH - 1]
+            , let base = y * mcuWidth * compW
+            , x <- [0 .. imageBlockSize - 1]]
+
+        indexMulti =
+            [(mcu + y * mcuWidth) * compW + x
+                | mcu <- [0 .. mcuWidth - 1]
+                , y <- [0 .. compH - 1]
+                , x <- [0 .. compW - 1] ]
+
+decodeFirstDC :: JpgUnpackerParameter
+              -> MS.STVector s Int16
+              -> MutableMacroBlock s Int16
+              -> Int32
+              -> BoolReader s Int32
+decodeFirstDC params dcCoeffs block eobrun = unpack >> pure eobrun
+  where unpack = do
+          (dcDeltaCoefficient) <- dcCoefficientDecode $ dcHuffmanTree params
+          previousDc <- lift $ dcCoeffs `MS.unsafeRead` componentIndex params
+          let neoDcCoefficient = previousDc + dcDeltaCoefficient
+              approxLow = fst $ successiveApprox params
+              scaledDc = neoDcCoefficient `unsafeShiftL` approxLow
+          lift $ (block `MS.unsafeWrite` 0) scaledDc 
+          lift $ (dcCoeffs `MS.unsafeWrite` componentIndex params) neoDcCoefficient
+
+decodeRefineDc :: JpgUnpackerParameter
+               -> a
+               -> MutableMacroBlock s Int16
+               -> Int32
+               -> BoolReader s Int32
+decodeRefineDc params _ block eobrun = unpack >> pure eobrun
+  where approxLow = fst $ successiveApprox params
+        plusOne = 1 `unsafeShiftL` approxLow
+        unpack = do
+            bit <- getNextBitJpg
+            when bit . lift $ do
+                v <- block `MS.unsafeRead` 0
+                (block `MS.unsafeWrite` 0) $ v .|. plusOne
+
+decodeFirstAc :: JpgUnpackerParameter
+              -> a
+              -> MutableMacroBlock s Int16
+              -> Int32
+              -> BoolReader s Int32
+decodeFirstAc _params _ _block eobrun | eobrun > 0 = pure $ eobrun - 1
+decodeFirstAc params _ block _ = unpack startIndex
+  where (startIndex, maxIndex) = coefficientRange params
+        (low, _) = successiveApprox params
+        unpack n | n > maxIndex = pure 0
+        unpack n = do
+            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
+            case rrrrssss of
+                (0xF, 0) -> unpack $ n + 16
+                (  0, 0) -> return 0
+                (  r, 0) -> eobrun <$> unpackInt r
+                    where eobrun lowBits = (1 `unsafeShiftL` r) - 1 + lowBits
+                (  r, s) -> do
+                    let n' = n + r
+                    val <- (`unsafeShiftL` low) <$> decodeInt s
+                    lift . (block `MS.unsafeWrite` n') $ fromIntegral val
+                    unpack $ n' + 1
+
+decodeRefineAc :: forall a s. JpgUnpackerParameter
+               -> a
+               -> MutableMacroBlock s Int16
+               -> Int32
+               -> BoolReader s Int32
+decodeRefineAc params _ block eobrun
+        | eobrun == 0 = unpack startIndex
+        | otherwise   = performEobRun startIndex >> return (eobrun - 1)
+  where (startIndex, maxIndex) = coefficientRange params
+        (low, _) = successiveApprox params
+        plusOne = 1 `unsafeShiftL` low
+        minusOne = (-1) `unsafeShiftL` low
+
+        getBitVal = do
+            v <- getNextBitJpg
+            pure $ if v then plusOne else minusOne
+
+        performEobRun idx | idx > maxIndex = pure ()
+        performEobRun idx = do
+          coeff <- lift $ block `MS.unsafeRead` idx
+          if coeff /= 0 then do
+            bit <- getNextBitJpg
+            case (bit, (coeff .&. plusOne) == 0) of
+               (False, _)    -> performEobRun $ idx + 1
+               (True, False) -> performEobRun $ idx + 1
+               (True, True) -> do
+                   let newVal | coeff >= 0 = coeff + plusOne
+                              | otherwise = coeff + minusOne
+                   lift $ (block `MS.unsafeWrite` idx) newVal
+                   performEobRun $ idx + 1
+          else
+            performEobRun $ idx + 1
+
+        unpack idx | idx > maxIndex = pure 0
+        unpack idx = do
+            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
+            case rrrrssss of
+              (0xF, 0) -> do
+                idx' <- updateCoeffs 0xF idx
+                unpack $ idx' + 1
+
+              (  r, 0) -> do
+                  lowBits <- unpackInt r
+                  let newEobRun = (1 `unsafeShiftL` r) + lowBits - 1
+                  performEobRun idx
+                  pure newEobRun
+
+              (  r, _) -> do
+                  val <- getBitVal
+                  idx' <- updateCoeffs (fromIntegral r) idx
+                  when (idx' <= maxIndex) $
+                       lift $ (block `MS.unsafeWrite` idx') val
+                  unpack $ idx' + 1
+
+        updateCoeffs :: Int -> Int -> BoolReader s Int
+        updateCoeffs r idx
+            | r   < 0        = pure $ idx - 1
+            | idx > maxIndex = pure idx
+        updateCoeffs r idx = do
+          coeff <- lift $ block `MS.unsafeRead` idx
+          if coeff /= 0 then do
+            bit <- getNextBitJpg
+            when (bit && coeff .&. plusOne == 0) $ do
+              let writeCoeff | coeff >= 0 = coeff + plusOne
+                             | otherwise = coeff + minusOne
+              lift $ (block `MS.unsafeWrite` idx) writeCoeff
+            updateCoeffs r $ idx + 1
+          else
+            updateCoeffs (r - 1) $ idx + 1
+
+type Unpacker s =
+    JpgUnpackerParameter -> MS.STVector s Int16 -> MutableMacroBlock s Int16 -> Int32
+        -> BoolReader s Int32
+
+
+prepareUnpacker :: [([(JpgUnpackerParameter, a)], L.ByteString)]
+                -> ST s ( V.Vector (V.Vector (JpgUnpackerParameter, Unpacker s))
+                        , M.STVector s BoolState)
+prepareUnpacker lst = do
+    let boolStates = V.fromList $ map snd infos
+    vec <- V.unsafeThaw boolStates
+    return (V.fromList $ map fst infos, vec)
+  where infos = map prepare lst
+        prepare ([], _) = error "progressiveUnpack, no component"
+        prepare (whole@((param, _) : _) , byteString) =
+         (V.fromList $ map (\(p,_) -> (p, unpacker)) whole, boolReader)
+           where unpacker = selection (successiveApprox param) (coefficientRange param)
+                 boolReader = initBoolStateJpg . B.concat $ L.toChunks byteString
+
+                 selection (_, 0) (0, _) = decodeFirstDC
+                 selection (_, 0) _      = decodeFirstAc
+                 selection _      (0, _) = decodeRefineDc
+                 selection _      _      = decodeRefineAc
+
+data ComponentData s = ComponentData
+  { componentIndices    :: V.Vector (VS.Vector Int)
+  , componentBlocks     :: V.Vector (MutableMacroBlock s Int16)
+  , componentId         :: !Int
+  , componentBlockCount :: !Int
+  }
+
+-- | Iteration from 0 to n in monadic context, without data
+-- keeping.
+lineMap :: (Monad m) => Int -> (Int -> m ()) -> m ()
+{-# INLINE lineMap #-}
+lineMap count f = go 0
+  where go n | n >= count = return ()
+        go n = f n >> go (n + 1)
+
+progressiveUnpack :: (Int, Int)
+                  -> JpgFrameHeader
+                  -> V.Vector (MacroBlock Int16)
+                  -> [([(JpgUnpackerParameter, a)], L.ByteString)]
+                  -> ST s (MutableImage s PixelYCbCr8)
+progressiveUnpack (maxiW, maxiH) frame quants lst = do
+    (unpackers, readers) <- prepareUnpacker lst
+    allBlocks <- mapM allocateWorkingBlocks . zip [0..] $ jpgComponents frame
+                    :: ST s [ComponentData s]
+    let scanCount = length lst
+        restartIntervalValue = case lst of
+                ((p,_):_,_): _ -> restartInterval p
+                _ -> -1
+    dcCoeffs <- MS.replicate imgComponentCount 0
+    eobRuns <- MS.replicate (length lst) 0
+    workBlock <- createEmptyMutableMacroBlock
+    writeIndices <- MS.replicate imgComponentCount (0 :: Int)
+    restartIntervals <- MS.replicate scanCount restartIntervalValue
+    let elementCount = imgWidth * imgHeight * fromIntegral imgComponentCount
+    img <- MutableImage imgWidth imgHeight <$> MS.replicate elementCount 128
+
+    let processRestartInterval =
+          forM_ [0 .. scanCount - 1] $ \ix -> do
+            v <- restartIntervals `MS.read` ix
+            if v == 0 then do
+              -- reset DC prediction
+              when (ix == 0) (MS.set dcCoeffs 0)
+              reader <- readers `M.read` ix
+              (_, updated) <- runBoolReaderWith reader $
+                  byteAlignJpg >> decodeRestartInterval
+              (readers `M.write` ix) updated 
+              (eobRuns `MS.unsafeWrite` ix) 0
+              (restartIntervals `MS.unsafeWrite` ix) $ restartIntervalValue - 1
+            else
+              (restartIntervals `MS.unsafeWrite` ix) $ v - 1
+
+
+    lineMap imageMcuHeight $ \mmY -> do
+      -- Reset all blocks to 0
+      forM_ allBlocks $ V.mapM_ (`MS.set` 0) .  componentBlocks
+      MS.set writeIndices 0
+
+      lineMap imageMcuWidth $ \_mmx -> do
+        processRestartInterval 
+        V.forM_ unpackers $ V.mapM_ $ \(unpackParam, unpacker) -> do
+            boolState <- readers `M.read` readerIndex unpackParam
+            eobrun <- eobRuns `MS.read` readerIndex unpackParam
+            let componentNumber = componentIndex unpackParam
+            writeIndex <- writeIndices `MS.read` componentNumber
+            let componentData = allBlocks !! componentNumber
+                -- We get back the correct block indices for the number of component
+                -- in the current scope (precalculated)
+                indexVector =
+                    componentIndices componentData ! indiceVector unpackParam
+                maxIndexLength = VS.length indexVector
+            unless (writeIndex + blockIndex unpackParam >= maxIndexLength) $ do
+               let realIndex = indexVector VS.! (writeIndex + blockIndex unpackParam)
+                   writeBlock = componentBlocks componentData ! realIndex
+               (eobrun', state) <-
+                   runBoolReaderWith boolState $
+                       unpacker unpackParam dcCoeffs writeBlock eobrun
+
+               (readers `M.write` readerIndex unpackParam) state
+               (eobRuns `MS.write` readerIndex unpackParam) eobrun'
+
+        -- Update the write indices
+        forM_ allBlocks $ \comp -> do
+          writeIndex <- writeIndices `MS.read` componentId comp
+          let newIndex = writeIndex + componentBlockCount comp
+          (writeIndices `MS.write` componentId comp) newIndex
+
+      forM_ allBlocks $ \compData -> do
+        let compBlocks = componentBlocks compData
+            cId = componentId compData
+            comp = jpgComponents frame !! cId
+            quantId =
+                fromIntegral $ quantizationTableDest comp
+            table = quants ! min 3 quantId
+            compW = fromIntegral $ horizontalSamplingFactor comp
+            compH = fromIntegral $ verticalSamplingFactor comp
+            cw8 = maxiW - fromIntegral (horizontalSamplingFactor comp) + 1
+            ch8 = maxiH - fromIntegral (verticalSamplingFactor comp) + 1
+
+        rasterMap (imageMcuWidth * compW) compH $ \rx y -> do
+            let ry = mmY * maxiH + y
+                block = compBlocks ! (y * imageMcuWidth * compW + rx)
+            transformed <- decodeMacroBlock table workBlock block
+            unpackMacroBlock imgComponentCount
+                    cw8 ch8 cId (rx * cw8) ry
+                    img transformed
+
+    return img
+
+  where imgComponentCount = length $ jpgComponents frame
+
+        imgWidth = fromIntegral $ jpgWidth frame
+        imgHeight = fromIntegral $ jpgHeight frame
+
+        imageBlockWidth = toBlockSize imgWidth
+        imageBlockHeight = toBlockSize imgHeight
+
+        imageMcuWidth =  (imageBlockWidth + (maxiW - 1)) `div` maxiW
+        imageMcuHeight = (imageBlockHeight + (maxiH - 1)) `div` maxiH
+
+        allocateWorkingBlocks (ix, comp) = do
+            let blockCount = hSample * vSample * imageMcuWidth * 2
+            blocks <- V.replicateM blockCount createEmptyMutableMacroBlock
+            return ComponentData 
+                { componentBlocks = blocks
+                , componentIndices = createMcuLineIndices comp imgWidth imageMcuWidth
+                , componentBlockCount = hSample * vSample
+                , componentId = ix
+                }
+            where hSample = fromIntegral $ horizontalSamplingFactor comp
+                  vSample = fromIntegral $ verticalSamplingFactor comp
+
diff --git a/src/Codec/Picture/Jpg/Internal/Types.hs b/src/Codec/Picture/Jpg/Internal/Types.hs
--- a/src/Codec/Picture/Jpg/Internal/Types.hs
+++ b/src/Codec/Picture/Jpg/Internal/Types.hs
@@ -1,1073 +1,1073 @@
-{-# LANGUAGE BangPatterns #-}
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE CPP #-}
-
--- | A good explanation of the JPEG format, including diagrams, is given at:
--- <https://github.com/corkami/formats/blob/master/image/jpeg.md>
---
--- The full spec (excluding EXIF): https://www.w3.org/Graphics/JPEG/itu-t81.pdf
-module Codec.Picture.Jpg.Internal.Types( MutableMacroBlock
-                              , createEmptyMutableMacroBlock
-                              , printMacroBlock
-                              , printPureMacroBlock
-                              , DcCoefficient
-                              , JpgImage( .. )
-                              , JpgComponent( .. )
-                              , JpgFrameHeader( .. )
-                              , JpgFrame( .. )
-                              , JpgFrameKind( .. )
-                              , JpgScanHeader( .. )
-                              , JpgQuantTableSpec( .. )
-                              , JpgHuffmanTableSpec( .. )
-                              , JpgImageKind( .. )
-                              , JpgScanSpecification( .. )
-                              , JpgColorSpace( .. )
-                              , AdobeTransform( .. )
-                              , JpgAdobeApp14( .. )
-                              , JpgJFIFApp0( .. )
-                              , JFifUnit( .. )
-                              , TableList( .. )
-                              , RestartInterval( .. )
-                              , getJpgImage
-                              , calculateSize
-                              , dctBlockSize
-                              , parseECS
-                              , parseECS_simple
-                              , skipUntilFrames
-                              , skipFrameMarker
-                              , parseFrameOfKind
-                              , parseFrames
-                              , parseFrameKinds
-                              , parseToFirstFrameHeader
-                              ) where
-
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( pure, (<*>), (<$>) )
-#endif
-
-import Control.DeepSeq( NFData(..) )
-import Control.Monad( when, replicateM, forM, forM_, unless )
-import Control.Monad.ST( ST )
-import Data.Bits( (.|.), (.&.), unsafeShiftL, unsafeShiftR )
-import Data.List( partition )
-import Data.Maybe( maybeToList )
-import GHC.Generics( Generic )
-
-#if !MIN_VERSION_base(4,11,0)
-import Data.Monoid( (<>) )
-#endif
-
-import Foreign.Storable ( Storable )
-import Data.Vector.Unboxed( (!) )
-import qualified Data.Vector as V
-import qualified Data.Vector.Unboxed as VU
-import qualified Data.Vector.Storable as VS
-import qualified Data.Vector.Storable.Mutable as M
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Char8 as BC
-import qualified Data.ByteString.Lazy as L
-import qualified Data.ByteString.Unsafe as BU
-
-import Data.Int( Int16, Int64 )
-import Data.Word(Word8, Word16 )
-import Data.Binary( Binary(..) )
-
-import Data.Binary.Get( Get
-                      , getWord8
-                      , getWord16be
-                      , getByteString
-                      , skip
-                      , bytesRead
-                      , lookAhead
-                      , ByteOffset
-                      , getLazyByteString
-                      )
-import qualified Data.Binary.Get.Internal as GetInternal
-
-import Data.Binary.Put( Put
-                      , putWord8
-                      , putWord16be
-                      , putLazyByteString
-                      , putByteString
-                      , runPut
-                      )
-
-import Codec.Picture.InternalHelper
-import Codec.Picture.Jpg.Internal.DefaultTable
-import Codec.Picture.Tiff.Internal.Types
-import Codec.Picture.Tiff.Internal.Metadata( exifOffsetIfd )
-import Codec.Picture.Metadata.Exif
-
-import Text.Printf
-
--- | Type only used to make clear what kind of integer we are carrying
--- Might be transformed into newtype in the future
-type DcCoefficient = Int16
-
--- | Macroblock that can be transformed.
-type MutableMacroBlock s a = M.STVector s a
-
-data JpgFrameKind =
-      JpgBaselineDCTHuffman
-    | JpgExtendedSequentialDCTHuffman
-    | JpgProgressiveDCTHuffman
-    | JpgLosslessHuffman
-    | JpgDifferentialSequentialDCTHuffman
-    | JpgDifferentialProgressiveDCTHuffman
-    | JpgDifferentialLosslessHuffman
-    | JpgExtendedSequentialArithmetic
-    | JpgProgressiveDCTArithmetic
-    | JpgLosslessArithmetic
-    | JpgDifferentialSequentialDCTArithmetic
-    | JpgDifferentialProgressiveDCTArithmetic
-    | JpgDifferentialLosslessArithmetic
-    | JpgQuantizationTable
-    | JpgHuffmanTableMarker
-    | JpgStartOfScan
-    | JpgEndOfImage
-    | JpgAppSegment Word8
-    | JpgExtensionSegment Word8
-
-    | JpgRestartInterval
-    | JpgRestartIntervalEnd Word8
-    deriving (Eq, Show, Generic)
-instance NFData JpgFrameKind
-
-data JpgFrame =
-      JpgAppFrame        !Word8 B.ByteString
-    | JpgAdobeAPP14      !JpgAdobeApp14
-    | JpgJFIF            !JpgJFIFApp0
-    | JpgExif            ![ImageFileDirectory]
-    | JpgExtension       !Word8 B.ByteString
-    | JpgQuantTable      ![JpgQuantTableSpec]
-    | JpgHuffmanTable    ![(JpgHuffmanTableSpec, HuffmanPackedTree)]
-    | JpgScanBlob        !JpgScanHeader !L.ByteString -- ^ The @ByteString@ is the ECS (Entropy-Coded Segment), typically the largest part of compressed image data.
-    | JpgScans           !JpgFrameKind !JpgFrameHeader
-    | JpgIntervalRestart !Word16
-    deriving (Eq, Show, Generic)
-instance NFData JpgFrame
-
-data JpgColorSpace
-  = JpgColorSpaceYCbCr
-  | JpgColorSpaceYCC
-  | JpgColorSpaceY
-  | JpgColorSpaceYA
-  | JpgColorSpaceYCCA
-  | JpgColorSpaceYCCK
-  | JpgColorSpaceCMYK
-  | JpgColorSpaceRGB
-  | JpgColorSpaceRGBA
-  deriving (Eq, Show, Generic)
-instance NFData JpgColorSpace
-
-data AdobeTransform
-  = AdobeUnknown    -- ^ Value 0
-  | AdobeYCbCr      -- ^ value 1
-  | AdobeYCck       -- ^ value 2
-  deriving (Eq, Show, Generic)
-instance NFData AdobeTransform
-
-data JpgAdobeApp14 = JpgAdobeApp14
-  { _adobeDctVersion :: !Word16
-  , _adobeFlag0      :: !Word16
-  , _adobeFlag1      :: !Word16
-  , _adobeTransform  :: !AdobeTransform
-  }
-  deriving (Eq, Show, Generic)
-instance NFData JpgAdobeApp14
-
--- | Size: 1
-data JFifUnit
-  = JFifUnitUnknown   -- ^ 0
-  | JFifPixelsPerInch -- ^ 1
-  | JFifPixelsPerCentimeter -- ^ 2
-  deriving (Eq, Show, Generic)
-instance NFData JFifUnit
-
-instance Binary JFifUnit where
-  put v = putWord8 $ case v of
-    JFifUnitUnknown -> 0
-    JFifPixelsPerInch -> 1
-    JFifPixelsPerCentimeter -> 2
-  get = do
-    v <- getWord8
-    pure $ case v of
-      0 -> JFifUnitUnknown
-      1 -> JFifPixelsPerInch
-      2 -> JFifPixelsPerCentimeter
-      _ -> JFifUnitUnknown
-
-data JpgJFIFApp0 = JpgJFIFApp0
-  { _jfifUnit      :: !JFifUnit
-  , _jfifDpiX      :: !Word16
-  , _jfifDpiY      :: !Word16
-  , _jfifThumbnail :: !(Maybe {- (Image PixelRGB8) -} Int)
-  }
-  deriving (Eq, Show, Generic)
-instance NFData JpgJFIFApp0
-
-instance Binary JpgJFIFApp0 where
-  get = do
-    sig <- getByteString 5
-    when (sig /= BC.pack "JFIF\0") $
-        fail "Invalid JFIF signature"
-    major <- getWord8
-    minor <- getWord8
-    when (major /= 1 && minor > 2) $
-        fail "Unrecognize JFIF version"
-    unit <- get
-    dpiX <- getWord16be
-    dpiY <- getWord16be
-    w <- getWord8
-    h <- getWord8
-    let pxCount = 3 * w * h
-    img <- case pxCount of
-      0 -> return Nothing
-      _ -> return Nothing
-    return $ JpgJFIFApp0
-        { _jfifUnit      = unit
-        , _jfifDpiX      = dpiX
-        , _jfifDpiY      = dpiY
-        , _jfifThumbnail = img
-        }
-
-
-  put jfif = do
-    putByteString $ BC.pack "JFIF\0" -- 5
-    putWord8 1                       -- 1 6
-    putWord8 2                       -- 1 7
-    put $ _jfifUnit jfif             -- 1 8
-    putWord16be $ _jfifDpiX jfif     -- 2 10
-    putWord16be $ _jfifDpiY jfif     -- 2 12
-    putWord8 0                       -- 1 13
-    putWord8 0                       -- 1 14
-
-{-Thumbnail width (tw) 	1 	Horizontal size of embedded JFIF thumbnail in pixels-}
-{-Thumbnail height (th) 	1 	Vertical size of embedded JFIF thumbnail in pixels-}
-{-Thumbnail data 	3 × tw × th 	Uncompressed 24 bit RGB raster thumbnail-}
-
-instance Binary AdobeTransform where
-  put v = case v of
-    AdobeUnknown -> putWord8 0
-    AdobeYCbCr -> putWord8 1
-    AdobeYCck -> putWord8 2
-
-  get = do
-    v <- getWord8
-    pure $ case v of
-      0 -> AdobeUnknown
-      1 -> AdobeYCbCr
-      2 -> AdobeYCck
-      _ -> AdobeUnknown
-
-instance Binary JpgAdobeApp14 where
-  get = do
-    let sig = BC.pack "Adobe"
-    fileSig <- getByteString 5
-    when (fileSig /= sig) $
-       fail "Invalid Adobe APP14 marker"
-    version <- getWord16be
-    when (version /= 100) $
-       fail $ "Invalid Adobe APP14 version " ++ show version
-    JpgAdobeApp14 version
-                  <$> getWord16be
-                  <*> getWord16be <*> get
-
-  put (JpgAdobeApp14 v f0 f1 t) = do
-    putByteString $ BC.pack "Adobe"
-    putWord16be v
-    putWord16be f0
-    putWord16be f1
-    put t
-
-
-data JpgFrameHeader = JpgFrameHeader
-    { jpgFrameHeaderLength   :: !Word16
-    , jpgSamplePrecision     :: !Word8
-    , jpgHeight              :: !Word16
-    , jpgWidth               :: !Word16
-    , jpgImageComponentCount :: !Word8
-    , jpgComponents          :: ![JpgComponent]
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgFrameHeader
-
-
-instance SizeCalculable JpgFrameHeader where
-    calculateSize hdr = 2 + 1 + 2 + 2 + 1
-                      + sum [calculateSize c | c <- jpgComponents hdr]
-
-data JpgComponent = JpgComponent
-    { componentIdentifier       :: !Word8
-      -- | Stored with 4 bits
-    , horizontalSamplingFactor  :: !Word8
-      -- | Stored with 4 bits
-    , verticalSamplingFactor    :: !Word8
-    , quantizationTableDest     :: !Word8
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgComponent
-
-instance SizeCalculable JpgComponent where
-    calculateSize _ = 3
-
-data JpgImage = JpgImage { jpgFrame :: [JpgFrame] }
-    deriving (Eq, Show, Generic)
-instance NFData JpgImage
-
-data JpgScanSpecification = JpgScanSpecification
-    { componentSelector :: !Word8
-      -- | Encoded as 4 bits
-    , dcEntropyCodingTable :: !Word8
-      -- | Encoded as 4 bits
-    , acEntropyCodingTable :: !Word8
-
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgScanSpecification
-
-instance SizeCalculable JpgScanSpecification where
-    calculateSize _ = 2
-
-data JpgScanHeader = JpgScanHeader
-    { scanLength :: !Word16
-    , scanComponentCount :: !Word8
-    , scans :: [JpgScanSpecification]
-
-      -- | (begin, end)
-    , spectralSelection    :: (Word8, Word8)
-
-      -- | Encoded as 4 bits
-    , successiveApproxHigh :: !Word8
-
-      -- | Encoded as 4 bits
-    , successiveApproxLow :: !Word8
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgScanHeader
-
-instance SizeCalculable JpgScanHeader where
-    calculateSize hdr = 2 + 1
-                      + sum [calculateSize c | c <- scans hdr]
-                      + 2
-                      + 1
-
-data JpgQuantTableSpec = JpgQuantTableSpec
-    { -- | Stored on 4 bits
-      quantPrecision     :: !Word8
-
-      -- | Stored on 4 bits
-    , quantDestination   :: !Word8
-
-    , quantTable         :: MacroBlock Int16
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgQuantTableSpec
-
-class SizeCalculable a where
-    calculateSize :: a -> Int
-
--- | Type introduced only to avoid some typeclass overlapping
--- problem
-newtype TableList a = TableList [a]
-
-instance (SizeCalculable a, Binary a) => Binary (TableList a) where
-    put (TableList lst) = do
-        putWord16be . fromIntegral $ sum [calculateSize table | table <- lst] + 2
-        mapM_ put lst
-
-    get = TableList <$> (getWord16be >>= \s -> innerParse (fromIntegral s - 2))
-      where innerParse :: Int -> Get [a]
-            innerParse 0    = return []
-            innerParse size = do
-                onStart <- fromIntegral <$> bytesRead
-                table <- get
-                onEnd <- fromIntegral <$> bytesRead
-                (table :) <$> innerParse (size - (onEnd - onStart))
-
-instance SizeCalculable JpgQuantTableSpec where
-    calculateSize table =
-        1 + (fromIntegral (quantPrecision table) + 1) * 64
-
-instance Binary JpgQuantTableSpec where
-    put table = do
-        let precision = quantPrecision table
-        put4BitsOfEach precision (quantDestination table)
-        forM_ (VS.toList $ quantTable table) $ \coeff ->
-            if precision == 0 then putWord8 $ fromIntegral coeff
-                             else putWord16be $ fromIntegral coeff
-
-    get = do
-        (precision, dest) <- get4BitOfEach
-        coeffs <- replicateM 64 $ if precision == 0
-                then fromIntegral <$> getWord8
-                else fromIntegral <$> getWord16be
-        return JpgQuantTableSpec
-            { quantPrecision = precision
-            , quantDestination = dest
-            , quantTable = VS.fromListN 64 coeffs
-            }
-
-data JpgHuffmanTableSpec = JpgHuffmanTableSpec
-    { -- | 0 : DC, 1 : AC, stored on 4 bits
-      huffmanTableClass       :: !DctComponent
-      -- | Stored on 4 bits
-    , huffmanTableDest        :: !Word8
-
-    , huffSizes :: !(VU.Vector Word8)
-    , huffCodes :: !(V.Vector (VU.Vector Word8))
-    }
-    deriving (Eq, Show, Generic)
-instance NFData JpgHuffmanTableSpec
-
-instance SizeCalculable JpgHuffmanTableSpec where
-    calculateSize table = 1 + 16 + sum [fromIntegral e | e <- VU.toList $ huffSizes table]
-
-instance Binary JpgHuffmanTableSpec where
-    put table = do
-        let classVal = if huffmanTableClass table == DcComponent
-                          then 0 else 1
-        put4BitsOfEach classVal $ huffmanTableDest table
-        mapM_ put . VU.toList $ huffSizes table
-        forM_ [0 .. 15] $ \i ->
-            when (huffSizes table ! i /= 0)
-                 (let elements = VU.toList $ huffCodes table V.! i
-                  in mapM_ put elements)
-
-    get = do
-        (huffClass, huffDest) <- get4BitOfEach
-        sizes <- replicateM 16 getWord8
-        codes <- forM sizes $ \s ->
-            VU.replicateM (fromIntegral s) getWord8
-        return JpgHuffmanTableSpec
-            { huffmanTableClass =
-                if huffClass == 0 then DcComponent else AcComponent
-            , huffmanTableDest = huffDest
-            , huffSizes = VU.fromListN 16 sizes
-            , huffCodes = V.fromListN 16 codes
-            }
-
-instance Binary JpgImage where
-    put (JpgImage { jpgFrame = frames }) =
-        putWord8 0xFF >> putWord8 0xD8 >> mapM_ putFrame frames
-            >> putWord8 0xFF >> putWord8 0xD9
-
-    -- | Consider using `getJpgImage` instead for a non-semi-lazy implementation.
-    get = do
-        skipUntilFrames
-        frames <- parseFramesSemiLazy
-        -- let endOfImageMarker = 0xD9
-        {-checkMarker commonMarkerFirstByte endOfImageMarker-}
-        return JpgImage { jpgFrame = frames }
-
--- | Like `get` from `instance Binary JpgImage`, but without the legacy
--- semi-lazy implementation.
-getJpgImage :: Get JpgImage
-getJpgImage = do
-    skipUntilFrames
-    frames <- parseFrames
-    return JpgImage { jpgFrame = frames }
-
-skipUntilFrames :: Get ()
-skipUntilFrames = do
-    let startOfImageMarker = 0xD8
-    checkMarker commonMarkerFirstByte startOfImageMarker
-    eatUntilCode
-
-eatUntilCode :: Get ()
-eatUntilCode = do
-    code <- getWord8
-    unless (code == 0xFF) eatUntilCode
-
-takeCurrentFrame :: Get B.ByteString
-takeCurrentFrame = do
-    size <- getWord16be
-    getByteString (fromIntegral size - 2)
-
-putFrame :: JpgFrame -> Put
-putFrame (JpgAdobeAPP14 adobe) =
-    put (JpgAppSegment 14) >> putWord16be 14 >> put adobe
-putFrame (JpgJFIF jfif) =
-    put (JpgAppSegment 0) >> putWord16be (14+2) >> put jfif
-putFrame (JpgExif exif) = putExif exif
-putFrame (JpgAppFrame appCode str) =
-    put (JpgAppSegment appCode) >> putWord16be (fromIntegral $ B.length str) >> put str
-putFrame (JpgExtension appCode str) =
-    put (JpgExtensionSegment appCode) >> putWord16be (fromIntegral $ B.length str) >> put str
-putFrame (JpgQuantTable tables) =
-    put JpgQuantizationTable >> put (TableList tables)
-putFrame (JpgHuffmanTable tables) =
-    put JpgHuffmanTableMarker >> put (TableList $ map fst tables)
-putFrame (JpgIntervalRestart size) =
-    put JpgRestartInterval >> put (RestartInterval size)
-putFrame (JpgScanBlob hdr blob) =
-    put JpgStartOfScan >> put hdr >> putLazyByteString blob
-putFrame (JpgScans kind hdr) =
-    put kind >> put hdr
-
---------------------------------------------------
-----            Serialization instances
---------------------------------------------------
-commonMarkerFirstByte :: Word8
-commonMarkerFirstByte = 0xFF
-
-checkMarker :: Word8 -> Word8 -> Get ()
-checkMarker b1 b2 = do
-    rb1 <- getWord8
-    rb2 <- getWord8
-    when (rb1 /= b1 || rb2 /= b2)
-         (fail "Invalid marker used")
-
--- | Simpler implementation of `parseECS` to allow an easier understanding
--- of the logic, and to provide a comparison for correctness.
-parseECS_simple :: Get L.ByteString
-parseECS_simple = do
-    -- There's no efficient way in `binary` to parse byte-by-byte while assembling a
-    -- resulting ByteString (without using `.Internal` modules, which is what
-    --  `parseECS` does), so instead first compute the length of the content
-    -- byte-by-byte inside a `lookAhead` (not advancing the parser offset), and
-    -- then efficiently take that long a ByteString (advancing the parser offset).
-    --
-    -- This is still slow compared to `parseECS` because parser functions
-    -- (`getWord8`) are used repeatedly, instead of plain loops over ByteString contents.
-    -- The slowdown is ~2x on GHC 8.10.7 on an Intel Core i7-7500U.
-    n <- lookAhead getContentLength
-    getLazyByteString n
-  where
-    getContentLength :: Get ByteOffset
-    getContentLength = do
-        bytesReadBeforeContent <- bytesRead
-        let loop :: Word8 -> Get ByteOffset
-            loop !v = do
-                vNext <- getWord8
-                let isReset = 0xD0 <= vNext && vNext <= 0xD7
-                let vIsSegmentMarker = v == 0xFF && vNext /= 0 && not isReset
-                if not vIsSegmentMarker
-                    then loop vNext
-                    else do
-                        bytesReadAfterContentPlus2 <- bytesRead -- "plus 2" because we've also read the segment marker (0xFF and `vNext`)
-                        let !contentLength = (bytesReadAfterContentPlus2 - 2) - bytesReadBeforeContent
-                        return contentLength
-
-        v_first <- getWord8
-        loop v_first
-
--- Replace by `Data.ByteString.dropEnd` once we require `bytestring >= 0.11.1.0`.
-bsDropEnd :: Int -> B.ByteString -> B.ByteString
-bsDropEnd n bs
-    | n <= 0    = bs
-    | n >= len  = B.empty
-    | otherwise = B.take (len - 1) bs
-  where
-    len = B.length bs
-{-# INLINE bsDropEnd #-}
-
--- | Parses a Scan's ECS (Entropy-Coded Segment, the largest part of compressed image data)
--- from the `Get` stream.
---
--- When this function is called, the parser's offset should be
--- immediately behind the SOS tag.
---
--- As described on e.g. https://www.ccoderun.ca/programming/2017-01-31_jpeg/,
---
--- > To find the next segment after the SOS, you must keep reading until you
--- > find a 0xFF bytes which is not immediately followed by 0x00 (see "byte stuffing")
--- > [or a reset marker's byte: 0xD0 through 0xD7].
--- > Normally, this will be the EOI segment that comes at the end of the file.
---
--- where the 0xFF is the next segment's marker.
--- See https://github.com/corkami/formats/blob/master/image/jpeg.md#entropy-coded-segment
--- for more details.
---
--- This function returns the ECS, not including the next segment's
--- marker on its trailing end.
-parseECS :: Get L.ByteString
-parseECS = do
-    -- For a simpler but slower implementation of this function, see
-    -- `parseECS_simple`.
-
-    v_first <- getWord8
-    -- TODO: Compare with what `scan` from `binary-parsers` does.
-    --       Probably we cannot use it because it does not allow us to set the parser state
-    --       to be _before_ the segment marker which would be convenient to not have to
-    --       make a special case the function that calls this function.
-    --       But `scan` works on pointers into the bytestring chunks. Why, for performance?
-    --       I've asked on https://github.com/winterland1989/binary-parsers/issues/7
-    --       If that is for performance, we may want to replicate the same thing here.
-    --
-    --       An orthogonal idea is to use `Data.ByteString.elemIndex` to fast-forward
-    --       to the next 0xFF using `memchr`, but the `unsafe` call to `memchr` might
-    --       have too much overhead, since 0xFF bytes appear statistically every 256 bytes.
-    --       See https://stackoverflow.com/questions/14519905/how-much-does-it-cost-for-haskell-ffi-to-go-into-c-and-back
-
-    -- `withInputChunks` allows us to work on chunks of ByteStrings,
-    -- reducing the number of higher-overhead `Get` functions called.
-    -- It also allows to easily assemble the ByteString to return,
-    -- which may be cross-chunk.
-    -- `withInputChunks` terminates when we return a
-    --     Right (consumed :: ByteString, unconsumed :: ByteString)
-    -- from `consumeChunk`, setting the `Get` parser's offset to just before `unconsumed`.
-    -- Because the segment marker we seek may be the 2 bytes across chunk boundaries,
-    -- we need to keep a reference to the previous chunk (initialised as `B.empty`),
-    -- so that we can set `consumed` properly, because this function is supposed
-    -- to not consume the start of the segment marker (see code dropping the last
-    -- byte of the previous chunk below).
-    GetInternal.withInputChunks
-        (v_first, B.empty)
-        consumeChunk
-        (         L.fromChunks . (B.singleton v_first :)) -- `v_first` also belongs to the returned BS
-        (return . L.fromChunks . (B.singleton v_first :)) -- `v_first` also belongs to the returned BS
-  where
-    consumeChunk :: GetInternal.Consume (Word8, B.ByteString) -- which is: (Word8, B.ByteString) -> B.ByteString -> Either (Word8, B.ByteString) (B.ByteString, B.ByteString)
-    consumeChunk (!v_chunk_start, !prev_chunk) !chunk
-        -- If `withInputChunks` hands us an empty chunk (which `binary` probably
-        -- won't do, but since that's not documented, handle it anyway) then skip over it,
-        -- so that we always remember the last `prev_chunk` that actually has data in it,
-        -- since we `bsDropEnd 1 prev_chunk` in the `case` below.
-        | B.null chunk = Left (v_chunk_start, prev_chunk)
-        | otherwise = loop v_chunk_start 0
-          where
-            loop :: Word8 -> Int -> Either (Word8, B.ByteString) (B.ByteString, B.ByteString)
-            loop !v !offset_in_chunk
-                | offset_in_chunk >= B.length chunk = Left (v, chunk)
-                | otherwise =
-                    let !vNext = BU.unsafeIndex chunk offset_in_chunk -- bounds check is done above
-                        !isReset = 0xD0 <= vNext && vNext <= 0xD7
-                        !vIsSegmentMarker = v == 0xFF && vNext /= 0 && not isReset
-                    in
-                        if not vIsSegmentMarker
-                            then loop vNext (offset_in_chunk+1)
-                            else
-                                -- Set the parser state to _before_ the segment marker.
-                                -- The first case, where the segment marker's 2 bytes are exactly
-                                -- at the chunk boundary, requires us to allocate a new BS with
-                                -- `B.cons`; luckily this case should be rare.
-                                let (!consumed, !unconsumed) = case () of
-                                     () | offset_in_chunk == 0 -> (bsDropEnd 1 prev_chunk, v `B.cons` chunk) -- segment marker starts at `v`, which is the last byte of the previous chunk
-                                        | offset_in_chunk == 1 -> (B.empty, chunk) -- segment marker starts exactly at `chunk`
-                                        | otherwise            -> B.splitAt (offset_in_chunk - 1) chunk -- segment marker starts at `v`, which is 1 before `vNext` (which is at `offset_in_chunk`)
-                                in Right $! (consumed, unconsumed)
-
-
-
-parseAdobe14 :: B.ByteString -> Maybe JpgFrame
-parseAdobe14 str = case runGetStrict get str of
-    Left _err -> Nothing
-    Right app14 -> Just $! JpgAdobeAPP14 app14
-
--- | Parse JFIF or JFXX information. Right now only JFIF.
-parseJF__ :: B.ByteString -> Maybe JpgFrame
-parseJF__ str = case runGetStrict get str of
-    Left _err -> Nothing
-    Right jfif -> Just $! JpgJFIF jfif
-
-parseExif :: B.ByteString -> Maybe JpgFrame
-parseExif str
-  | exifHeader `B.isPrefixOf` str =
-      let
-        tiff = B.drop (B.length exifHeader) str
-      in
-        case runGetStrict (getP tiff) tiff of
-            Left _err -> Nothing
-            Right (_hdr :: TiffHeader, []) -> Nothing
-            Right (_hdr :: TiffHeader, ifds : _) -> Just $! JpgExif ifds
-  | otherwise = Nothing
-  where
-    exifHeader = BC.pack "Exif\0\0"
-
-putExif :: [ImageFileDirectory] -> Put
-putExif ifds = putAll where
-  hdr = TiffHeader
-    { hdrEndianness = EndianBig
-    , hdrOffset = 8
-    }
-
-  ifdList = case partition (isInIFD0 . ifdIdentifier) ifds of
-    (ifd0, []) -> [ifd0]
-    (ifd0, ifdExif) -> [ifd0 <> pure exifOffsetIfd, ifdExif]
-
-  exifBlob = runPut $ do
-    putByteString $ BC.pack "Exif\0\0"
-    putP BC.empty (hdr, ifdList)
-
-  putAll = do
-    put (JpgAppSegment 1)
-    putWord16be . fromIntegral $ L.length exifBlob + 2
-    putLazyByteString exifBlob
-
-skipFrameMarker :: Get ()
-skipFrameMarker = do
-    word <- getWord8
-    when (word /= 0xFF) $ do
-        readedData <- bytesRead
-        fail $ "Invalid Frame marker (" ++ show word
-                ++ ", bytes read : " ++ show readedData ++ ")"
-
--- | Parses a single frame.
---
--- Returns `Nothing` when we encounter a frame we want to skip.
-parseFrameOfKind :: JpgFrameKind -> Get (Maybe JpgFrame)
-parseFrameOfKind kind = do
-    case kind of
-        JpgEndOfImage -> return Nothing
-        JpgAppSegment 0 -> parseJF__ <$> takeCurrentFrame
-        JpgAppSegment 1 -> parseExif <$> takeCurrentFrame
-        JpgAppSegment 14 -> parseAdobe14 <$> takeCurrentFrame
-        JpgAppSegment c -> Just . JpgAppFrame c <$> takeCurrentFrame
-        JpgExtensionSegment c -> Just . JpgExtension c <$> takeCurrentFrame
-        JpgQuantizationTable ->
-            (\(TableList quants) -> Just $! JpgQuantTable quants) <$> get
-        JpgRestartInterval ->
-            (\(RestartInterval i) -> Just $! JpgIntervalRestart i) <$> get
-        JpgHuffmanTableMarker ->
-            (\(TableList huffTables) -> Just $!
-                    JpgHuffmanTable [(t, packHuffmanTree . buildPackedHuffmanTree $ huffCodes t) | t <- huffTables])
-                    <$> get
-        JpgStartOfScan -> do
-            scanHeader <- get
-            ecs <- parseECS
-            return $! Just $! JpgScanBlob scanHeader ecs
-        _ -> Just . JpgScans kind <$> get
-
-
--- | Parse a list of `JpgFrame`s.
---
--- This function has various quirks; consider the below with great caution
--- when using this function.
---
--- While @data JpgFrame = ... | JpgScanBlob !...` itself has strict fields,
---
--- This function is written in such a way that that it can construct
--- the @[JpgFrame]@ "lazily" such that the expensive byte-by-byte traversal
--- in `parseECS` to create a `JpgScanBlob` can be avoided if only
--- list elements before that `JpgScanBlob` are evaluated.
---
--- That means the user can write code such as
---
--- > let mbFirstScan =
--- >       case runGetOrFail (get @JPG.JpgImage) hugeImageByteString of -- (`get @JPG.JpgImage` uses `parseFramesSemiLazy`)
--- >         Right (_restBs, _offset, res) ->
--- >           find (\frame -> case frame of { JPG.JpgScans{} -> True; _ -> False }) (JPG.jpgFrame res)
---
--- with the guarantee that only the bytes before the ECS (large compressed image data)
--- will be inspected, assuming that indeed there is at least 1 `JpgScan` in front
--- of the `JpgScanBlob` that contains the ECS.
---
--- This guarantee can be useful to e.g. quickly read just the image
--- dimensions (width, height) without traversing the large data.
---
--- Also note that this `Get` parser does not correctly maintain the parser byte offset
--- (`Data.Binary.Get.bytesRead`), because as soon as a `JpgStartOfScan` is returned,
--- it uses `Data.Binary.Get.getRemainingLazyBytes` to provide:
---
--- 1. the laziness described above, and
--- 2. the ability to ignore any parser failure after the first successfully-parsed
---    `JpgScanBlob` (it is debatable whether this behaviour is a desirable behaviour of this
---    library, but it is historically so and existing exposed functions do not break
---    this for backwards compatibility with existing uses of this library).
---    This fact also means that even `parseNextFrameStrict` cannot maintain
---    correct parser byte offsets.
---
--- Further note that if you are reading a huge JPEG image from disk strictly,
--- this will already incur a full traversal (namely creation) of the `hugeImageByteString`.
--- Thus, `parseNextFrameLazy` only provides any benefit if you:
---
--- - read the image from disk using lazy IO (not recommended!) such as via
---   `Data.ByteString.Lazy.readFile`,
--- - or do something similar, such as creating the `hugeImageByteString` via @mmap()@
---
--- This function is called "semi lazy" because only the first `JpgScanBlob` returned
--- in the `[JpgFrame]` is returned lazily; frames of other types, or multiple
--- `JpgScanBlob`s, are confusingly not dealt with lazily.
---
--- If as a caller you do not want to deal with any of these quirks,
--- and use proper strict IO and/or via `Data.Binary.Get`'s incremental input interface:
---
--- - If you want the whole `[JpgFrame]`: use `parseFrames`.
--- - If you want parsing to terminate early as in the example shown above,
---   use in combination with just the right amount of `get :: Get JpgFrameKind`,
---   `parseFrameOfKind`, and `skipFrameMarker`.
-parseFramesSemiLazy :: Get [JpgFrame]
-parseFramesSemiLazy = do
-    kind <- get
-    case kind of
-        -- The end-of-image case needs to be here because `_ ->` default case below
-        -- unconditionally uses `skipFrameMarker` which does not exist after `JpgEndOfImage`.
-        JpgEndOfImage -> pure []
-        JpgStartOfScan -> do
-            scanHeader <- get
-            remainingBytes <- getRemainingLazyBytes
-            -- It is after the above `getRemainingLazyBytes` that the `Get` parser lazily succeeds,
-            -- allowing consumers of `parseFramesSemiLazy` evaluate all `[JpgFrame]` list elements
-            -- until (excluding) the cons-cell around the `JpgScanBlob ...` we construct below.
-
-            return $ case runGet parseECS remainingBytes of
-                Left _ ->
-                    -- Construct invalid `JpgScanBlob` even when the compressed JPEG
-                    -- data is truncated or otherwise invalid, because that's what JuicyPixels's
-                    -- `parseFramesSemiLazy` function did in the past, for backwards compat.
-                    [JpgScanBlob scanHeader remainingBytes]
-                Right ecs ->
-                    JpgScanBlob scanHeader ecs
-                    :
-                    -- TODO Why `drop 1` instead of `runGet (skipFrameMarker *> parseFramesSemiLazy) remainingBytes` that would check that the dropped 1 Byte is really a frame marker?
-                    case runGet parseFramesSemiLazy (L.drop (L.length ecs + 1) remainingBytes) of
-                        -- After we've encountered the first scan blob containing encoded image data,
-                        -- we accept anything else after to fail parsing, ignoring that failure,
-                        -- end emitting no further frames.
-                        -- TODO: Explain why JuicyPixel chose to use this logic, insteaed of failing.
-                        Left _ -> []
-                        Right remainingFrames -> remainingFrames
-        _ -> do
-            mbFrame <- parseFrameOfKind kind
-            skipFrameMarker
-            remainingFrames <- parseFramesSemiLazy
-            return $ maybeToList mbFrame ++ remainingFrames
-
--- | Parse a list of `JpgFrame`s.
-parseFrames :: Get [JpgFrame]
-parseFrames = do
-    kind <- get
-    case kind of
-        JpgEndOfImage -> pure []
-        _ -> do
-            mbFrame <- parseFrameOfKind kind
-            skipFrameMarker
-            remainingFrames <- parseFrames
-            return $ maybeToList mbFrame ++ remainingFrames
-
--- | Parse a list of `JpgFrameKind`s with their corresponding offsets and lengths
--- (not counting the segment and frame markers into the lengths).
---
--- Useful for debugging.
-parseFrameKinds :: Get [(JpgFrameKind, Int64, Int64)]
-parseFrameKinds = do
-    kindMarkerOffset :: Int64 <- bytesRead
-    kind <- get
-    case kind of
-        JpgEndOfImage -> pure [(JpgEndOfImage, kindMarkerOffset, 0)]
-        _ -> do
-            parserOffsetBefore <- bytesRead
-            _ <- parseFrameOfKind kind
-            parserOffsetAfter <- bytesRead
-            let !segmentLengthWithoutMarker = parserOffsetAfter - parserOffsetBefore
-            skipFrameMarker
-            remainingKinds <- parseFrameKinds
-            return $ (kind, kindMarkerOffset, segmentLengthWithoutMarker):remainingKinds
-
--- | Parses forward, returning the first scan header encountered.
---
--- Should be used after `skipUntilFrames`.
---
--- Fails parsing when an SOS segment marker (`JpgStartOfScan`, resulting
--- in `JpgScanBlob`) is encountered before an SOF segment marker (that
--- results in `JpgScans` carrying the `JpgFrameHeader`).
-parseToFirstFrameHeader :: Get (Maybe JpgFrameHeader)
-parseToFirstFrameHeader = do
-    kind <- get
-    case kind of
-        JpgEndOfImage -> return Nothing
-        JpgStartOfScan -> fail "parseToFirstFrameHeader: Encountered SOS frame marker before frame header that tells its dimensions"
-        _ -> do
-            mbFrame <- parseFrameOfKind kind
-            case mbFrame of
-                Nothing -> continueSearching
-                Just frame -> case frame of
-                    JpgScans _ frameHeader -> return $ Just $! frameHeader
-                    _ -> continueSearching
-  where
-    continueSearching = do
-        skipFrameMarker
-        parseToFirstFrameHeader
-
-buildPackedHuffmanTree :: V.Vector (VU.Vector Word8) -> HuffmanTree
-buildPackedHuffmanTree = buildHuffmanTree . map VU.toList . V.toList
-
-secondStartOfFrameByteOfKind :: JpgFrameKind -> Word8
-secondStartOfFrameByteOfKind = aux
-  where
-    aux JpgBaselineDCTHuffman = 0xC0
-    aux JpgExtendedSequentialDCTHuffman = 0xC1
-    aux JpgProgressiveDCTHuffman = 0xC2
-    aux JpgLosslessHuffman = 0xC3
-    aux JpgDifferentialSequentialDCTHuffman = 0xC5
-    aux JpgDifferentialProgressiveDCTHuffman = 0xC6
-    aux JpgDifferentialLosslessHuffman = 0xC7
-    aux JpgExtendedSequentialArithmetic = 0xC9
-    aux JpgProgressiveDCTArithmetic = 0xCA
-    aux JpgLosslessArithmetic = 0xCB
-    aux JpgHuffmanTableMarker = 0xC4
-    aux JpgDifferentialSequentialDCTArithmetic = 0xCD
-    aux JpgDifferentialProgressiveDCTArithmetic = 0xCE
-    aux JpgDifferentialLosslessArithmetic = 0xCF
-    aux JpgEndOfImage = 0xD9
-    aux JpgQuantizationTable = 0xDB
-    aux JpgStartOfScan = 0xDA
-    aux JpgRestartInterval = 0xDD
-    aux (JpgRestartIntervalEnd v) = v
-    aux (JpgAppSegment a) = (a + 0xE0)
-    aux (JpgExtensionSegment a) = a
-
-data JpgImageKind = BaseLineDCT | ProgressiveDCT
-
-instance Binary JpgFrameKind where
-    put v = putWord8 0xFF >> put (secondStartOfFrameByteOfKind v)
-    get = do
-        -- no lookahead :(
-        {-word <- getWord8-}
-        word2 <- getWord8
-        case word2 of
-            0xC0 -> return JpgBaselineDCTHuffman
-            0xC1 -> return JpgExtendedSequentialDCTHuffman
-            0xC2 -> return JpgProgressiveDCTHuffman
-            0xC3 -> return JpgLosslessHuffman
-            0xC4 -> return JpgHuffmanTableMarker
-            0xC5 -> return JpgDifferentialSequentialDCTHuffman
-            0xC6 -> return JpgDifferentialProgressiveDCTHuffman
-            0xC7 -> return JpgDifferentialLosslessHuffman
-            0xC9 -> return JpgExtendedSequentialArithmetic
-            0xCA -> return JpgProgressiveDCTArithmetic
-            0xCB -> return JpgLosslessArithmetic
-            0xCD -> return JpgDifferentialSequentialDCTArithmetic
-            0xCE -> return JpgDifferentialProgressiveDCTArithmetic
-            0xCF -> return JpgDifferentialLosslessArithmetic
-            0xD9 -> return JpgEndOfImage
-            0xDA -> return JpgStartOfScan
-            0xDB -> return JpgQuantizationTable
-            0xDD -> return JpgRestartInterval
-            a | a >= 0xF0 -> return $! JpgExtensionSegment a
-              | a >= 0xE0 -> return $! JpgAppSegment (a - 0xE0)
-              | a >= 0xD0 && a <= 0xD7 -> return $! JpgRestartIntervalEnd a
-              | otherwise -> fail ("Invalid frame marker (" ++ show a ++ ")")
-
-put4BitsOfEach :: Word8 -> Word8 -> Put
-put4BitsOfEach a b = put $ (a `unsafeShiftL` 4) .|. b
-
-get4BitOfEach :: Get (Word8, Word8)
-get4BitOfEach = do
-    val <- get
-    return ((val `unsafeShiftR` 4) .&. 0xF, val .&. 0xF)
-
-newtype RestartInterval = RestartInterval Word16
-
-instance Binary RestartInterval where
-    put (RestartInterval i) = putWord16be 4 >> putWord16be i
-    get = do
-        size <- getWord16be
-        when (size /= 4) (fail "Invalid jpeg restart interval size")
-        RestartInterval <$> getWord16be
-
-instance Binary JpgComponent where
-    get = do
-        ident <- getWord8
-        (horiz, vert) <- get4BitOfEach
-        quantTableIndex <- getWord8
-        return JpgComponent
-            { componentIdentifier = ident
-            , horizontalSamplingFactor = horiz
-            , verticalSamplingFactor = vert
-            , quantizationTableDest = quantTableIndex
-            }
-    put v = do
-        put $ componentIdentifier v
-        put4BitsOfEach (horizontalSamplingFactor v) $ verticalSamplingFactor v
-        put $ quantizationTableDest v
-
-instance Binary JpgFrameHeader where
-    get = do
-        beginOffset <- fromIntegral <$> bytesRead
-        frmHLength <- getWord16be
-        samplePrec <- getWord8
-        h <- getWord16be
-        w <- getWord16be
-        compCount <- getWord8
-        components <- replicateM (fromIntegral compCount) get
-        endOffset <- fromIntegral <$> bytesRead
-        when (beginOffset - endOffset < fromIntegral frmHLength)
-             (skip $ fromIntegral frmHLength - (endOffset - beginOffset))
-        return JpgFrameHeader
-            { jpgFrameHeaderLength = frmHLength
-            , jpgSamplePrecision = samplePrec
-            , jpgHeight = h
-            , jpgWidth = w
-            , jpgImageComponentCount = compCount
-            , jpgComponents = components
-            }
-
-    put v = do
-        putWord16be $ jpgFrameHeaderLength v
-        putWord8    $ jpgSamplePrecision v
-        putWord16be $ jpgHeight v
-        putWord16be $ jpgWidth v
-        putWord8    $ jpgImageComponentCount v
-        mapM_ put   $ jpgComponents v
-
-instance Binary JpgScanSpecification where
-    put v = do
-        put $ componentSelector v
-        put4BitsOfEach (dcEntropyCodingTable v) $ acEntropyCodingTable v
-
-    get = do
-        compSel <- get
-        (dc, ac) <- get4BitOfEach
-        return JpgScanSpecification {
-            componentSelector = compSel
-          , dcEntropyCodingTable = dc
-          , acEntropyCodingTable = ac
-          }
-
-instance Binary JpgScanHeader where
-    get = do
-        thisScanLength <- getWord16be
-        compCount <- getWord8
-        comp <- replicateM (fromIntegral compCount) get
-        specBeg <- get
-        specEnd <- get
-        (approxHigh, approxLow) <- get4BitOfEach
-
-        return JpgScanHeader {
-            scanLength = thisScanLength,
-            scanComponentCount = compCount,
-            scans = comp,
-            spectralSelection = (specBeg, specEnd),
-            successiveApproxHigh = approxHigh,
-            successiveApproxLow = approxLow
-        }
-
-    put v = do
-        putWord16be $ scanLength v
-        putWord8 $ scanComponentCount v
-        mapM_ put $ scans v
-        putWord8 . fst $ spectralSelection v
-        putWord8 . snd $ spectralSelection v
-        put4BitsOfEach (successiveApproxHigh v) $ successiveApproxLow v
-
-{-# INLINE createEmptyMutableMacroBlock #-}
--- | Create a new macroblock with the good array size
-createEmptyMutableMacroBlock :: (Storable a, Num a) => ST s (MutableMacroBlock s a)
-createEmptyMutableMacroBlock = M.replicate 64 0
-
-printMacroBlock :: (Storable a, PrintfArg a)
-                => MutableMacroBlock s a -> ST s String
-printMacroBlock block = pLn 0
-    where pLn 64 = return "===============================\n"
-          pLn i = do
-              v <- block `M.unsafeRead` i
-              vn <- pLn (i+1)
-              return $ printf (if i `mod` 8 == 0 then "\n%5d " else "%5d ") v ++ vn
-
-printPureMacroBlock :: (Storable a, PrintfArg a) => MacroBlock a -> String
-printPureMacroBlock block = pLn 0
-    where pLn 64 = "===============================\n"
-          pLn i = str ++ pLn (i + 1)
-            where str | i `mod` 8 == 0 = printf "\n%5d " v
-                      | otherwise = printf "%5d" v
-                  v = block VS.! i
-
-
-{-# INLINE dctBlockSize #-}
-dctBlockSize :: Num a => a
-dctBlockSize = 8
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE CPP #-}
+
+-- | A good explanation of the JPEG format, including diagrams, is given at:
+-- <https://github.com/corkami/formats/blob/master/image/jpeg.md>
+--
+-- The full spec (excluding EXIF): https://www.w3.org/Graphics/JPEG/itu-t81.pdf
+module Codec.Picture.Jpg.Internal.Types( MutableMacroBlock
+                              , createEmptyMutableMacroBlock
+                              , printMacroBlock
+                              , printPureMacroBlock
+                              , DcCoefficient
+                              , JpgImage( .. )
+                              , JpgComponent( .. )
+                              , JpgFrameHeader( .. )
+                              , JpgFrame( .. )
+                              , JpgFrameKind( .. )
+                              , JpgScanHeader( .. )
+                              , JpgQuantTableSpec( .. )
+                              , JpgHuffmanTableSpec( .. )
+                              , JpgImageKind( .. )
+                              , JpgScanSpecification( .. )
+                              , JpgColorSpace( .. )
+                              , AdobeTransform( .. )
+                              , JpgAdobeApp14( .. )
+                              , JpgJFIFApp0( .. )
+                              , JFifUnit( .. )
+                              , TableList( .. )
+                              , RestartInterval( .. )
+                              , getJpgImage
+                              , calculateSize
+                              , dctBlockSize
+                              , parseECS
+                              , parseECS_simple
+                              , skipUntilFrames
+                              , skipFrameMarker
+                              , parseFrameOfKind
+                              , parseFrames
+                              , parseFrameKinds
+                              , parseToFirstFrameHeader
+                              ) where
+
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( pure, (<*>), (<$>) )
+#endif
+
+import Control.DeepSeq( NFData(..) )
+import Control.Monad( when, replicateM, forM, forM_, unless )
+import Control.Monad.ST( ST )
+import Data.Bits( (.|.), (.&.), unsafeShiftL, unsafeShiftR )
+import Data.List( partition )
+import Data.Maybe( maybeToList )
+import GHC.Generics( Generic )
+
+#if !MIN_VERSION_base(4,11,0)
+import Data.Monoid( (<>) )
+#endif
+
+import Foreign.Storable ( Storable )
+import Data.Vector.Unboxed( (!) )
+import qualified Data.Vector as V
+import qualified Data.Vector.Unboxed as VU
+import qualified Data.Vector.Storable as VS
+import qualified Data.Vector.Storable.Mutable as M
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as BC
+import qualified Data.ByteString.Lazy as L
+import qualified Data.ByteString.Unsafe as BU
+
+import Data.Int( Int16, Int64 )
+import Data.Word(Word8, Word16 )
+import Data.Binary( Binary(..) )
+
+import Data.Binary.Get( Get
+                      , getWord8
+                      , getWord16be
+                      , getByteString
+                      , skip
+                      , bytesRead
+                      , lookAhead
+                      , ByteOffset
+                      , getLazyByteString
+                      )
+import qualified Data.Binary.Get.Internal as GetInternal
+
+import Data.Binary.Put( Put
+                      , putWord8
+                      , putWord16be
+                      , putLazyByteString
+                      , putByteString
+                      , runPut
+                      )
+
+import Codec.Picture.InternalHelper
+import Codec.Picture.Jpg.Internal.DefaultTable
+import Codec.Picture.Tiff.Internal.Types
+import Codec.Picture.Tiff.Internal.Metadata( exifOffsetIfd )
+import Codec.Picture.Metadata.Exif
+
+import Text.Printf
+
+-- | Type only used to make clear what kind of integer we are carrying
+-- Might be transformed into newtype in the future
+type DcCoefficient = Int16
+
+-- | Macroblock that can be transformed.
+type MutableMacroBlock s a = M.STVector s a
+
+data JpgFrameKind =
+      JpgBaselineDCTHuffman
+    | JpgExtendedSequentialDCTHuffman
+    | JpgProgressiveDCTHuffman
+    | JpgLosslessHuffman
+    | JpgDifferentialSequentialDCTHuffman
+    | JpgDifferentialProgressiveDCTHuffman
+    | JpgDifferentialLosslessHuffman
+    | JpgExtendedSequentialArithmetic
+    | JpgProgressiveDCTArithmetic
+    | JpgLosslessArithmetic
+    | JpgDifferentialSequentialDCTArithmetic
+    | JpgDifferentialProgressiveDCTArithmetic
+    | JpgDifferentialLosslessArithmetic
+    | JpgQuantizationTable
+    | JpgHuffmanTableMarker
+    | JpgStartOfScan
+    | JpgEndOfImage
+    | JpgAppSegment Word8
+    | JpgExtensionSegment Word8
+
+    | JpgRestartInterval
+    | JpgRestartIntervalEnd Word8
+    deriving (Eq, Show, Generic)
+instance NFData JpgFrameKind
+
+data JpgFrame =
+      JpgAppFrame        !Word8 B.ByteString
+    | JpgAdobeAPP14      !JpgAdobeApp14
+    | JpgJFIF            !JpgJFIFApp0
+    | JpgExif            ![ImageFileDirectory]
+    | JpgExtension       !Word8 B.ByteString
+    | JpgQuantTable      ![JpgQuantTableSpec]
+    | JpgHuffmanTable    ![(JpgHuffmanTableSpec, HuffmanPackedTree)]
+    | JpgScanBlob        !JpgScanHeader !L.ByteString -- ^ The @ByteString@ is the ECS (Entropy-Coded Segment), typically the largest part of compressed image data.
+    | JpgScans           !JpgFrameKind !JpgFrameHeader
+    | JpgIntervalRestart !Word16
+    deriving (Eq, Show, Generic)
+instance NFData JpgFrame
+
+data JpgColorSpace
+  = JpgColorSpaceYCbCr
+  | JpgColorSpaceYCC
+  | JpgColorSpaceY
+  | JpgColorSpaceYA
+  | JpgColorSpaceYCCA
+  | JpgColorSpaceYCCK
+  | JpgColorSpaceCMYK
+  | JpgColorSpaceRGB
+  | JpgColorSpaceRGBA
+  deriving (Eq, Show, Generic)
+instance NFData JpgColorSpace
+
+data AdobeTransform
+  = AdobeUnknown    -- ^ Value 0
+  | AdobeYCbCr      -- ^ value 1
+  | AdobeYCck       -- ^ value 2
+  deriving (Eq, Show, Generic)
+instance NFData AdobeTransform
+
+data JpgAdobeApp14 = JpgAdobeApp14
+  { _adobeDctVersion :: !Word16
+  , _adobeFlag0      :: !Word16
+  , _adobeFlag1      :: !Word16
+  , _adobeTransform  :: !AdobeTransform
+  }
+  deriving (Eq, Show, Generic)
+instance NFData JpgAdobeApp14
+
+-- | Size: 1
+data JFifUnit
+  = JFifUnitUnknown   -- ^ 0
+  | JFifPixelsPerInch -- ^ 1
+  | JFifPixelsPerCentimeter -- ^ 2
+  deriving (Eq, Show, Generic)
+instance NFData JFifUnit
+
+instance Binary JFifUnit where
+  put v = putWord8 $ case v of
+    JFifUnitUnknown -> 0
+    JFifPixelsPerInch -> 1
+    JFifPixelsPerCentimeter -> 2
+  get = do
+    v <- getWord8
+    pure $ case v of
+      0 -> JFifUnitUnknown
+      1 -> JFifPixelsPerInch
+      2 -> JFifPixelsPerCentimeter
+      _ -> JFifUnitUnknown
+
+data JpgJFIFApp0 = JpgJFIFApp0
+  { _jfifUnit      :: !JFifUnit
+  , _jfifDpiX      :: !Word16
+  , _jfifDpiY      :: !Word16
+  , _jfifThumbnail :: !(Maybe {- (Image PixelRGB8) -} Int)
+  }
+  deriving (Eq, Show, Generic)
+instance NFData JpgJFIFApp0
+
+instance Binary JpgJFIFApp0 where
+  get = do
+    sig <- getByteString 5
+    when (sig /= BC.pack "JFIF\0") $
+        fail "Invalid JFIF signature"
+    major <- getWord8
+    minor <- getWord8
+    when (major /= 1 && minor > 2) $
+        fail "Unrecognize JFIF version"
+    unit <- get
+    dpiX <- getWord16be
+    dpiY <- getWord16be
+    w <- getWord8
+    h <- getWord8
+    let pxCount = 3 * w * h
+    img <- case pxCount of
+      0 -> return Nothing
+      _ -> return Nothing
+    return $ JpgJFIFApp0
+        { _jfifUnit      = unit
+        , _jfifDpiX      = dpiX
+        , _jfifDpiY      = dpiY
+        , _jfifThumbnail = img
+        }
+
+
+  put jfif = do
+    putByteString $ BC.pack "JFIF\0" -- 5
+    putWord8 1                       -- 1 6
+    putWord8 2                       -- 1 7
+    put $ _jfifUnit jfif             -- 1 8
+    putWord16be $ _jfifDpiX jfif     -- 2 10
+    putWord16be $ _jfifDpiY jfif     -- 2 12
+    putWord8 0                       -- 1 13
+    putWord8 0                       -- 1 14
+
+{-Thumbnail width (tw) 	1 	Horizontal size of embedded JFIF thumbnail in pixels-}
+{-Thumbnail height (th) 	1 	Vertical size of embedded JFIF thumbnail in pixels-}
+{-Thumbnail data 	3 × tw × th 	Uncompressed 24 bit RGB raster thumbnail-}
+
+instance Binary AdobeTransform where
+  put v = case v of
+    AdobeUnknown -> putWord8 0
+    AdobeYCbCr -> putWord8 1
+    AdobeYCck -> putWord8 2
+
+  get = do
+    v <- getWord8
+    pure $ case v of
+      0 -> AdobeUnknown
+      1 -> AdobeYCbCr
+      2 -> AdobeYCck
+      _ -> AdobeUnknown
+
+instance Binary JpgAdobeApp14 where
+  get = do
+    let sig = BC.pack "Adobe"
+    fileSig <- getByteString 5
+    when (fileSig /= sig) $
+       fail "Invalid Adobe APP14 marker"
+    version <- getWord16be
+    when (version /= 100) $
+       fail $ "Invalid Adobe APP14 version " ++ show version
+    JpgAdobeApp14 version
+                  <$> getWord16be
+                  <*> getWord16be <*> get
+
+  put (JpgAdobeApp14 v f0 f1 t) = do
+    putByteString $ BC.pack "Adobe"
+    putWord16be v
+    putWord16be f0
+    putWord16be f1
+    put t
+
+
+data JpgFrameHeader = JpgFrameHeader
+    { jpgFrameHeaderLength   :: !Word16
+    , jpgSamplePrecision     :: !Word8
+    , jpgHeight              :: !Word16
+    , jpgWidth               :: !Word16
+    , jpgImageComponentCount :: !Word8
+    , jpgComponents          :: ![JpgComponent]
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgFrameHeader
+
+
+instance SizeCalculable JpgFrameHeader where
+    calculateSize hdr = 2 + 1 + 2 + 2 + 1
+                      + sum [calculateSize c | c <- jpgComponents hdr]
+
+data JpgComponent = JpgComponent
+    { componentIdentifier       :: !Word8
+      -- | Stored with 4 bits
+    , horizontalSamplingFactor  :: !Word8
+      -- | Stored with 4 bits
+    , verticalSamplingFactor    :: !Word8
+    , quantizationTableDest     :: !Word8
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgComponent
+
+instance SizeCalculable JpgComponent where
+    calculateSize _ = 3
+
+data JpgImage = JpgImage { jpgFrame :: [JpgFrame] }
+    deriving (Eq, Show, Generic)
+instance NFData JpgImage
+
+data JpgScanSpecification = JpgScanSpecification
+    { componentSelector :: !Word8
+      -- | Encoded as 4 bits
+    , dcEntropyCodingTable :: !Word8
+      -- | Encoded as 4 bits
+    , acEntropyCodingTable :: !Word8
+
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgScanSpecification
+
+instance SizeCalculable JpgScanSpecification where
+    calculateSize _ = 2
+
+data JpgScanHeader = JpgScanHeader
+    { scanLength :: !Word16
+    , scanComponentCount :: !Word8
+    , scans :: [JpgScanSpecification]
+
+      -- | (begin, end)
+    , spectralSelection    :: (Word8, Word8)
+
+      -- | Encoded as 4 bits
+    , successiveApproxHigh :: !Word8
+
+      -- | Encoded as 4 bits
+    , successiveApproxLow :: !Word8
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgScanHeader
+
+instance SizeCalculable JpgScanHeader where
+    calculateSize hdr = 2 + 1
+                      + sum [calculateSize c | c <- scans hdr]
+                      + 2
+                      + 1
+
+data JpgQuantTableSpec = JpgQuantTableSpec
+    { -- | Stored on 4 bits
+      quantPrecision     :: !Word8
+
+      -- | Stored on 4 bits
+    , quantDestination   :: !Word8
+
+    , quantTable         :: MacroBlock Int16
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgQuantTableSpec
+
+class SizeCalculable a where
+    calculateSize :: a -> Int
+
+-- | Type introduced only to avoid some typeclass overlapping
+-- problem
+newtype TableList a = TableList [a]
+
+instance (SizeCalculable a, Binary a) => Binary (TableList a) where
+    put (TableList lst) = do
+        putWord16be . fromIntegral $ sum [calculateSize table | table <- lst] + 2
+        mapM_ put lst
+
+    get = TableList <$> (getWord16be >>= \s -> innerParse (fromIntegral s - 2))
+      where innerParse :: Int -> Get [a]
+            innerParse 0    = return []
+            innerParse size = do
+                onStart <- fromIntegral <$> bytesRead
+                table <- get
+                onEnd <- fromIntegral <$> bytesRead
+                (table :) <$> innerParse (size - (onEnd - onStart))
+
+instance SizeCalculable JpgQuantTableSpec where
+    calculateSize table =
+        1 + (fromIntegral (quantPrecision table) + 1) * 64
+
+instance Binary JpgQuantTableSpec where
+    put table = do
+        let precision = quantPrecision table
+        put4BitsOfEach precision (quantDestination table)
+        forM_ (VS.toList $ quantTable table) $ \coeff ->
+            if precision == 0 then putWord8 $ fromIntegral coeff
+                             else putWord16be $ fromIntegral coeff
+
+    get = do
+        (precision, dest) <- get4BitOfEach
+        coeffs <- replicateM 64 $ if precision == 0
+                then fromIntegral <$> getWord8
+                else fromIntegral <$> getWord16be
+        return JpgQuantTableSpec
+            { quantPrecision = precision
+            , quantDestination = dest
+            , quantTable = VS.fromListN 64 coeffs
+            }
+
+data JpgHuffmanTableSpec = JpgHuffmanTableSpec
+    { -- | 0 : DC, 1 : AC, stored on 4 bits
+      huffmanTableClass       :: !DctComponent
+      -- | Stored on 4 bits
+    , huffmanTableDest        :: !Word8
+
+    , huffSizes :: !(VU.Vector Word8)
+    , huffCodes :: !(V.Vector (VU.Vector Word8))
+    }
+    deriving (Eq, Show, Generic)
+instance NFData JpgHuffmanTableSpec
+
+instance SizeCalculable JpgHuffmanTableSpec where
+    calculateSize table = 1 + 16 + sum [fromIntegral e | e <- VU.toList $ huffSizes table]
+
+instance Binary JpgHuffmanTableSpec where
+    put table = do
+        let classVal = if huffmanTableClass table == DcComponent
+                          then 0 else 1
+        put4BitsOfEach classVal $ huffmanTableDest table
+        mapM_ put . VU.toList $ huffSizes table
+        forM_ [0 .. 15] $ \i ->
+            when (huffSizes table ! i /= 0)
+                 (let elements = VU.toList $ huffCodes table V.! i
+                  in mapM_ put elements)
+
+    get = do
+        (huffClass, huffDest) <- get4BitOfEach
+        sizes <- replicateM 16 getWord8
+        codes <- forM sizes $ \s ->
+            VU.replicateM (fromIntegral s) getWord8
+        return JpgHuffmanTableSpec
+            { huffmanTableClass =
+                if huffClass == 0 then DcComponent else AcComponent
+            , huffmanTableDest = huffDest
+            , huffSizes = VU.fromListN 16 sizes
+            , huffCodes = V.fromListN 16 codes
+            }
+
+instance Binary JpgImage where
+    put (JpgImage { jpgFrame = frames }) =
+        putWord8 0xFF >> putWord8 0xD8 >> mapM_ putFrame frames
+            >> putWord8 0xFF >> putWord8 0xD9
+
+    -- | Consider using `getJpgImage` instead for a non-semi-lazy implementation.
+    get = do
+        skipUntilFrames
+        frames <- parseFramesSemiLazy
+        -- let endOfImageMarker = 0xD9
+        {-checkMarker commonMarkerFirstByte endOfImageMarker-}
+        return JpgImage { jpgFrame = frames }
+
+-- | Like `get` from `instance Binary JpgImage`, but without the legacy
+-- semi-lazy implementation.
+getJpgImage :: Get JpgImage
+getJpgImage = do
+    skipUntilFrames
+    frames <- parseFrames
+    return JpgImage { jpgFrame = frames }
+
+skipUntilFrames :: Get ()
+skipUntilFrames = do
+    let startOfImageMarker = 0xD8
+    checkMarker commonMarkerFirstByte startOfImageMarker
+    eatUntilCode
+
+eatUntilCode :: Get ()
+eatUntilCode = do
+    code <- getWord8
+    unless (code == 0xFF) eatUntilCode
+
+takeCurrentFrame :: Get B.ByteString
+takeCurrentFrame = do
+    size <- getWord16be
+    getByteString (fromIntegral size - 2)
+
+putFrame :: JpgFrame -> Put
+putFrame (JpgAdobeAPP14 adobe) =
+    put (JpgAppSegment 14) >> putWord16be 14 >> put adobe
+putFrame (JpgJFIF jfif) =
+    put (JpgAppSegment 0) >> putWord16be (14+2) >> put jfif
+putFrame (JpgExif exif) = putExif exif
+putFrame (JpgAppFrame appCode str) =
+    put (JpgAppSegment appCode) >> putWord16be (fromIntegral $ B.length str) >> put str
+putFrame (JpgExtension appCode str) =
+    put (JpgExtensionSegment appCode) >> putWord16be (fromIntegral $ B.length str) >> put str
+putFrame (JpgQuantTable tables) =
+    put JpgQuantizationTable >> put (TableList tables)
+putFrame (JpgHuffmanTable tables) =
+    put JpgHuffmanTableMarker >> put (TableList $ map fst tables)
+putFrame (JpgIntervalRestart size) =
+    put JpgRestartInterval >> put (RestartInterval size)
+putFrame (JpgScanBlob hdr blob) =
+    put JpgStartOfScan >> put hdr >> putLazyByteString blob
+putFrame (JpgScans kind hdr) =
+    put kind >> put hdr
+
+--------------------------------------------------
+----            Serialization instances
+--------------------------------------------------
+commonMarkerFirstByte :: Word8
+commonMarkerFirstByte = 0xFF
+
+checkMarker :: Word8 -> Word8 -> Get ()
+checkMarker b1 b2 = do
+    rb1 <- getWord8
+    rb2 <- getWord8
+    when (rb1 /= b1 || rb2 /= b2)
+         (fail "Invalid marker used")
+
+-- | Simpler implementation of `parseECS` to allow an easier understanding
+-- of the logic, and to provide a comparison for correctness.
+parseECS_simple :: Get L.ByteString
+parseECS_simple = do
+    -- There's no efficient way in `binary` to parse byte-by-byte while assembling a
+    -- resulting ByteString (without using `.Internal` modules, which is what
+    --  `parseECS` does), so instead first compute the length of the content
+    -- byte-by-byte inside a `lookAhead` (not advancing the parser offset), and
+    -- then efficiently take that long a ByteString (advancing the parser offset).
+    --
+    -- This is still slow compared to `parseECS` because parser functions
+    -- (`getWord8`) are used repeatedly, instead of plain loops over ByteString contents.
+    -- The slowdown is ~2x on GHC 8.10.7 on an Intel Core i7-7500U.
+    n <- lookAhead getContentLength
+    getLazyByteString n
+  where
+    getContentLength :: Get ByteOffset
+    getContentLength = do
+        bytesReadBeforeContent <- bytesRead
+        let loop :: Word8 -> Get ByteOffset
+            loop !v = do
+                vNext <- getWord8
+                let isReset = 0xD0 <= vNext && vNext <= 0xD7
+                let vIsSegmentMarker = v == 0xFF && vNext /= 0 && not isReset
+                if not vIsSegmentMarker
+                    then loop vNext
+                    else do
+                        bytesReadAfterContentPlus2 <- bytesRead -- "plus 2" because we've also read the segment marker (0xFF and `vNext`)
+                        let !contentLength = (bytesReadAfterContentPlus2 - 2) - bytesReadBeforeContent
+                        return contentLength
+
+        v_first <- getWord8
+        loop v_first
+
+-- Replace by `Data.ByteString.dropEnd` once we require `bytestring >= 0.11.1.0`.
+bsDropEnd :: Int -> B.ByteString -> B.ByteString
+bsDropEnd n bs
+    | n <= 0    = bs
+    | n >= len  = B.empty
+    | otherwise = B.take (len - 1) bs
+  where
+    len = B.length bs
+{-# INLINE bsDropEnd #-}
+
+-- | Parses a Scan's ECS (Entropy-Coded Segment, the largest part of compressed image data)
+-- from the `Get` stream.
+--
+-- When this function is called, the parser's offset should be
+-- immediately behind the SOS tag.
+--
+-- As described on e.g. https://www.ccoderun.ca/programming/2017-01-31_jpeg/,
+--
+-- > To find the next segment after the SOS, you must keep reading until you
+-- > find a 0xFF bytes which is not immediately followed by 0x00 (see "byte stuffing")
+-- > [or a reset marker's byte: 0xD0 through 0xD7].
+-- > Normally, this will be the EOI segment that comes at the end of the file.
+--
+-- where the 0xFF is the next segment's marker.
+-- See https://github.com/corkami/formats/blob/master/image/jpeg.md#entropy-coded-segment
+-- for more details.
+--
+-- This function returns the ECS, not including the next segment's
+-- marker on its trailing end.
+parseECS :: Get L.ByteString
+parseECS = do
+    -- For a simpler but slower implementation of this function, see
+    -- `parseECS_simple`.
+
+    v_first <- getWord8
+    -- TODO: Compare with what `scan` from `binary-parsers` does.
+    --       Probably we cannot use it because it does not allow us to set the parser state
+    --       to be _before_ the segment marker which would be convenient to not have to
+    --       make a special case the function that calls this function.
+    --       But `scan` works on pointers into the bytestring chunks. Why, for performance?
+    --       I've asked on https://github.com/winterland1989/binary-parsers/issues/7
+    --       If that is for performance, we may want to replicate the same thing here.
+    --
+    --       An orthogonal idea is to use `Data.ByteString.elemIndex` to fast-forward
+    --       to the next 0xFF using `memchr`, but the `unsafe` call to `memchr` might
+    --       have too much overhead, since 0xFF bytes appear statistically every 256 bytes.
+    --       See https://stackoverflow.com/questions/14519905/how-much-does-it-cost-for-haskell-ffi-to-go-into-c-and-back
+
+    -- `withInputChunks` allows us to work on chunks of ByteStrings,
+    -- reducing the number of higher-overhead `Get` functions called.
+    -- It also allows to easily assemble the ByteString to return,
+    -- which may be cross-chunk.
+    -- `withInputChunks` terminates when we return a
+    --     Right (consumed :: ByteString, unconsumed :: ByteString)
+    -- from `consumeChunk`, setting the `Get` parser's offset to just before `unconsumed`.
+    -- Because the segment marker we seek may be the 2 bytes across chunk boundaries,
+    -- we need to keep a reference to the previous chunk (initialised as `B.empty`),
+    -- so that we can set `consumed` properly, because this function is supposed
+    -- to not consume the start of the segment marker (see code dropping the last
+    -- byte of the previous chunk below).
+    GetInternal.withInputChunks
+        (v_first, B.empty)
+        consumeChunk
+        (         L.fromChunks . (B.singleton v_first :)) -- `v_first` also belongs to the returned BS
+        (return . L.fromChunks . (B.singleton v_first :)) -- `v_first` also belongs to the returned BS
+  where
+    consumeChunk :: GetInternal.Consume (Word8, B.ByteString) -- which is: (Word8, B.ByteString) -> B.ByteString -> Either (Word8, B.ByteString) (B.ByteString, B.ByteString)
+    consumeChunk (!v_chunk_start, !prev_chunk) !chunk
+        -- If `withInputChunks` hands us an empty chunk (which `binary` probably
+        -- won't do, but since that's not documented, handle it anyway) then skip over it,
+        -- so that we always remember the last `prev_chunk` that actually has data in it,
+        -- since we `bsDropEnd 1 prev_chunk` in the `case` below.
+        | B.null chunk = Left (v_chunk_start, prev_chunk)
+        | otherwise = loop v_chunk_start 0
+          where
+            loop :: Word8 -> Int -> Either (Word8, B.ByteString) (B.ByteString, B.ByteString)
+            loop !v !offset_in_chunk
+                | offset_in_chunk >= B.length chunk = Left (v, chunk)
+                | otherwise =
+                    let !vNext = BU.unsafeIndex chunk offset_in_chunk -- bounds check is done above
+                        !isReset = 0xD0 <= vNext && vNext <= 0xD7
+                        !vIsSegmentMarker = v == 0xFF && vNext /= 0 && not isReset
+                    in
+                        if not vIsSegmentMarker
+                            then loop vNext (offset_in_chunk+1)
+                            else
+                                -- Set the parser state to _before_ the segment marker.
+                                -- The first case, where the segment marker's 2 bytes are exactly
+                                -- at the chunk boundary, requires us to allocate a new BS with
+                                -- `B.cons`; luckily this case should be rare.
+                                let (!consumed, !unconsumed) = case () of
+                                     () | offset_in_chunk == 0 -> (bsDropEnd 1 prev_chunk, v `B.cons` chunk) -- segment marker starts at `v`, which is the last byte of the previous chunk
+                                        | offset_in_chunk == 1 -> (B.empty, chunk) -- segment marker starts exactly at `chunk`
+                                        | otherwise            -> B.splitAt (offset_in_chunk - 1) chunk -- segment marker starts at `v`, which is 1 before `vNext` (which is at `offset_in_chunk`)
+                                in Right $! (consumed, unconsumed)
+
+
+
+parseAdobe14 :: B.ByteString -> Maybe JpgFrame
+parseAdobe14 str = case runGetStrict get str of
+    Left _err -> Nothing
+    Right app14 -> Just $! JpgAdobeAPP14 app14
+
+-- | Parse JFIF or JFXX information. Right now only JFIF.
+parseJF__ :: B.ByteString -> Maybe JpgFrame
+parseJF__ str = case runGetStrict get str of
+    Left _err -> Nothing
+    Right jfif -> Just $! JpgJFIF jfif
+
+parseExif :: B.ByteString -> Maybe JpgFrame
+parseExif str
+  | exifHeader `B.isPrefixOf` str =
+      let
+        tiff = B.drop (B.length exifHeader) str
+      in
+        case runGetStrict (getP tiff) tiff of
+            Left _err -> Nothing
+            Right (_hdr :: TiffHeader, []) -> Nothing
+            Right (_hdr :: TiffHeader, ifds : _) -> Just $! JpgExif ifds
+  | otherwise = Nothing
+  where
+    exifHeader = BC.pack "Exif\0\0"
+
+putExif :: [ImageFileDirectory] -> Put
+putExif ifds = putAll where
+  hdr = TiffHeader
+    { hdrEndianness = EndianBig
+    , hdrOffset = 8
+    }
+
+  ifdList = case partition (isInIFD0 . ifdIdentifier) ifds of
+    (ifd0, []) -> [ifd0]
+    (ifd0, ifdExif) -> [ifd0 <> pure exifOffsetIfd, ifdExif]
+
+  exifBlob = runPut $ do
+    putByteString $ BC.pack "Exif\0\0"
+    putP BC.empty (hdr, ifdList)
+
+  putAll = do
+    put (JpgAppSegment 1)
+    putWord16be . fromIntegral $ L.length exifBlob + 2
+    putLazyByteString exifBlob
+
+skipFrameMarker :: Get ()
+skipFrameMarker = do
+    word <- getWord8
+    when (word /= 0xFF) $ do
+        readedData <- bytesRead
+        fail $ "Invalid Frame marker (" ++ show word
+                ++ ", bytes read : " ++ show readedData ++ ")"
+
+-- | Parses a single frame.
+--
+-- Returns `Nothing` when we encounter a frame we want to skip.
+parseFrameOfKind :: JpgFrameKind -> Get (Maybe JpgFrame)
+parseFrameOfKind kind = do
+    case kind of
+        JpgEndOfImage -> return Nothing
+        JpgAppSegment 0 -> parseJF__ <$> takeCurrentFrame
+        JpgAppSegment 1 -> parseExif <$> takeCurrentFrame
+        JpgAppSegment 14 -> parseAdobe14 <$> takeCurrentFrame
+        JpgAppSegment c -> Just . JpgAppFrame c <$> takeCurrentFrame
+        JpgExtensionSegment c -> Just . JpgExtension c <$> takeCurrentFrame
+        JpgQuantizationTable ->
+            (\(TableList quants) -> Just $! JpgQuantTable quants) <$> get
+        JpgRestartInterval ->
+            (\(RestartInterval i) -> Just $! JpgIntervalRestart i) <$> get
+        JpgHuffmanTableMarker ->
+            (\(TableList huffTables) -> Just $!
+                    JpgHuffmanTable [(t, packHuffmanTree . buildPackedHuffmanTree $ huffCodes t) | t <- huffTables])
+                    <$> get
+        JpgStartOfScan -> do
+            scanHeader <- get
+            ecs <- parseECS
+            return $! Just $! JpgScanBlob scanHeader ecs
+        _ -> Just . JpgScans kind <$> get
+
+
+-- | Parse a list of `JpgFrame`s.
+--
+-- This function has various quirks; consider the below with great caution
+-- when using this function.
+--
+-- While @data JpgFrame = ... | JpgScanBlob !...` itself has strict fields,
+--
+-- This function is written in such a way that that it can construct
+-- the @[JpgFrame]@ "lazily" such that the expensive byte-by-byte traversal
+-- in `parseECS` to create a `JpgScanBlob` can be avoided if only
+-- list elements before that `JpgScanBlob` are evaluated.
+--
+-- That means the user can write code such as
+--
+-- > let mbFirstScan =
+-- >       case runGetOrFail (get @JPG.JpgImage) hugeImageByteString of -- (`get @JPG.JpgImage` uses `parseFramesSemiLazy`)
+-- >         Right (_restBs, _offset, res) ->
+-- >           find (\frame -> case frame of { JPG.JpgScans{} -> True; _ -> False }) (JPG.jpgFrame res)
+--
+-- with the guarantee that only the bytes before the ECS (large compressed image data)
+-- will be inspected, assuming that indeed there is at least 1 `JpgScan` in front
+-- of the `JpgScanBlob` that contains the ECS.
+--
+-- This guarantee can be useful to e.g. quickly read just the image
+-- dimensions (width, height) without traversing the large data.
+--
+-- Also note that this `Get` parser does not correctly maintain the parser byte offset
+-- (`Data.Binary.Get.bytesRead`), because as soon as a `JpgStartOfScan` is returned,
+-- it uses `Data.Binary.Get.getRemainingLazyBytes` to provide:
+--
+-- 1. the laziness described above, and
+-- 2. the ability to ignore any parser failure after the first successfully-parsed
+--    `JpgScanBlob` (it is debatable whether this behaviour is a desirable behaviour of this
+--    library, but it is historically so and existing exposed functions do not break
+--    this for backwards compatibility with existing uses of this library).
+--    This fact also means that even `parseNextFrameStrict` cannot maintain
+--    correct parser byte offsets.
+--
+-- Further note that if you are reading a huge JPEG image from disk strictly,
+-- this will already incur a full traversal (namely creation) of the `hugeImageByteString`.
+-- Thus, `parseNextFrameLazy` only provides any benefit if you:
+--
+-- - read the image from disk using lazy IO (not recommended!) such as via
+--   `Data.ByteString.Lazy.readFile`,
+-- - or do something similar, such as creating the `hugeImageByteString` via @mmap()@
+--
+-- This function is called "semi lazy" because only the first `JpgScanBlob` returned
+-- in the `[JpgFrame]` is returned lazily; frames of other types, or multiple
+-- `JpgScanBlob`s, are confusingly not dealt with lazily.
+--
+-- If as a caller you do not want to deal with any of these quirks,
+-- and use proper strict IO and/or via `Data.Binary.Get`'s incremental input interface:
+--
+-- - If you want the whole `[JpgFrame]`: use `parseFrames`.
+-- - If you want parsing to terminate early as in the example shown above,
+--   use in combination with just the right amount of `get :: Get JpgFrameKind`,
+--   `parseFrameOfKind`, and `skipFrameMarker`.
+parseFramesSemiLazy :: Get [JpgFrame]
+parseFramesSemiLazy = do
+    kind <- get
+    case kind of
+        -- The end-of-image case needs to be here because `_ ->` default case below
+        -- unconditionally uses `skipFrameMarker` which does not exist after `JpgEndOfImage`.
+        JpgEndOfImage -> pure []
+        JpgStartOfScan -> do
+            scanHeader <- get
+            remainingBytes <- getRemainingLazyBytes
+            -- It is after the above `getRemainingLazyBytes` that the `Get` parser lazily succeeds,
+            -- allowing consumers of `parseFramesSemiLazy` evaluate all `[JpgFrame]` list elements
+            -- until (excluding) the cons-cell around the `JpgScanBlob ...` we construct below.
+
+            return $ case runGet parseECS remainingBytes of
+                Left _ ->
+                    -- Construct invalid `JpgScanBlob` even when the compressed JPEG
+                    -- data is truncated or otherwise invalid, because that's what JuicyPixels's
+                    -- `parseFramesSemiLazy` function did in the past, for backwards compat.
+                    [JpgScanBlob scanHeader remainingBytes]
+                Right ecs ->
+                    JpgScanBlob scanHeader ecs
+                    :
+                    -- TODO Why `drop 1` instead of `runGet (skipFrameMarker *> parseFramesSemiLazy) remainingBytes` that would check that the dropped 1 Byte is really a frame marker?
+                    case runGet parseFramesSemiLazy (L.drop (L.length ecs + 1) remainingBytes) of
+                        -- After we've encountered the first scan blob containing encoded image data,
+                        -- we accept anything else after to fail parsing, ignoring that failure,
+                        -- end emitting no further frames.
+                        -- TODO: Explain why JuicyPixel chose to use this logic, insteaed of failing.
+                        Left _ -> []
+                        Right remainingFrames -> remainingFrames
+        _ -> do
+            mbFrame <- parseFrameOfKind kind
+            skipFrameMarker
+            remainingFrames <- parseFramesSemiLazy
+            return $ maybeToList mbFrame ++ remainingFrames
+
+-- | Parse a list of `JpgFrame`s.
+parseFrames :: Get [JpgFrame]
+parseFrames = do
+    kind <- get
+    case kind of
+        JpgEndOfImage -> pure []
+        _ -> do
+            mbFrame <- parseFrameOfKind kind
+            skipFrameMarker
+            remainingFrames <- parseFrames
+            return $ maybeToList mbFrame ++ remainingFrames
+
+-- | Parse a list of `JpgFrameKind`s with their corresponding offsets and lengths
+-- (not counting the segment and frame markers into the lengths).
+--
+-- Useful for debugging.
+parseFrameKinds :: Get [(JpgFrameKind, Int64, Int64)]
+parseFrameKinds = do
+    kindMarkerOffset :: Int64 <- bytesRead
+    kind <- get
+    case kind of
+        JpgEndOfImage -> pure [(JpgEndOfImage, kindMarkerOffset, 0)]
+        _ -> do
+            parserOffsetBefore <- bytesRead
+            _ <- parseFrameOfKind kind
+            parserOffsetAfter <- bytesRead
+            let !segmentLengthWithoutMarker = parserOffsetAfter - parserOffsetBefore
+            skipFrameMarker
+            remainingKinds <- parseFrameKinds
+            return $ (kind, kindMarkerOffset, segmentLengthWithoutMarker):remainingKinds
+
+-- | Parses forward, returning the first scan header encountered.
+--
+-- Should be used after `skipUntilFrames`.
+--
+-- Fails parsing when an SOS segment marker (`JpgStartOfScan`, resulting
+-- in `JpgScanBlob`) is encountered before an SOF segment marker (that
+-- results in `JpgScans` carrying the `JpgFrameHeader`).
+parseToFirstFrameHeader :: Get (Maybe JpgFrameHeader)
+parseToFirstFrameHeader = do
+    kind <- get
+    case kind of
+        JpgEndOfImage -> return Nothing
+        JpgStartOfScan -> fail "parseToFirstFrameHeader: Encountered SOS frame marker before frame header that tells its dimensions"
+        _ -> do
+            mbFrame <- parseFrameOfKind kind
+            case mbFrame of
+                Nothing -> continueSearching
+                Just frame -> case frame of
+                    JpgScans _ frameHeader -> return $ Just $! frameHeader
+                    _ -> continueSearching
+  where
+    continueSearching = do
+        skipFrameMarker
+        parseToFirstFrameHeader
+
+buildPackedHuffmanTree :: V.Vector (VU.Vector Word8) -> HuffmanTree
+buildPackedHuffmanTree = buildHuffmanTree . map VU.toList . V.toList
+
+secondStartOfFrameByteOfKind :: JpgFrameKind -> Word8
+secondStartOfFrameByteOfKind = aux
+  where
+    aux JpgBaselineDCTHuffman = 0xC0
+    aux JpgExtendedSequentialDCTHuffman = 0xC1
+    aux JpgProgressiveDCTHuffman = 0xC2
+    aux JpgLosslessHuffman = 0xC3
+    aux JpgDifferentialSequentialDCTHuffman = 0xC5
+    aux JpgDifferentialProgressiveDCTHuffman = 0xC6
+    aux JpgDifferentialLosslessHuffman = 0xC7
+    aux JpgExtendedSequentialArithmetic = 0xC9
+    aux JpgProgressiveDCTArithmetic = 0xCA
+    aux JpgLosslessArithmetic = 0xCB
+    aux JpgHuffmanTableMarker = 0xC4
+    aux JpgDifferentialSequentialDCTArithmetic = 0xCD
+    aux JpgDifferentialProgressiveDCTArithmetic = 0xCE
+    aux JpgDifferentialLosslessArithmetic = 0xCF
+    aux JpgEndOfImage = 0xD9
+    aux JpgQuantizationTable = 0xDB
+    aux JpgStartOfScan = 0xDA
+    aux JpgRestartInterval = 0xDD
+    aux (JpgRestartIntervalEnd v) = v
+    aux (JpgAppSegment a) = (a + 0xE0)
+    aux (JpgExtensionSegment a) = a
+
+data JpgImageKind = BaseLineDCT | ProgressiveDCT
+
+instance Binary JpgFrameKind where
+    put v = putWord8 0xFF >> put (secondStartOfFrameByteOfKind v)
+    get = do
+        -- no lookahead :(
+        {-word <- getWord8-}
+        word2 <- getWord8
+        case word2 of
+            0xC0 -> return JpgBaselineDCTHuffman
+            0xC1 -> return JpgExtendedSequentialDCTHuffman
+            0xC2 -> return JpgProgressiveDCTHuffman
+            0xC3 -> return JpgLosslessHuffman
+            0xC4 -> return JpgHuffmanTableMarker
+            0xC5 -> return JpgDifferentialSequentialDCTHuffman
+            0xC6 -> return JpgDifferentialProgressiveDCTHuffman
+            0xC7 -> return JpgDifferentialLosslessHuffman
+            0xC9 -> return JpgExtendedSequentialArithmetic
+            0xCA -> return JpgProgressiveDCTArithmetic
+            0xCB -> return JpgLosslessArithmetic
+            0xCD -> return JpgDifferentialSequentialDCTArithmetic
+            0xCE -> return JpgDifferentialProgressiveDCTArithmetic
+            0xCF -> return JpgDifferentialLosslessArithmetic
+            0xD9 -> return JpgEndOfImage
+            0xDA -> return JpgStartOfScan
+            0xDB -> return JpgQuantizationTable
+            0xDD -> return JpgRestartInterval
+            a | a >= 0xF0 -> return $! JpgExtensionSegment a
+              | a >= 0xE0 -> return $! JpgAppSegment (a - 0xE0)
+              | a >= 0xD0 && a <= 0xD7 -> return $! JpgRestartIntervalEnd a
+              | otherwise -> fail ("Invalid frame marker (" ++ show a ++ ")")
+
+put4BitsOfEach :: Word8 -> Word8 -> Put
+put4BitsOfEach a b = put $ (a `unsafeShiftL` 4) .|. b
+
+get4BitOfEach :: Get (Word8, Word8)
+get4BitOfEach = do
+    val <- get
+    return ((val `unsafeShiftR` 4) .&. 0xF, val .&. 0xF)
+
+newtype RestartInterval = RestartInterval Word16
+
+instance Binary RestartInterval where
+    put (RestartInterval i) = putWord16be 4 >> putWord16be i
+    get = do
+        size <- getWord16be
+        when (size /= 4) (fail "Invalid jpeg restart interval size")
+        RestartInterval <$> getWord16be
+
+instance Binary JpgComponent where
+    get = do
+        ident <- getWord8
+        (horiz, vert) <- get4BitOfEach
+        quantTableIndex <- getWord8
+        return JpgComponent
+            { componentIdentifier = ident
+            , horizontalSamplingFactor = horiz
+            , verticalSamplingFactor = vert
+            , quantizationTableDest = quantTableIndex
+            }
+    put v = do
+        put $ componentIdentifier v
+        put4BitsOfEach (horizontalSamplingFactor v) $ verticalSamplingFactor v
+        put $ quantizationTableDest v
+
+instance Binary JpgFrameHeader where
+    get = do
+        beginOffset <- fromIntegral <$> bytesRead
+        frmHLength <- getWord16be
+        samplePrec <- getWord8
+        h <- getWord16be
+        w <- getWord16be
+        compCount <- getWord8
+        components <- replicateM (fromIntegral compCount) get
+        endOffset <- fromIntegral <$> bytesRead
+        when (beginOffset - endOffset < fromIntegral frmHLength)
+             (skip $ fromIntegral frmHLength - (endOffset - beginOffset))
+        return JpgFrameHeader
+            { jpgFrameHeaderLength = frmHLength
+            , jpgSamplePrecision = samplePrec
+            , jpgHeight = h
+            , jpgWidth = w
+            , jpgImageComponentCount = compCount
+            , jpgComponents = components
+            }
+
+    put v = do
+        putWord16be $ jpgFrameHeaderLength v
+        putWord8    $ jpgSamplePrecision v
+        putWord16be $ jpgHeight v
+        putWord16be $ jpgWidth v
+        putWord8    $ jpgImageComponentCount v
+        mapM_ put   $ jpgComponents v
+
+instance Binary JpgScanSpecification where
+    put v = do
+        put $ componentSelector v
+        put4BitsOfEach (dcEntropyCodingTable v) $ acEntropyCodingTable v
+
+    get = do
+        compSel <- get
+        (dc, ac) <- get4BitOfEach
+        return JpgScanSpecification {
+            componentSelector = compSel
+          , dcEntropyCodingTable = dc
+          , acEntropyCodingTable = ac
+          }
+
+instance Binary JpgScanHeader where
+    get = do
+        thisScanLength <- getWord16be
+        compCount <- getWord8
+        comp <- replicateM (fromIntegral compCount) get
+        specBeg <- get
+        specEnd <- get
+        (approxHigh, approxLow) <- get4BitOfEach
+
+        return JpgScanHeader {
+            scanLength = thisScanLength,
+            scanComponentCount = compCount,
+            scans = comp,
+            spectralSelection = (specBeg, specEnd),
+            successiveApproxHigh = approxHigh,
+            successiveApproxLow = approxLow
+        }
+
+    put v = do
+        putWord16be $ scanLength v
+        putWord8 $ scanComponentCount v
+        mapM_ put $ scans v
+        putWord8 . fst $ spectralSelection v
+        putWord8 . snd $ spectralSelection v
+        put4BitsOfEach (successiveApproxHigh v) $ successiveApproxLow v
+
+{-# INLINE createEmptyMutableMacroBlock #-}
+-- | Create a new macroblock with the good array size
+createEmptyMutableMacroBlock :: (Storable a, Num a) => ST s (MutableMacroBlock s a)
+createEmptyMutableMacroBlock = M.replicate 64 0
+
+printMacroBlock :: (Storable a, PrintfArg a)
+                => MutableMacroBlock s a -> ST s String
+printMacroBlock block = pLn 0
+    where pLn 64 = return "===============================\n"
+          pLn i = do
+              v <- block `M.unsafeRead` i
+              vn <- pLn (i+1)
+              return $ printf (if i `mod` 8 == 0 then "\n%5d " else "%5d ") v ++ vn
+
+printPureMacroBlock :: (Storable a, PrintfArg a) => MacroBlock a -> String
+printPureMacroBlock block = pLn 0
+    where pLn 64 = "===============================\n"
+          pLn i = str ++ pLn (i + 1)
+            where str | i `mod` 8 == 0 = printf "\n%5d " v
+                      | otherwise = printf "%5d" v
+                  v = block VS.! i
+
+
+{-# INLINE dctBlockSize #-}
+dctBlockSize :: Num a => a
+dctBlockSize = 8
diff --git a/src/Codec/Picture/Metadata.hs b/src/Codec/Picture/Metadata.hs
--- a/src/Codec/Picture/Metadata.hs
+++ b/src/Codec/Picture/Metadata.hs
@@ -1,316 +1,316 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE GADTs #-}
-{-# LANGUAGE ExistentialQuantification #-}
-{-# LANGUAGE StandaloneDeriving #-}
-{-# LANGUAGE TypeOperators #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-# LANGUAGE FlexibleInstances #-}
--- | This module expose a common "metadata" storage for various image
--- type. Different format can generate different metadatas, and write
--- only a part of them.
---
--- Since version 3.2.5
---
-module Codec.Picture.Metadata( -- * Types
-                               Metadatas
-                             , Keys( .. )
-                             , Value( .. )
-                             , Elem( .. )
-                             , SourceFormat( .. )
-                             , ColorSpace( .. )
-
-                               -- * Functions
-                             , Codec.Picture.Metadata.lookup
-                             , empty
-                             , insert
-                             , delete
-                             , singleton
-
-                               -- * Folding
-                             , foldl'
-                             , Codec.Picture.Metadata.foldMap
-
-                              -- * Helper functions
-                             , mkDpiMetadata
-                             , mkSizeMetadata
-                             , basicMetadata
-                             , simpleMetadata
-                             , extractExifMetas
-
-                               -- * Conversion functions
-                             , dotsPerMeterToDotPerInch
-                             , dotPerInchToDotsPerMeter 
-                             , dotsPerCentiMeterToDotPerInch
-                             ) where
-
-import Prelude hiding (Foldable(..))
-
-#if !MIN_VERSION_base(4,8,0)
-import Data.Monoid( Monoid, mempty, mappend )
-import Data.Word( Word )
-#endif
-
-
-import Control.DeepSeq( NFData( .. ) )
-import qualified Data.ByteString as B
-import qualified Data.Foldable as F
-
-import Codec.Picture.Metadata.Exif
-
-#if MIN_VERSION_base(4,7,0)
-import Data.Typeable( (:~:)( Refl ) )
-type Equiv = (:~:)
-#else
-data Equiv a b where
-    Refl :: Equiv a a
-#endif
-
--- | Type describing the original file format of the file.
-data SourceFormat
-  = SourceJpeg
-  | SourceGif
-  | SourceBitmap
-  | SourceTiff
-  | SourcePng
-  | SourceHDR
-  | SourceTGA
-  deriving (Eq, Show)
-
-instance NFData SourceFormat where
-  rnf a = a `seq` ()
-
--- | The same color values may result in slightly different colors on different
--- devices. To get consistent colors accross multiple devices we need a way of
--- mapping color values from a source device into their equivalents on the
--- target device.
---
--- The solution is essentially to define, for each device, a family of mappings
--- that convert between device colors and standard CIEXYZ or CIELAB colors. The
--- collection of mappings for a device is known as the 'color-profile' of that
--- device, and each color-profile can be thought of as describing a
--- 'color-space'.
---
--- If we know the color-space of the input pixels, and the color space of the
--- output device, then we can convert the colors in the image to their
--- equivalents on the output device.
---
--- JuicyPixels does not parse color-profiles or attempt to perform color
--- correction.
---
--- The following color space types are recognised:
---
---   * sRGB: Standard RGB color space.
---   * Windows BMP color space: Color space information embedded within a V4
---         Windows BMP file.
---   * ICC profile: An ICC color profile.
-data ColorSpace = SRGB
-                | WindowsBitmapColorSpace !B.ByteString
-                | ICCProfile !B.ByteString
-                deriving (Eq, Show)
-
-instance NFData ColorSpace where
-  rnf v = v `seq` ()
-
--- | Store various additional information about an image. If
--- something is not recognized, it can be stored in an unknown tag.
---
---   * 'DpiX' Dot per inch on this x axis.
---
---   * 'DpiY' Dot per inch on this y axis.
---
---   * 'Width' Image width in pixel. Relying on the metadata for this
---          information can avoid the full decompression of the image.
---          Ignored for image writing.
---
---   * 'Height' Image height in pixels. Relying on the metadata for this
---          information can void the full decompression of the image.
---          Ignored for image writing.
---
---   * 'ColorProfile' An unparsed ICC color profile. Currently only supported by
---          the Bitmap format.
---
---   * 'Unknown' unlikely to be decoded, but usefull for metadata writing
---
---   * 'Exif' Exif tag and associated data.
---
-data Keys a where
-  Gamma       :: Keys Double
-  ColorSpace  :: Keys ColorSpace
-  Format      :: Keys SourceFormat
-  DpiX        :: Keys Word
-  DpiY        :: Keys Word
-  Width       :: Keys Word
-  Height      :: Keys Word
-  Title       :: Keys String
-  Description :: Keys String
-  Author      :: Keys String
-  Copyright   :: Keys String
-  Software    :: Keys String
-  Comment     :: Keys String
-  Disclaimer  :: Keys String
-  Source      :: Keys String
-  Warning     :: Keys String
-  Exif        :: !ExifTag -> Keys ExifData
-  Unknown     :: !String -> Keys Value
-
-deriving instance Show (Keys a)
-deriving instance Eq (Keys a)
-{-deriving instance Ord (Keys a)-}
-
--- | Encode values for unknown information
-data Value
-  = Int    !Int
-  | Double !Double
-  | String !String
-  deriving (Eq, Show)
-
-instance NFData Value where
-  rnf v = v `seq` () -- everything is strict, so it's OK
-
--- | Element describing a metadata and it's (typed) associated
--- value.
-data Elem k =
-  forall a. (Show a, NFData a) => !(k a) :=> a
-
-deriving instance Show (Elem Keys)
-
-instance NFData (Elem Keys) where
-  rnf (_ :=> v) = rnf v `seq` ()
-
-keyEq :: Keys a -> Keys b -> Maybe (Equiv a b)
-keyEq a b = case (a, b) of
-  (Gamma, Gamma) -> Just Refl
-  (ColorSpace, ColorSpace) -> Just Refl
-  (DpiX, DpiX) -> Just Refl
-  (DpiY, DpiY) -> Just Refl
-  (Width, Width) -> Just Refl
-  (Height, Height) -> Just Refl
-  (Title, Title) -> Just Refl
-  (Description, Description) -> Just Refl
-  (Author, Author) -> Just Refl
-  (Copyright, Copyright) -> Just Refl
-  (Software, Software) -> Just Refl
-  (Comment, Comment) -> Just Refl
-  (Disclaimer, Disclaimer) -> Just Refl
-  (Source, Source) -> Just Refl
-  (Warning, Warning) -> Just Refl
-  (Format, Format) -> Just Refl
-  (Unknown v1, Unknown v2) | v1 == v2 -> Just Refl
-  (Exif t1, Exif t2) | t1 == t2 -> Just Refl
-  _ -> Nothing
-
--- | Dependent storage used for metadatas.
--- All metadatas of a given kind are unique within
--- this container.
-    --
--- The current data structure is based on list,
--- so bad performances can be expected.
-newtype Metadatas = Metadatas
-  { getMetadatas :: [Elem Keys]
-  }
-  deriving (Show, NFData)
-
-instance Monoid Metadatas where
-  mempty = empty
-#if !MIN_VERSION_base(4,11,0)
-  mappend = union
-#else
-instance Semigroup Metadatas where
-  (<>) = union
-#endif
-
--- | Right based union
-union :: Metadatas -> Metadatas -> Metadatas
-union m1 = F.foldl' go m1 . getMetadatas where
-  go acc el@(k :=> _) = Metadatas $ el : getMetadatas (delete k acc)
-
--- | Strict left fold of the metadatas
-foldl' :: (acc -> Elem Keys -> acc) -> acc -> Metadatas -> acc
-foldl' f initAcc = F.foldl' f initAcc . getMetadatas
-
--- | foldMap equivalent for metadatas.
-foldMap :: Monoid m => (Elem Keys -> m) -> Metadatas -> m
-foldMap f = foldl' (\acc v -> acc `mappend` f v) mempty
-
--- | Remove an element of the given keys from the metadatas.
--- If not present does nothing.
-delete :: Keys a -> Metadatas -> Metadatas
-delete k = Metadatas . go . getMetadatas where
-  go [] = []
-  go (el@(k2 :=> _) : rest) = case keyEq k k2 of
-    Nothing -> el : go rest
-    Just Refl -> rest
-
--- | Extract all Exif specific metadatas
-extractExifMetas :: Metadatas -> [(ExifTag, ExifData)]
-extractExifMetas = go . getMetadatas where
-  go :: [Elem Keys] -> [(ExifTag, ExifData)]
-  go [] = []
-  go ((k :=> v) : rest) =
-    case k of
-      Exif t -> (t, v) : go rest
-      _ -> go rest
-
--- | Search a metadata with the given key.
-lookup :: Keys a -> Metadatas -> Maybe a
-lookup k = go . getMetadatas where
-  go [] = Nothing
-  go ((k2 :=> v) : rest) = case keyEq k k2 of
-    Nothing -> go rest
-    Just Refl -> Just v
-
--- | Insert an element in the metadatas, if an element with
--- the same key is present, it is overwritten.
-insert :: (Show a, NFData a) => Keys a -> a -> Metadatas -> Metadatas
-insert k val metas =
-  Metadatas $ (k :=> val) : getMetadatas (delete k metas)
-
--- | Create metadatas with a single element.
-singleton :: (Show a, NFData a) => Keys a -> a -> Metadatas
-singleton k val = Metadatas [k :=> val]
-
--- | Empty metadatas. Favor 'mempty'
-empty :: Metadatas
-empty = Metadatas mempty
-
--- | Conversion from dpm to dpi
-dotsPerMeterToDotPerInch :: Word -> Word
-dotsPerMeterToDotPerInch z = z * 254 `div` 10000
-
--- | Conversion from dpi to dpm
-dotPerInchToDotsPerMeter :: Word -> Word
-dotPerInchToDotsPerMeter z = (z * 10000) `div` 254
-
--- | Conversion dpcm -> dpi
-dotsPerCentiMeterToDotPerInch :: Word -> Word
-dotsPerCentiMeterToDotPerInch z = z * 254 `div` 100
-
--- | Create metadatas indicating the resolution, with DpiX == DpiY
-mkDpiMetadata :: Word -> Metadatas
-mkDpiMetadata w =
-  Metadatas [DpiY :=> w, DpiX :=> w]
-
--- | Create metadatas holding width and height information.
-mkSizeMetadata :: Integral n => n -> n -> Metadatas
-mkSizeMetadata w h = 
-  Metadatas [ Width :=> fromIntegral w, Height :=> fromIntegral h ]
-
--- | Create simple metadatas with Format, Width & Height
-basicMetadata :: Integral nSize => SourceFormat -> nSize -> nSize -> Metadatas
-basicMetadata f w h =
-  Metadatas [ Format :=> f
-            , Width :=> fromIntegral w
-            , Height :=> fromIntegral h
-            ]
-
--- | Create simple metadatas with Format, Width, Height, DpiX & DpiY
-simpleMetadata :: (Integral nSize, Integral nDpi)
-               => SourceFormat -> nSize -> nSize -> nDpi -> nDpi -> Metadatas
-simpleMetadata f w h dpiX dpiY =
-  Metadatas [ Format :=> f
-            , Width :=> fromIntegral w
-            , Height :=> fromIntegral h
-            , DpiX :=> fromIntegral dpiX
-            , DpiY :=> fromIntegral dpiY
-            ]
-
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE GADTs #-}
+{-# LANGUAGE ExistentialQuantification #-}
+{-# LANGUAGE StandaloneDeriving #-}
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE FlexibleInstances #-}
+-- | This module expose a common "metadata" storage for various image
+-- type. Different format can generate different metadatas, and write
+-- only a part of them.
+--
+-- Since version 3.2.5
+--
+module Codec.Picture.Metadata( -- * Types
+                               Metadatas
+                             , Keys( .. )
+                             , Value( .. )
+                             , Elem( .. )
+                             , SourceFormat( .. )
+                             , ColorSpace( .. )
+
+                               -- * Functions
+                             , Codec.Picture.Metadata.lookup
+                             , empty
+                             , insert
+                             , delete
+                             , singleton
+
+                               -- * Folding
+                             , foldl'
+                             , Codec.Picture.Metadata.foldMap
+
+                              -- * Helper functions
+                             , mkDpiMetadata
+                             , mkSizeMetadata
+                             , basicMetadata
+                             , simpleMetadata
+                             , extractExifMetas
+
+                               -- * Conversion functions
+                             , dotsPerMeterToDotPerInch
+                             , dotPerInchToDotsPerMeter 
+                             , dotsPerCentiMeterToDotPerInch
+                             ) where
+
+import Prelude hiding (Foldable(..))
+
+#if !MIN_VERSION_base(4,8,0)
+import Data.Monoid( Monoid, mempty, mappend )
+import Data.Word( Word )
+#endif
+
+
+import Control.DeepSeq( NFData( .. ) )
+import qualified Data.ByteString as B
+import qualified Data.Foldable as F
+
+import Codec.Picture.Metadata.Exif
+
+#if MIN_VERSION_base(4,7,0)
+import Data.Typeable( (:~:)( Refl ) )
+type Equiv = (:~:)
+#else
+data Equiv a b where
+    Refl :: Equiv a a
+#endif
+
+-- | Type describing the original file format of the file.
+data SourceFormat
+  = SourceJpeg
+  | SourceGif
+  | SourceBitmap
+  | SourceTiff
+  | SourcePng
+  | SourceHDR
+  | SourceTGA
+  deriving (Eq, Show)
+
+instance NFData SourceFormat where
+  rnf a = a `seq` ()
+
+-- | The same color values may result in slightly different colors on different
+-- devices. To get consistent colors across multiple devices we need a way of
+-- mapping color values from a source device into their equivalents on the
+-- target device.
+--
+-- The solution is essentially to define, for each device, a family of mappings
+-- that convert between device colors and standard CIEXYZ or CIELAB colors. The
+-- collection of mappings for a device is known as the 'color-profile' of that
+-- device, and each color-profile can be thought of as describing a
+-- 'color-space'.
+--
+-- If we know the color-space of the input pixels, and the color space of the
+-- output device, then we can convert the colors in the image to their
+-- equivalents on the output device.
+--
+-- JuicyPixels does not parse color-profiles or attempt to perform color
+-- correction.
+--
+-- The following color space types are recognised:
+--
+--   * sRGB: Standard RGB color space.
+--   * Windows BMP color space: Color space information embedded within a V4
+--         Windows BMP file.
+--   * ICC profile: An ICC color profile.
+data ColorSpace = SRGB
+                | WindowsBitmapColorSpace !B.ByteString
+                | ICCProfile !B.ByteString
+                deriving (Eq, Show)
+
+instance NFData ColorSpace where
+  rnf v = v `seq` ()
+
+-- | Store various additional information about an image. If
+-- something is not recognized, it can be stored in an unknown tag.
+--
+--   * 'DpiX' Dot per inch on this x axis.
+--
+--   * 'DpiY' Dot per inch on this y axis.
+--
+--   * 'Width' Image width in pixel. Relying on the metadata for this
+--          information can avoid the full decompression of the image.
+--          Ignored for image writing.
+--
+--   * 'Height' Image height in pixels. Relying on the metadata for this
+--          information can void the full decompression of the image.
+--          Ignored for image writing.
+--
+--   * 'ColorProfile' An unparsed ICC color profile. Currently only supported by
+--          the Bitmap format.
+--
+--   * 'Unknown' unlikely to be decoded, but useful for metadata writing
+--
+--   * 'Exif' Exif tag and associated data.
+--
+data Keys a where
+  Gamma       :: Keys Double
+  ColorSpace  :: Keys ColorSpace
+  Format      :: Keys SourceFormat
+  DpiX        :: Keys Word
+  DpiY        :: Keys Word
+  Width       :: Keys Word
+  Height      :: Keys Word
+  Title       :: Keys String
+  Description :: Keys String
+  Author      :: Keys String
+  Copyright   :: Keys String
+  Software    :: Keys String
+  Comment     :: Keys String
+  Disclaimer  :: Keys String
+  Source      :: Keys String
+  Warning     :: Keys String
+  Exif        :: !ExifTag -> Keys ExifData
+  Unknown     :: !String -> Keys Value
+
+deriving instance Show (Keys a)
+deriving instance Eq (Keys a)
+{-deriving instance Ord (Keys a)-}
+
+-- | Encode values for unknown information
+data Value
+  = Int    !Int
+  | Double !Double
+  | String !String
+  deriving (Eq, Show)
+
+instance NFData Value where
+  rnf v = v `seq` () -- everything is strict, so it's OK
+
+-- | Element describing a metadata and it's (typed) associated
+-- value.
+data Elem k =
+  forall a. (Show a, NFData a) => !(k a) :=> a
+
+deriving instance Show (Elem Keys)
+
+instance NFData (Elem Keys) where
+  rnf (_ :=> v) = rnf v `seq` ()
+
+keyEq :: Keys a -> Keys b -> Maybe (Equiv a b)
+keyEq a b = case (a, b) of
+  (Gamma, Gamma) -> Just Refl
+  (ColorSpace, ColorSpace) -> Just Refl
+  (DpiX, DpiX) -> Just Refl
+  (DpiY, DpiY) -> Just Refl
+  (Width, Width) -> Just Refl
+  (Height, Height) -> Just Refl
+  (Title, Title) -> Just Refl
+  (Description, Description) -> Just Refl
+  (Author, Author) -> Just Refl
+  (Copyright, Copyright) -> Just Refl
+  (Software, Software) -> Just Refl
+  (Comment, Comment) -> Just Refl
+  (Disclaimer, Disclaimer) -> Just Refl
+  (Source, Source) -> Just Refl
+  (Warning, Warning) -> Just Refl
+  (Format, Format) -> Just Refl
+  (Unknown v1, Unknown v2) | v1 == v2 -> Just Refl
+  (Exif t1, Exif t2) | t1 == t2 -> Just Refl
+  _ -> Nothing
+
+-- | Dependent storage used for metadatas.
+-- All metadatas of a given kind are unique within
+-- this container.
+    --
+-- The current data structure is based on list,
+-- so bad performances can be expected.
+newtype Metadatas = Metadatas
+  { getMetadatas :: [Elem Keys]
+  }
+  deriving (Show, NFData)
+
+instance Monoid Metadatas where
+  mempty = empty
+#if !MIN_VERSION_base(4,11,0)
+  mappend = union
+#else
+instance Semigroup Metadatas where
+  (<>) = union
+#endif
+
+-- | Right based union
+union :: Metadatas -> Metadatas -> Metadatas
+union m1 = F.foldl' go m1 . getMetadatas where
+  go acc el@(k :=> _) = Metadatas $ el : getMetadatas (delete k acc)
+
+-- | Strict left fold of the metadatas
+foldl' :: (acc -> Elem Keys -> acc) -> acc -> Metadatas -> acc
+foldl' f initAcc = F.foldl' f initAcc . getMetadatas
+
+-- | foldMap equivalent for metadatas.
+foldMap :: Monoid m => (Elem Keys -> m) -> Metadatas -> m
+foldMap f = foldl' (\acc v -> acc `mappend` f v) mempty
+
+-- | Remove an element of the given keys from the metadatas.
+-- If not present does nothing.
+delete :: Keys a -> Metadatas -> Metadatas
+delete k = Metadatas . go . getMetadatas where
+  go [] = []
+  go (el@(k2 :=> _) : rest) = case keyEq k k2 of
+    Nothing -> el : go rest
+    Just Refl -> rest
+
+-- | Extract all Exif specific metadatas
+extractExifMetas :: Metadatas -> [(ExifTag, ExifData)]
+extractExifMetas = go . getMetadatas where
+  go :: [Elem Keys] -> [(ExifTag, ExifData)]
+  go [] = []
+  go ((k :=> v) : rest) =
+    case k of
+      Exif t -> (t, v) : go rest
+      _ -> go rest
+
+-- | Search a metadata with the given key.
+lookup :: Keys a -> Metadatas -> Maybe a
+lookup k = go . getMetadatas where
+  go [] = Nothing
+  go ((k2 :=> v) : rest) = case keyEq k k2 of
+    Nothing -> go rest
+    Just Refl -> Just v
+
+-- | Insert an element in the metadatas, if an element with
+-- the same key is present, it is overwritten.
+insert :: (Show a, NFData a) => Keys a -> a -> Metadatas -> Metadatas
+insert k val metas =
+  Metadatas $ (k :=> val) : getMetadatas (delete k metas)
+
+-- | Create metadatas with a single element.
+singleton :: (Show a, NFData a) => Keys a -> a -> Metadatas
+singleton k val = Metadatas [k :=> val]
+
+-- | Empty metadatas. Favor 'mempty'
+empty :: Metadatas
+empty = Metadatas mempty
+
+-- | Conversion from dpm to dpi
+dotsPerMeterToDotPerInch :: Word -> Word
+dotsPerMeterToDotPerInch z = z * 254 `div` 10000
+
+-- | Conversion from dpi to dpm
+dotPerInchToDotsPerMeter :: Word -> Word
+dotPerInchToDotsPerMeter z = (z * 10000) `div` 254
+
+-- | Conversion dpcm -> dpi
+dotsPerCentiMeterToDotPerInch :: Word -> Word
+dotsPerCentiMeterToDotPerInch z = z * 254 `div` 100
+
+-- | Create metadatas indicating the resolution, with DpiX == DpiY
+mkDpiMetadata :: Word -> Metadatas
+mkDpiMetadata w =
+  Metadatas [DpiY :=> w, DpiX :=> w]
+
+-- | Create metadatas holding width and height information.
+mkSizeMetadata :: Integral n => n -> n -> Metadatas
+mkSizeMetadata w h = 
+  Metadatas [ Width :=> fromIntegral w, Height :=> fromIntegral h ]
+
+-- | Create simple metadatas with Format, Width & Height
+basicMetadata :: Integral nSize => SourceFormat -> nSize -> nSize -> Metadatas
+basicMetadata f w h =
+  Metadatas [ Format :=> f
+            , Width :=> fromIntegral w
+            , Height :=> fromIntegral h
+            ]
+
+-- | Create simple metadatas with Format, Width, Height, DpiX & DpiY
+simpleMetadata :: (Integral nSize, Integral nDpi)
+               => SourceFormat -> nSize -> nSize -> nDpi -> nDpi -> Metadatas
+simpleMetadata f w h dpiX dpiY =
+  Metadatas [ Format :=> f
+            , Width :=> fromIntegral w
+            , Height :=> fromIntegral h
+            , DpiX :=> fromIntegral dpiX
+            , DpiY :=> fromIntegral dpiY
+            ]
+
diff --git a/src/Codec/Picture/Metadata/Exif.hs b/src/Codec/Picture/Metadata/Exif.hs
--- a/src/Codec/Picture/Metadata/Exif.hs
+++ b/src/Codec/Picture/Metadata/Exif.hs
@@ -1,214 +1,214 @@
-{-# LANGUAGE DeriveGeneric #-}
-
--- | This module provide a totally partial and incomplete maping
--- of Exif values. Used for Tiff parsing and reused for Exif extraction.
-module Codec.Picture.Metadata.Exif ( ExifTag( .. )
-                                   , ExifData( .. )
-
-                                   , tagOfWord16
-                                   , word16OfTag
-
-                                   , isInIFD0
-                                   ) where
-
-import Control.DeepSeq( NFData( .. ) )
-import Data.Int( Int32 )
-import Data.Word( Word16, Word32 )
-import qualified Data.Vector as V
-import qualified Data.ByteString as B
-import GHC.Generics( Generic )
-
--- | Tag values used for exif fields. Completly incomplete
-data ExifTag
-  = TagPhotometricInterpretation
-  | TagCompression -- ^ Short type
-  | TagImageWidth  -- ^ Short or long type
-  | TagImageLength -- ^ Short or long type
-  | TagXResolution -- ^ Rational type
-  | TagYResolution -- ^ Rational type
-  | TagResolutionUnit --  ^ Short type
-  | TagRowPerStrip -- ^ Short or long type
-  | TagStripByteCounts -- ^ Short or long
-  | TagStripOffsets -- ^ Short or long
-  | TagBitsPerSample --  ^ Short
-  | TagColorMap -- ^ Short
-  | TagTileWidth
-  | TagTileLength
-  | TagTileOffset
-  | TagTileByteCount
-  | TagSamplesPerPixel -- ^ Short
-  | TagArtist
-  | TagDocumentName
-  | TagSoftware
-  | TagPlanarConfiguration -- ^ Short
-  | TagOrientation
-  | TagSampleFormat -- ^ Short
-  | TagInkSet
-  | TagSubfileType
-  | TagFillOrder
-  | TagYCbCrCoeff
-  | TagYCbCrSubsampling
-  | TagYCbCrPositioning
-  | TagReferenceBlackWhite
-  | TagXPosition
-  | TagYPosition
-  | TagExtraSample
-  | TagImageDescription
-  | TagPredictor
-  | TagCopyright
-  | TagMake
-  | TagModel
-  | TagDateTime
-  | TagGPSInfo
-  | TagLightSource -- ^ Short
-  | TagFlash -- ^ Short
-
-  | TagJpegProc
-  | TagJPEGInterchangeFormat
-  | TagJPEGInterchangeFormatLength
-  | TagJPEGRestartInterval
-  | TagJPEGLosslessPredictors
-  | TagJPEGPointTransforms
-  | TagJPEGQTables
-  | TagJPEGDCTables
-  | TagJPEGACTables
-
-  | TagExifOffset
-  | TagUnknown !Word16
-  deriving (Eq, Ord, Show, Generic)
-instance NFData ExifTag
-
--- | Convert a value to it's corresponding Exif tag.
--- Will often be written as 'TagUnknown'
-tagOfWord16 :: Word16 -> ExifTag
-tagOfWord16 v = case v of
-  255 -> TagSubfileType
-  256 -> TagImageWidth
-  257 -> TagImageLength
-  258 -> TagBitsPerSample
-  259 -> TagCompression
-  262 -> TagPhotometricInterpretation
-  266 -> TagFillOrder
-  269 -> TagDocumentName
-  270 -> TagImageDescription
-  271 -> TagMake
-  272 -> TagModel
-  273 -> TagStripOffsets
-  274 -> TagOrientation
-  277 -> TagSamplesPerPixel
-  278 -> TagRowPerStrip
-  279 -> TagStripByteCounts
-  282 -> TagXResolution
-  283 -> TagYResolution
-  284 -> TagPlanarConfiguration
-  286 -> TagXPosition
-  287 -> TagYPosition
-  296 -> TagResolutionUnit
-  305 -> TagSoftware
-  306 -> TagDateTime
-  315 -> TagArtist
-  317 -> TagPredictor
-  320 -> TagColorMap
-  322 -> TagTileWidth
-  323 -> TagTileLength
-  324 -> TagTileOffset
-  325 -> TagTileByteCount
-  332 -> TagInkSet
-  338 -> TagExtraSample
-  339 -> TagSampleFormat
-  529 -> TagYCbCrCoeff
-  512 -> TagJpegProc
-  513 -> TagJPEGInterchangeFormat
-  514 -> TagJPEGInterchangeFormatLength
-  515 -> TagJPEGRestartInterval
-  517 -> TagJPEGLosslessPredictors
-  518 -> TagJPEGPointTransforms
-  519 -> TagJPEGQTables
-  520 -> TagJPEGDCTables
-  521 -> TagJPEGACTables
-  530 -> TagYCbCrSubsampling
-  531 -> TagYCbCrPositioning
-  532 -> TagReferenceBlackWhite
-  33432 -> TagCopyright
-  34665 -> TagExifOffset
-  34853 -> TagGPSInfo
-  37384 -> TagLightSource
-  37385 -> TagFlash
-  vv -> TagUnknown vv
-
--- | Convert a tag to it's corresponding value.
-word16OfTag :: ExifTag -> Word16
-word16OfTag t = case t of
-  TagSubfileType -> 255
-  TagImageWidth -> 256
-  TagImageLength -> 257
-  TagBitsPerSample -> 258
-  TagCompression -> 259
-  TagPhotometricInterpretation -> 262
-  TagFillOrder -> 266
-  TagDocumentName -> 269
-  TagImageDescription -> 270
-  TagMake -> 271
-  TagModel -> 272
-  TagStripOffsets -> 273
-  TagOrientation -> 274
-  TagSamplesPerPixel -> 277
-  TagRowPerStrip -> 278
-  TagStripByteCounts -> 279
-  TagXResolution -> 282
-  TagYResolution -> 283
-  TagPlanarConfiguration -> 284
-  TagXPosition -> 286
-  TagYPosition -> 287
-  TagResolutionUnit -> 296
-  TagSoftware -> 305
-  TagDateTime -> 306
-  TagArtist -> 315
-  TagPredictor -> 317
-  TagColorMap -> 320
-  TagTileWidth -> 322
-  TagTileLength -> 323
-  TagTileOffset -> 324
-  TagTileByteCount -> 325
-  TagInkSet -> 332
-  TagExtraSample -> 338
-  TagSampleFormat -> 339
-  TagYCbCrCoeff -> 529
-  TagJpegProc -> 512
-  TagJPEGInterchangeFormat -> 513
-  TagJPEGInterchangeFormatLength -> 514
-  TagJPEGRestartInterval -> 515
-  TagJPEGLosslessPredictors -> 517
-  TagJPEGPointTransforms -> 518
-  TagJPEGQTables -> 519
-  TagJPEGDCTables -> 520
-  TagJPEGACTables -> 521
-  TagYCbCrSubsampling -> 530
-  TagYCbCrPositioning -> 531
-  TagReferenceBlackWhite -> 532
-  TagCopyright -> 33432
-  TagExifOffset -> 34665
-  TagGPSInfo -> 34853
-  TagLightSource -> 37384
-  TagFlash -> 37385
-  (TagUnknown v) -> v
-
-isInIFD0 :: ExifTag -> Bool
-isInIFD0 t = word16OfTag t <= lastTag || isRedirectTag where
-  lastTag = word16OfTag TagCopyright
-  isRedirectTag = t `elem` [TagExifOffset, TagGPSInfo]
-
--- | Possible data held by an Exif tag
-data ExifData
-  = ExifNone
-  | ExifLong      !Word32
-  | ExifShort     !Word16
-  | ExifString    !B.ByteString
-  | ExifUndefined !B.ByteString
-  | ExifShorts    !(V.Vector Word16)
-  | ExifLongs     !(V.Vector Word32)
-  | ExifRational  !Word32 !Word32
-  | ExifSignedRational  !Int32 !Int32
-  | ExifIFD       ![(ExifTag, ExifData)]
-  deriving (Eq, Show, Generic)
-instance NFData ExifData
+{-# LANGUAGE DeriveGeneric #-}
+
+-- | This module provide a totally partial and incomplete mapping
+-- of Exif values. Used for Tiff parsing and reused for Exif extraction.
+module Codec.Picture.Metadata.Exif ( ExifTag( .. )
+                                   , ExifData( .. )
+
+                                   , tagOfWord16
+                                   , word16OfTag
+
+                                   , isInIFD0
+                                   ) where
+
+import Control.DeepSeq( NFData( .. ) )
+import Data.Int( Int32 )
+import Data.Word( Word16, Word32 )
+import qualified Data.Vector as V
+import qualified Data.ByteString as B
+import GHC.Generics( Generic )
+
+-- | Tag values used for exif fields. Completely incomplete
+data ExifTag
+  = TagPhotometricInterpretation
+  | TagCompression -- ^ Short type
+  | TagImageWidth  -- ^ Short or long type
+  | TagImageLength -- ^ Short or long type
+  | TagXResolution -- ^ Rational type
+  | TagYResolution -- ^ Rational type
+  | TagResolutionUnit --  ^ Short type
+  | TagRowPerStrip -- ^ Short or long type
+  | TagStripByteCounts -- ^ Short or long
+  | TagStripOffsets -- ^ Short or long
+  | TagBitsPerSample --  ^ Short
+  | TagColorMap -- ^ Short
+  | TagTileWidth
+  | TagTileLength
+  | TagTileOffset
+  | TagTileByteCount
+  | TagSamplesPerPixel -- ^ Short
+  | TagArtist
+  | TagDocumentName
+  | TagSoftware
+  | TagPlanarConfiguration -- ^ Short
+  | TagOrientation
+  | TagSampleFormat -- ^ Short
+  | TagInkSet
+  | TagSubfileType
+  | TagFillOrder
+  | TagYCbCrCoeff
+  | TagYCbCrSubsampling
+  | TagYCbCrPositioning
+  | TagReferenceBlackWhite
+  | TagXPosition
+  | TagYPosition
+  | TagExtraSample
+  | TagImageDescription
+  | TagPredictor
+  | TagCopyright
+  | TagMake
+  | TagModel
+  | TagDateTime
+  | TagGPSInfo
+  | TagLightSource -- ^ Short
+  | TagFlash -- ^ Short
+
+  | TagJpegProc
+  | TagJPEGInterchangeFormat
+  | TagJPEGInterchangeFormatLength
+  | TagJPEGRestartInterval
+  | TagJPEGLosslessPredictors
+  | TagJPEGPointTransforms
+  | TagJPEGQTables
+  | TagJPEGDCTables
+  | TagJPEGACTables
+
+  | TagExifOffset
+  | TagUnknown !Word16
+  deriving (Eq, Ord, Show, Generic)
+instance NFData ExifTag
+
+-- | Convert a value to it's corresponding Exif tag.
+-- Will often be written as 'TagUnknown'
+tagOfWord16 :: Word16 -> ExifTag
+tagOfWord16 v = case v of
+  255 -> TagSubfileType
+  256 -> TagImageWidth
+  257 -> TagImageLength
+  258 -> TagBitsPerSample
+  259 -> TagCompression
+  262 -> TagPhotometricInterpretation
+  266 -> TagFillOrder
+  269 -> TagDocumentName
+  270 -> TagImageDescription
+  271 -> TagMake
+  272 -> TagModel
+  273 -> TagStripOffsets
+  274 -> TagOrientation
+  277 -> TagSamplesPerPixel
+  278 -> TagRowPerStrip
+  279 -> TagStripByteCounts
+  282 -> TagXResolution
+  283 -> TagYResolution
+  284 -> TagPlanarConfiguration
+  286 -> TagXPosition
+  287 -> TagYPosition
+  296 -> TagResolutionUnit
+  305 -> TagSoftware
+  306 -> TagDateTime
+  315 -> TagArtist
+  317 -> TagPredictor
+  320 -> TagColorMap
+  322 -> TagTileWidth
+  323 -> TagTileLength
+  324 -> TagTileOffset
+  325 -> TagTileByteCount
+  332 -> TagInkSet
+  338 -> TagExtraSample
+  339 -> TagSampleFormat
+  529 -> TagYCbCrCoeff
+  512 -> TagJpegProc
+  513 -> TagJPEGInterchangeFormat
+  514 -> TagJPEGInterchangeFormatLength
+  515 -> TagJPEGRestartInterval
+  517 -> TagJPEGLosslessPredictors
+  518 -> TagJPEGPointTransforms
+  519 -> TagJPEGQTables
+  520 -> TagJPEGDCTables
+  521 -> TagJPEGACTables
+  530 -> TagYCbCrSubsampling
+  531 -> TagYCbCrPositioning
+  532 -> TagReferenceBlackWhite
+  33432 -> TagCopyright
+  34665 -> TagExifOffset
+  34853 -> TagGPSInfo
+  37384 -> TagLightSource
+  37385 -> TagFlash
+  vv -> TagUnknown vv
+
+-- | Convert a tag to it's corresponding value.
+word16OfTag :: ExifTag -> Word16
+word16OfTag t = case t of
+  TagSubfileType -> 255
+  TagImageWidth -> 256
+  TagImageLength -> 257
+  TagBitsPerSample -> 258
+  TagCompression -> 259
+  TagPhotometricInterpretation -> 262
+  TagFillOrder -> 266
+  TagDocumentName -> 269
+  TagImageDescription -> 270
+  TagMake -> 271
+  TagModel -> 272
+  TagStripOffsets -> 273
+  TagOrientation -> 274
+  TagSamplesPerPixel -> 277
+  TagRowPerStrip -> 278
+  TagStripByteCounts -> 279
+  TagXResolution -> 282
+  TagYResolution -> 283
+  TagPlanarConfiguration -> 284
+  TagXPosition -> 286
+  TagYPosition -> 287
+  TagResolutionUnit -> 296
+  TagSoftware -> 305
+  TagDateTime -> 306
+  TagArtist -> 315
+  TagPredictor -> 317
+  TagColorMap -> 320
+  TagTileWidth -> 322
+  TagTileLength -> 323
+  TagTileOffset -> 324
+  TagTileByteCount -> 325
+  TagInkSet -> 332
+  TagExtraSample -> 338
+  TagSampleFormat -> 339
+  TagYCbCrCoeff -> 529
+  TagJpegProc -> 512
+  TagJPEGInterchangeFormat -> 513
+  TagJPEGInterchangeFormatLength -> 514
+  TagJPEGRestartInterval -> 515
+  TagJPEGLosslessPredictors -> 517
+  TagJPEGPointTransforms -> 518
+  TagJPEGQTables -> 519
+  TagJPEGDCTables -> 520
+  TagJPEGACTables -> 521
+  TagYCbCrSubsampling -> 530
+  TagYCbCrPositioning -> 531
+  TagReferenceBlackWhite -> 532
+  TagCopyright -> 33432
+  TagExifOffset -> 34665
+  TagGPSInfo -> 34853
+  TagLightSource -> 37384
+  TagFlash -> 37385
+  (TagUnknown v) -> v
+
+isInIFD0 :: ExifTag -> Bool
+isInIFD0 t = word16OfTag t <= lastTag || isRedirectTag where
+  lastTag = word16OfTag TagCopyright
+  isRedirectTag = t `elem` [TagExifOffset, TagGPSInfo]
+
+-- | Possible data held by an Exif tag
+data ExifData
+  = ExifNone
+  | ExifLong      !Word32
+  | ExifShort     !Word16
+  | ExifString    !B.ByteString
+  | ExifUndefined !B.ByteString
+  | ExifShorts    !(V.Vector Word16)
+  | ExifLongs     !(V.Vector Word32)
+  | ExifRational  !Word32 !Word32
+  | ExifSignedRational  !Int32 !Int32
+  | ExifIFD       ![(ExifTag, ExifData)]
+  deriving (Eq, Show, Generic)
+instance NFData ExifData
diff --git a/src/Codec/Picture/Png.hs b/src/Codec/Picture/Png.hs
--- a/src/Codec/Picture/Png.hs
+++ b/src/Codec/Picture/Png.hs
@@ -498,7 +498,7 @@
 decodePngWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
 decodePngWithMetadata b = first palettedToTrueColor <$> decodePngWithPaletteAndMetadata b
 
--- | Same as 'decodePng' but also extract meta datas present
+-- | Same as 'decodePng' but also extract meta data present
 -- in the files.
 decodePngWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
 decodePngWithPaletteAndMetadata byte =  do
diff --git a/src/Codec/Picture/Png/Internal/Export.hs b/src/Codec/Picture/Png/Internal/Export.hs
--- a/src/Codec/Picture/Png/Internal/Export.hs
+++ b/src/Codec/Picture/Png/Internal/Export.hs
@@ -3,7 +3,7 @@
 {-# LANGUAGE TypeSynonymInstances #-}
 {-# LANGUAGE TypeFamilies #-}
 {-# LANGUAGE ScopedTypeVariables #-}
--- | Module implementing a basic png export, no filtering is applyed, but
+-- | Module implementing a basic png export, no filtering is applied, but
 -- export at least valid images.
 module Codec.Picture.Png.Internal.Export( PngSavable( .. )
                                , PngPaletteSaveable( .. )
@@ -93,11 +93,11 @@
     --  * 'Codec.Picture.Metadata.Warning'
     --  * 'Codec.Picture.Metadata.Unknown' using the key present in the constructor.
     -- 
-    -- the followings metadata will be stored in the `gAMA` chunk.
+    -- the following metadata will be stored in the `gAMA` chunk.
     --
     --  * 'Codec.Picture.Metadata.Gamma'
     --
-    -- The followings metadata will be stored in a `pHYs` chunk
+    -- The following metadata will be stored in a `pHYs` chunk
     --
     --  * 'Codec.Picture.Metadata.DpiX'
     --  * 'Codec.Picture.Metadata.DpiY' 
diff --git a/src/Codec/Picture/Png/Internal/Metadata.hs b/src/Codec/Picture/Png/Internal/Metadata.hs
--- a/src/Codec/Picture/Png/Internal/Metadata.hs
+++ b/src/Codec/Picture/Png/Internal/Metadata.hs
@@ -1,167 +1,167 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE GADTs #-}
-{-# LANGUAGE OverloadedStrings #-}
-module Codec.Picture.Png.Internal.Metadata( extractMetadatas
-                                 , encodeMetadatas
-                                 ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>), (<*>), pure )
-import Data.Monoid( Monoid, mempty )
-import Data.Foldable( foldMap )
-#endif
-
-import Data.Maybe( fromMaybe )
-import Data.Binary( Binary( get, put ), encode )
-import Data.Binary.Get( getLazyByteStringNul, getWord8 )
-import Data.Binary.Put( putLazyByteString, putWord8 )
-import qualified Data.ByteString.Lazy.Char8 as L
-#if !MIN_VERSION_base(4,11,0)
-import Data.Monoid( (<>) )
-#endif
-
-import qualified Codec.Compression.Zlib as Z
-
-import Codec.Picture.InternalHelper
-import qualified Codec.Picture.Metadata as Met
-import Codec.Picture.Metadata ( Metadatas
-                              , dotsPerMeterToDotPerInch
-                              , Elem( (:=>) ) )
-import Codec.Picture.Png.Internal.Type
-
-#if !MIN_VERSION_base(4,7,0)
-eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
-eitherFoldMap f v = case v of
-  Left _ -> mempty
-  Right a -> f a
-#else
-eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
-eitherFoldMap = foldMap
-#endif
-
-getGamma :: [L.ByteString] -> Metadatas
-getGamma [] = mempty
-getGamma (g:_) = eitherFoldMap unpackGamma $ runGet get g
-  where
-    unpackGamma gamma = Met.singleton Met.Gamma (getPngGamma gamma)
-
-getDpis :: [L.ByteString] -> Metadatas
-getDpis [] = mempty
-getDpis (b:_) = eitherFoldMap unpackPhys $ runGet get b
-  where
-    unpackPhys PngPhysicalDimension { pngUnit = PngUnitUnknown } =
-      Met.insert Met.DpiX 72 $ Met.singleton Met.DpiY 72
-    unpackPhys phy@PngPhysicalDimension { pngUnit = PngUnitMeter } =
-      Met.insert Met.DpiX dpx $ Met.singleton Met.DpiY dpy
-        where
-          dpx = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiX phy
-          dpy = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiY phy
-
-data PngText = PngText
-  { pngKeyword :: !L.ByteString
-  , pngData    :: !L.ByteString
-  }
-  deriving Show
-
-instance Binary PngText where
-  get = PngText <$> getLazyByteStringNul <*> getRemainingLazyBytes
-  put (PngText kw pdata) = do
-    putLazyByteString kw
-    putWord8 0
-    putLazyByteString pdata
-
-data PngZText = PngZText
-  { pngZKeyword :: !L.ByteString
-  , pngZData    :: !L.ByteString
-  }
-  deriving Show
-
-instance Binary PngZText where
-  get = PngZText <$> getLazyByteStringNul <* getCompressionType <*> (Z.decompress <$> getRemainingLazyBytes)
-    where
-      getCompressionType = do
-        0 <- getWord8
-        return ()
-  put (PngZText kw pdata) = do
-    putLazyByteString kw
-    putWord8 0
-    putWord8 0 -- compression type
-    putLazyByteString (Z.compress pdata)
-
-aToMetadata :: (a -> L.ByteString) -> (a -> L.ByteString) -> a -> Metadatas
-aToMetadata pkeyword pdata ptext = case pkeyword ptext of
-  "Title" -> strValue Met.Title
-  "Author" -> strValue Met.Author
-  "Description" -> strValue Met.Description
-  "Copyright" -> strValue Met.Copyright
-  {-"Creation Time" -> strValue Creation-}
-  "Software" -> strValue Met.Software
-  "Disclaimer" -> strValue Met.Disclaimer
-  "Warning" -> strValue Met.Warning
-  "Source" -> strValue Met.Source
-  "Comment" -> strValue Met.Comment
-  other -> 
-    Met.singleton
-      (Met.Unknown $ L.unpack other)
-      (Met.String . L.unpack $ pdata ptext)
-  where
-    strValue k = Met.singleton k . L.unpack $ pdata ptext
-
-textToMetadata :: PngText -> Metadatas
-textToMetadata = aToMetadata pngKeyword pngData
-
-ztxtToMetadata :: PngZText -> Metadatas
-ztxtToMetadata = aToMetadata pngZKeyword pngZData
-
-getTexts :: [L.ByteString] -> Metadatas
-getTexts = foldMap (eitherFoldMap textToMetadata . runGet get)
-
-getZTexts :: [L.ByteString] -> Metadatas
-getZTexts = foldMap (eitherFoldMap ztxtToMetadata . runGet get)
-
-extractMetadatas :: PngRawImage -> Metadatas
-extractMetadatas img = getDpis (chunksOf pHYsSignature)
-                    <> getGamma (chunksOf gammaSignature)
-                    <> getTexts (chunksOf tEXtSignature)
-                    <> getZTexts (chunksOf zTXtSignature)
-  where
-    chunksOf = chunksWithSig img
-
-encodePhysicalMetadata :: Metadatas -> [PngRawChunk]
-encodePhysicalMetadata metas = fromMaybe [] $ do
-  dx <- Met.lookup Met.DpiX metas
-  dy <- Met.lookup Met.DpiY metas
-  let to = fromIntegral . Met.dotPerInchToDotsPerMeter
-      dim = PngPhysicalDimension (to dx) (to dy) PngUnitMeter
-  pure [mkRawChunk pHYsSignature $ encode dim]
-
-encodeSingleMetadata :: Metadatas -> [PngRawChunk]
-encodeSingleMetadata = Met.foldMap go where
-  go :: Elem Met.Keys -> [PngRawChunk]
-  go v = case v of
-    Met.Exif _ :=> _ -> mempty
-    Met.DpiX :=> _ -> mempty
-    Met.DpiY :=> _ -> mempty
-    Met.Width :=> _ -> mempty
-    Met.Height :=> _ -> mempty
-    Met.Format :=> _ -> mempty
-    Met.Gamma       :=> g ->
-      pure $ mkRawChunk gammaSignature . encode $ PngGamma g
-    Met.ColorSpace  :=> _ -> mempty
-    Met.Title       :=> tx -> txt "Title" (L.pack tx)
-    Met.Description :=> tx -> txt "Description" (L.pack tx)
-    Met.Author      :=> tx -> txt "Author" (L.pack tx)
-    Met.Copyright   :=> tx -> txt "Copyright" (L.pack tx)
-    Met.Software    :=> tx -> txt "Software" (L.pack tx)
-    Met.Comment     :=> tx -> txt "Comment" (L.pack tx)
-    Met.Disclaimer  :=> tx -> txt "Disclaimer" (L.pack tx)
-    Met.Source      :=> tx -> txt "Source" (L.pack tx)
-    Met.Warning     :=> tx -> txt "Warning" (L.pack tx)
-    Met.Unknown k   :=> Met.String tx -> txt (L.pack k) (L.pack tx)
-    Met.Unknown _   :=> _ -> mempty
-
-  txt k c = pure . mkRawChunk tEXtSignature . encode $ PngText k c
-
-encodeMetadatas :: Metadatas -> [PngRawChunk]
-encodeMetadatas m = encodePhysicalMetadata m <> encodeSingleMetadata m
-
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE GADTs #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Codec.Picture.Png.Internal.Metadata( extractMetadatas
+                                 , encodeMetadatas
+                                 ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>), (<*>), pure )
+import Data.Monoid( Monoid, mempty )
+import Data.Foldable( foldMap )
+#endif
+
+import Data.Maybe( fromMaybe )
+import Data.Binary( Binary( get, put ), encode )
+import Data.Binary.Get( getLazyByteStringNul, getWord8 )
+import Data.Binary.Put( putLazyByteString, putWord8 )
+import qualified Data.ByteString.Lazy.Char8 as L
+#if !MIN_VERSION_base(4,11,0)
+import Data.Monoid( (<>) )
+#endif
+
+import qualified Codec.Compression.Zlib as Z
+
+import Codec.Picture.InternalHelper
+import qualified Codec.Picture.Metadata as Met
+import Codec.Picture.Metadata ( Metadatas
+                              , dotsPerMeterToDotPerInch
+                              , Elem( (:=>) ) )
+import Codec.Picture.Png.Internal.Type
+
+#if !MIN_VERSION_base(4,7,0)
+eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
+eitherFoldMap f v = case v of
+  Left _ -> mempty
+  Right a -> f a
+#else
+eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
+eitherFoldMap = foldMap
+#endif
+
+getGamma :: [L.ByteString] -> Metadatas
+getGamma [] = mempty
+getGamma (g:_) = eitherFoldMap unpackGamma $ runGet get g
+  where
+    unpackGamma gamma = Met.singleton Met.Gamma (getPngGamma gamma)
+
+getDpis :: [L.ByteString] -> Metadatas
+getDpis [] = mempty
+getDpis (b:_) = eitherFoldMap unpackPhys $ runGet get b
+  where
+    unpackPhys PngPhysicalDimension { pngUnit = PngUnitUnknown } =
+      Met.insert Met.DpiX 72 $ Met.singleton Met.DpiY 72
+    unpackPhys phy@PngPhysicalDimension { pngUnit = PngUnitMeter } =
+      Met.insert Met.DpiX dpx $ Met.singleton Met.DpiY dpy
+        where
+          dpx = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiX phy
+          dpy = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiY phy
+
+data PngText = PngText
+  { pngKeyword :: !L.ByteString
+  , pngData    :: !L.ByteString
+  }
+  deriving Show
+
+instance Binary PngText where
+  get = PngText <$> getLazyByteStringNul <*> getRemainingLazyBytes
+  put (PngText kw pdata) = do
+    putLazyByteString kw
+    putWord8 0
+    putLazyByteString pdata
+
+data PngZText = PngZText
+  { pngZKeyword :: !L.ByteString
+  , pngZData    :: !L.ByteString
+  }
+  deriving Show
+
+instance Binary PngZText where
+  get = PngZText <$> getLazyByteStringNul <* getCompressionType <*> (Z.decompress <$> getRemainingLazyBytes)
+    where
+      getCompressionType = do
+        0 <- getWord8
+        return ()
+  put (PngZText kw pdata) = do
+    putLazyByteString kw
+    putWord8 0
+    putWord8 0 -- compression type
+    putLazyByteString (Z.compress pdata)
+
+aToMetadata :: (a -> L.ByteString) -> (a -> L.ByteString) -> a -> Metadatas
+aToMetadata pkeyword pdata ptext = case pkeyword ptext of
+  "Title" -> strValue Met.Title
+  "Author" -> strValue Met.Author
+  "Description" -> strValue Met.Description
+  "Copyright" -> strValue Met.Copyright
+  {-"Creation Time" -> strValue Creation-}
+  "Software" -> strValue Met.Software
+  "Disclaimer" -> strValue Met.Disclaimer
+  "Warning" -> strValue Met.Warning
+  "Source" -> strValue Met.Source
+  "Comment" -> strValue Met.Comment
+  other -> 
+    Met.singleton
+      (Met.Unknown $ L.unpack other)
+      (Met.String . L.unpack $ pdata ptext)
+  where
+    strValue k = Met.singleton k . L.unpack $ pdata ptext
+
+textToMetadata :: PngText -> Metadatas
+textToMetadata = aToMetadata pngKeyword pngData
+
+ztxtToMetadata :: PngZText -> Metadatas
+ztxtToMetadata = aToMetadata pngZKeyword pngZData
+
+getTexts :: [L.ByteString] -> Metadatas
+getTexts = foldMap (eitherFoldMap textToMetadata . runGet get)
+
+getZTexts :: [L.ByteString] -> Metadatas
+getZTexts = foldMap (eitherFoldMap ztxtToMetadata . runGet get)
+
+extractMetadatas :: PngRawImage -> Metadatas
+extractMetadatas img = getDpis (chunksOf pHYsSignature)
+                    <> getGamma (chunksOf gammaSignature)
+                    <> getTexts (chunksOf tEXtSignature)
+                    <> getZTexts (chunksOf zTXtSignature)
+  where
+    chunksOf = chunksWithSig img
+
+encodePhysicalMetadata :: Metadatas -> [PngRawChunk]
+encodePhysicalMetadata metas = fromMaybe [] $ do
+  dx <- Met.lookup Met.DpiX metas
+  dy <- Met.lookup Met.DpiY metas
+  let to = fromIntegral . Met.dotPerInchToDotsPerMeter
+      dim = PngPhysicalDimension (to dx) (to dy) PngUnitMeter
+  pure [mkRawChunk pHYsSignature $ encode dim]
+
+encodeSingleMetadata :: Metadatas -> [PngRawChunk]
+encodeSingleMetadata = Met.foldMap go where
+  go :: Elem Met.Keys -> [PngRawChunk]
+  go v = case v of
+    Met.Exif _ :=> _ -> mempty
+    Met.DpiX :=> _ -> mempty
+    Met.DpiY :=> _ -> mempty
+    Met.Width :=> _ -> mempty
+    Met.Height :=> _ -> mempty
+    Met.Format :=> _ -> mempty
+    Met.Gamma       :=> g ->
+      pure $ mkRawChunk gammaSignature . encode $ PngGamma g
+    Met.ColorSpace  :=> _ -> mempty
+    Met.Title       :=> tx -> txt "Title" (L.pack tx)
+    Met.Description :=> tx -> txt "Description" (L.pack tx)
+    Met.Author      :=> tx -> txt "Author" (L.pack tx)
+    Met.Copyright   :=> tx -> txt "Copyright" (L.pack tx)
+    Met.Software    :=> tx -> txt "Software" (L.pack tx)
+    Met.Comment     :=> tx -> txt "Comment" (L.pack tx)
+    Met.Disclaimer  :=> tx -> txt "Disclaimer" (L.pack tx)
+    Met.Source      :=> tx -> txt "Source" (L.pack tx)
+    Met.Warning     :=> tx -> txt "Warning" (L.pack tx)
+    Met.Unknown k   :=> Met.String tx -> txt (L.pack k) (L.pack tx)
+    Met.Unknown _   :=> _ -> mempty
+
+  txt k c = pure . mkRawChunk tEXtSignature . encode $ PngText k c
+
+encodeMetadatas :: Metadatas -> [PngRawChunk]
+encodeMetadatas m = encodePhysicalMetadata m <> encodeSingleMetadata m
+
diff --git a/src/Codec/Picture/Png/Internal/Type.hs b/src/Codec/Picture/Png/Internal/Type.hs
--- a/src/Codec/Picture/Png/Internal/Type.hs
+++ b/src/Codec/Picture/Png/Internal/Type.hs
@@ -381,7 +381,7 @@
 iHDRSignature = signature "IHDR"
 
 -- | Signature for a palette chunk in the pgn file. Must
--- occure before iDAT.
+-- occurred before iDAT.
 pLTESignature :: ChunkSignature
 pLTESignature = signature "PLTE"
 
diff --git a/src/Codec/Picture/Saving.hs b/src/Codec/Picture/Saving.hs
--- a/src/Codec/Picture/Saving.hs
+++ b/src/Codec/Picture/Saving.hs
@@ -1,239 +1,239 @@
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE CPP #-}
--- | Helper functions to save dynamic images to other file format
--- with automatic color space/sample format conversion done automatically.
-module Codec.Picture.Saving( imageToJpg
-                           , imageToPng
-                           , imageToGif
-                           , imageToBitmap
-                           , imageToTiff
-                           , imageToRadiance
-                           , imageToTga
-                           ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Data.Monoid( mempty )
-#endif
-
-import Data.Bits( unsafeShiftR )
-import Data.Word( Word8, Word16, Word32 )
-import qualified Data.ByteString.Lazy as L
-import Codec.Picture.Bitmap
-import Codec.Picture.Jpg
-import Codec.Picture.Png
-import Codec.Picture.Gif
-import Codec.Picture.ColorQuant
-import Codec.Picture.HDR
-import Codec.Picture.Types
-import Codec.Picture.Tiff
-import Codec.Picture.Tga
-
-import qualified Data.Vector.Storable as V
-
-componentToLDR :: Float -> Word8
-componentToLDR = truncate . (255 *) . min 1.0 . max 0.0
-
-toStandardDef :: Image PixelRGBF -> Image PixelRGB8
-toStandardDef = pixelMap pixelConverter
-  where pixelConverter (PixelRGBF rf gf bf) = PixelRGB8 r g b
-          where r = componentToLDR rf
-                g = componentToLDR gf
-                b = componentToLDR bf
-
-greyScaleToStandardDef :: Image PixelF -> Image Pixel8
-greyScaleToStandardDef = pixelMap componentToLDR
-
-from16to8 :: ( PixelBaseComponent source ~ Word16
-             , PixelBaseComponent dest ~ Word8 )
-          => Image source -> Image dest
-from16to8 Image { imageWidth = w, imageHeight = h
-                , imageData = arr } = Image w h transformed
-   where transformed = V.map toWord8 arr
-         toWord8 v = fromIntegral (v `unsafeShiftR` 8)
-
-from32to8 :: ( PixelBaseComponent source ~ Word32
-             , PixelBaseComponent dest ~ Word8 )
-          => Image source -> Image dest
-from32to8 Image { imageWidth = w, imageHeight = h
-                , imageData = arr } = Image w h transformed
-   where transformed = V.map toWord8 arr
-         toWord8 v = fromIntegral (v `unsafeShiftR` 24)
-
-from32to16 :: ( PixelBaseComponent source ~ Word32
-             , PixelBaseComponent dest ~ Word16 )
-          => Image source -> Image dest
-from32to16 Image { imageWidth = w, imageHeight = h
-                , imageData = arr } = Image w h transformed
-   where transformed = V.map toWord16 arr
-         toWord16 v = fromIntegral (v `unsafeShiftR` 16)
-
-from16toFloat :: ( PixelBaseComponent source ~ Word16
-                 , PixelBaseComponent dest ~ Float )
-          => Image source -> Image dest
-from16toFloat Image { imageWidth = w, imageHeight = h
-                    , imageData = arr } = Image w h transformed
-   where transformed = V.map toWord8 arr
-         toWord8 v = fromIntegral v / 65536.0
-
--- | This function will try to do anything to encode an image
--- as RADIANCE, make all color conversion and such. Equivalent
--- of 'decodeImage' for radiance encoding
-imageToRadiance :: DynamicImage -> L.ByteString
-imageToRadiance (ImageCMYK8 img) =
-    imageToRadiance . ImageRGB8 $ convertImage img
-imageToRadiance (ImageCMYK16 img) =
-    imageToRadiance . ImageRGB16 $ convertImage img
-imageToRadiance (ImageYCbCr8 img) =
-    imageToRadiance . ImageRGB8 $ convertImage img
-imageToRadiance (ImageRGB8   img) =
-    imageToRadiance . ImageRGBF $ promoteImage img
-imageToRadiance (ImageRGBF   img) = encodeHDR img
-imageToRadiance (ImageRGBA8  img) =
-    imageToRadiance . ImageRGBF . promoteImage $ dropAlphaLayer img
-imageToRadiance (ImageY8     img) =
-    imageToRadiance . ImageRGB8 $ promoteImage img
-imageToRadiance (ImageYF     img) =
-    imageToRadiance . ImageRGBF $ promoteImage img
-imageToRadiance (ImageYA8    img) =
-    imageToRadiance . ImageRGB8 . promoteImage $ dropAlphaLayer img
-imageToRadiance (ImageY16    img) =
-  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
-    where toRgbf v = PixelRGBF val val val
-            where val = fromIntegral v / 65536.0
-imageToRadiance (ImageY32    img) =
-  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
-    where toRgbf v = PixelRGBF val val val
-            where val = fromIntegral v / 4294967296.0
-imageToRadiance (ImageYA16   img) =
-  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
-    where toRgbf (PixelYA16 v _) = PixelRGBF val val val
-            where val = fromIntegral v / 65536.0
-imageToRadiance (ImageRGB16  img) =
-    imageToRadiance . ImageRGBF $ from16toFloat img
-imageToRadiance (ImageRGBA16 img) =
-    imageToRadiance . ImageRGBF $ pixelMap toRgbf img
-    where toRgbf (PixelRGBA16 r g b _) = PixelRGBF (f r) (f g) (f b)
-            where f v = fromIntegral v / 65536.0
-
--- | This function will try to do anything to encode an image
--- as JPEG, make all color conversion and such. Equivalent
--- of 'decodeImage' for jpeg encoding
--- Save Y or YCbCr Jpeg only, all other colorspaces are converted.
--- To save a RGB or CMYK JPEG file, use the
--- 'Codec.Picture.Jpg.Internal.encodeDirectJpegAtQualityWithMetadata' function
-imageToJpg :: Int -> DynamicImage -> L.ByteString
-imageToJpg quality dynImage =
-    let encodeAtQuality = encodeJpegAtQuality (fromIntegral quality)
-        encodeWithMeta = encodeDirectJpegAtQualityWithMetadata (fromIntegral quality) mempty
-    in case dynImage of
-        ImageYCbCr8 img -> encodeAtQuality img
-        ImageCMYK8  img -> imageToJpg quality . ImageRGB8 $ convertImage img
-        ImageCMYK16 img -> imageToJpg quality . ImageRGB16 $ convertImage img
-        ImageRGB8   img -> encodeAtQuality (convertImage img)
-        ImageRGBF   img -> imageToJpg quality . ImageRGB8 $ toStandardDef img
-        ImageRGBA8  img -> encodeAtQuality (convertImage $ dropAlphaLayer img)
-        ImageYF     img -> imageToJpg quality . ImageY8 $ greyScaleToStandardDef img
-        ImageY8     img -> encodeWithMeta img
-        ImageYA8    img -> encodeWithMeta $ dropAlphaLayer img
-        ImageY16    img -> imageToJpg quality . ImageY8 $ from16to8 img
-        ImageYA16   img -> imageToJpg quality . ImageYA8 $ from16to8 img
-        ImageY32    img -> imageToJpg quality . ImageY8 $ from32to8 img
-        ImageRGB16  img -> imageToJpg quality . ImageRGB8 $ from16to8 img
-        ImageRGBA16 img -> imageToJpg quality . ImageRGBA8 $ from16to8 img
-
--- | This function will try to do anything to encode an image
--- as PNG, make all color conversion and such. Equivalent
--- of 'decodeImage' for PNG encoding
-imageToPng :: DynamicImage -> L.ByteString
-imageToPng (ImageYCbCr8 img) = encodePng (convertImage img :: Image PixelRGB8)
-imageToPng (ImageCMYK8 img)  = encodePng (convertImage img :: Image PixelRGB8)
-imageToPng (ImageCMYK16 img) = encodePng (convertImage img :: Image PixelRGB16)
-imageToPng (ImageRGB8   img) = encodePng img
-imageToPng (ImageRGBF   img) = encodePng $ toStandardDef img
-imageToPng (ImageRGBA8  img) = encodePng img
-imageToPng (ImageY8     img) = encodePng img
-imageToPng (ImageYF     img) = encodePng $ greyScaleToStandardDef img
-imageToPng (ImageYA8    img) = encodePng img
-imageToPng (ImageY16    img) = encodePng img
-imageToPng (ImageY32    img) = imageToPng . ImageY16 $ from32to16 img
-imageToPng (ImageYA16   img) = encodePng img
-imageToPng (ImageRGB16  img) = encodePng img
-imageToPng (ImageRGBA16 img) = encodePng img
-
--- | This function will try to do anything to encode an image
--- as a Tiff, make all color conversion and such. Equivalent
--- of 'decodeImage' for Tiff encoding
-imageToTiff :: DynamicImage -> L.ByteString
-imageToTiff (ImageYCbCr8 img) = encodeTiff img
-imageToTiff (ImageCMYK8 img)  = encodeTiff img
-imageToTiff (ImageCMYK16 img) = encodeTiff img
-imageToTiff (ImageRGB8   img) = encodeTiff img
-imageToTiff (ImageRGBF   img) = encodeTiff $ toStandardDef img
-imageToTiff (ImageRGBA8  img) = encodeTiff img
-imageToTiff (ImageY8     img) = encodeTiff img
-imageToTiff (ImageYF     img) = encodeTiff $ greyScaleToStandardDef img
-imageToTiff (ImageYA8    img) = encodeTiff $ dropAlphaLayer img
-imageToTiff (ImageY16    img) = encodeTiff img
-imageToTiff (ImageY32    img) = encodeTiff img
-imageToTiff (ImageYA16   img) = encodeTiff $ dropAlphaLayer img
-imageToTiff (ImageRGB16  img) = encodeTiff img
-imageToTiff (ImageRGBA16 img) = encodeTiff img
-
--- | This function will try to do anything to encode an image
--- as bitmap, make all color conversion and such. Equivalent
--- of 'decodeImage' for Bitmap encoding
-imageToBitmap :: DynamicImage -> L.ByteString
-imageToBitmap (ImageYCbCr8 img) = encodeBitmap (convertImage img :: Image PixelRGB8)
-imageToBitmap (ImageCMYK8  img) = encodeBitmap (convertImage img :: Image PixelRGB8)
-imageToBitmap (ImageCMYK16 img) = imageToBitmap . ImageRGB16 $ convertImage img
-imageToBitmap (ImageRGBF   img) = encodeBitmap $ toStandardDef img
-imageToBitmap (ImageRGB8   img) = encodeBitmap img
-imageToBitmap (ImageRGBA8  img) = encodeBitmap img
-imageToBitmap (ImageY8     img) = encodeBitmap img
-imageToBitmap (ImageYF     img) = encodeBitmap $ greyScaleToStandardDef img
-imageToBitmap (ImageYA8    img) = encodeBitmap (promoteImage img :: Image PixelRGBA8)
-imageToBitmap (ImageY16    img) = imageToBitmap . ImageY8 $ from16to8 img
-imageToBitmap (ImageY32    img) = imageToBitmap . ImageY8 $ from32to8 img
-imageToBitmap (ImageYA16   img) = imageToBitmap . ImageYA8 $ from16to8 img
-imageToBitmap (ImageRGB16  img) = imageToBitmap . ImageRGB8 $ from16to8 img
-imageToBitmap (ImageRGBA16 img) = imageToBitmap . ImageRGBA8 $ from16to8 img
-
-
--- | This function will try to do anything to encode an image
--- as a gif, make all color conversion and quantization. Equivalent
--- of 'decodeImage' for gif encoding
-imageToGif :: DynamicImage -> Either String L.ByteString
-imageToGif (ImageYCbCr8 img) = imageToGif . ImageRGB8 $ convertImage img
-imageToGif (ImageCMYK8  img) = imageToGif . ImageRGB8 $ convertImage img
-imageToGif (ImageCMYK16 img) = imageToGif . ImageRGB16 $ convertImage img
-imageToGif (ImageRGBF   img) = imageToGif . ImageRGB8 $ toStandardDef img
-imageToGif (ImageRGB8   img) = encodeGifImageWithPalette indexed pal
-  where (indexed, pal) = palettize defaultPaletteOptions img
-imageToGif (ImageRGBA8  img) = imageToGif . ImageRGB8 $ dropAlphaLayer img
-imageToGif (ImageY8     img) = Right $ encodeGifImage img
-imageToGif (ImageYF     img) = imageToGif . ImageY8 $ greyScaleToStandardDef img
-imageToGif (ImageYA8    img) = imageToGif . ImageY8 $ dropAlphaLayer img
-imageToGif (ImageY16    img) = imageToGif . ImageY8 $ from16to8 img
-imageToGif (ImageY32    img) = imageToGif . ImageY8 $ from32to8 img
-imageToGif (ImageYA16   img) = imageToGif . ImageYA8 $ from16to8 img
-imageToGif (ImageRGB16  img) = imageToGif . ImageRGB8 $ from16to8 img
-imageToGif (ImageRGBA16 img) = imageToGif . ImageRGBA8 $ from16to8 img
-
--- | This function will try to do anything to encode an image
--- as a tga, make all color conversion and quantization. Equivalent
--- of 'decodeImage' for tga encoding
-imageToTga :: DynamicImage -> L.ByteString
-imageToTga (ImageYCbCr8 img) = encodeTga (convertImage img :: Image PixelRGB8)
-imageToTga (ImageCMYK8  img) = encodeTga (convertImage img :: Image PixelRGB8)
-imageToTga (ImageCMYK16 img) = encodeTga (from16to8 img :: Image PixelRGB8)
-imageToTga (ImageRGBF   img) = encodeTga $ toStandardDef img
-imageToTga (ImageRGB8   img) = encodeTga img
-imageToTga (ImageRGBA8  img) = encodeTga img
-imageToTga (ImageY8     img) = encodeTga img
-imageToTga (ImageYF     img) = encodeTga $ greyScaleToStandardDef img
-imageToTga (ImageYA8    img) = encodeTga (promoteImage img :: Image PixelRGBA8)
-imageToTga (ImageY16    img) = encodeTga (from16to8 img :: Image Pixel8)
-imageToTga (ImageY32    img) = encodeTga (from32to8 img :: Image Pixel8)
-imageToTga (ImageYA16   img) = encodeTga (from16to8 img :: Image PixelRGBA8)
-imageToTga (ImageRGB16  img) = encodeTga (from16to8 img :: Image PixelRGB8)
-imageToTga (ImageRGBA16 img) = encodeTga (from16to8 img :: Image PixelRGBA8)
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE CPP #-}
+-- | Helper functions to save dynamic images to other file format
+-- with automatic color space/sample format conversion done automatically.
+module Codec.Picture.Saving( imageToJpg
+                           , imageToPng
+                           , imageToGif
+                           , imageToBitmap
+                           , imageToTiff
+                           , imageToRadiance
+                           , imageToTga
+                           ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Data.Monoid( mempty )
+#endif
+
+import Data.Bits( unsafeShiftR )
+import Data.Word( Word8, Word16, Word32 )
+import qualified Data.ByteString.Lazy as L
+import Codec.Picture.Bitmap
+import Codec.Picture.Jpg
+import Codec.Picture.Png
+import Codec.Picture.Gif
+import Codec.Picture.ColorQuant
+import Codec.Picture.HDR
+import Codec.Picture.Types
+import Codec.Picture.Tiff
+import Codec.Picture.Tga
+
+import qualified Data.Vector.Storable as V
+
+componentToLDR :: Float -> Word8
+componentToLDR = truncate . (255 *) . min 1.0 . max 0.0
+
+toStandardDef :: Image PixelRGBF -> Image PixelRGB8
+toStandardDef = pixelMap pixelConverter
+  where pixelConverter (PixelRGBF rf gf bf) = PixelRGB8 r g b
+          where r = componentToLDR rf
+                g = componentToLDR gf
+                b = componentToLDR bf
+
+greyScaleToStandardDef :: Image PixelF -> Image Pixel8
+greyScaleToStandardDef = pixelMap componentToLDR
+
+from16to8 :: ( PixelBaseComponent source ~ Word16
+             , PixelBaseComponent dest ~ Word8 )
+          => Image source -> Image dest
+from16to8 Image { imageWidth = w, imageHeight = h
+                , imageData = arr } = Image w h transformed
+   where transformed = V.map toWord8 arr
+         toWord8 v = fromIntegral (v `unsafeShiftR` 8)
+
+from32to8 :: ( PixelBaseComponent source ~ Word32
+             , PixelBaseComponent dest ~ Word8 )
+          => Image source -> Image dest
+from32to8 Image { imageWidth = w, imageHeight = h
+                , imageData = arr } = Image w h transformed
+   where transformed = V.map toWord8 arr
+         toWord8 v = fromIntegral (v `unsafeShiftR` 24)
+
+from32to16 :: ( PixelBaseComponent source ~ Word32
+             , PixelBaseComponent dest ~ Word16 )
+          => Image source -> Image dest
+from32to16 Image { imageWidth = w, imageHeight = h
+                , imageData = arr } = Image w h transformed
+   where transformed = V.map toWord16 arr
+         toWord16 v = fromIntegral (v `unsafeShiftR` 16)
+
+from16toFloat :: ( PixelBaseComponent source ~ Word16
+                 , PixelBaseComponent dest ~ Float )
+          => Image source -> Image dest
+from16toFloat Image { imageWidth = w, imageHeight = h
+                    , imageData = arr } = Image w h transformed
+   where transformed = V.map toWord8 arr
+         toWord8 v = fromIntegral v / 65536.0
+
+-- | This function will try to do anything to encode an image
+-- as RADIANCE, make all color conversion and such. Equivalent
+-- of 'decodeImage' for radiance encoding
+imageToRadiance :: DynamicImage -> L.ByteString
+imageToRadiance (ImageCMYK8 img) =
+    imageToRadiance . ImageRGB8 $ convertImage img
+imageToRadiance (ImageCMYK16 img) =
+    imageToRadiance . ImageRGB16 $ convertImage img
+imageToRadiance (ImageYCbCr8 img) =
+    imageToRadiance . ImageRGB8 $ convertImage img
+imageToRadiance (ImageRGB8   img) =
+    imageToRadiance . ImageRGBF $ promoteImage img
+imageToRadiance (ImageRGBF   img) = encodeHDR img
+imageToRadiance (ImageRGBA8  img) =
+    imageToRadiance . ImageRGBF . promoteImage $ dropAlphaLayer img
+imageToRadiance (ImageY8     img) =
+    imageToRadiance . ImageRGB8 $ promoteImage img
+imageToRadiance (ImageYF     img) =
+    imageToRadiance . ImageRGBF $ promoteImage img
+imageToRadiance (ImageYA8    img) =
+    imageToRadiance . ImageRGB8 . promoteImage $ dropAlphaLayer img
+imageToRadiance (ImageY16    img) =
+  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
+    where toRgbf v = PixelRGBF val val val
+            where val = fromIntegral v / 65536.0
+imageToRadiance (ImageY32    img) =
+  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
+    where toRgbf v = PixelRGBF val val val
+            where val = fromIntegral v / 4294967296.0
+imageToRadiance (ImageYA16   img) =
+  imageToRadiance . ImageRGBF $ pixelMap toRgbf img
+    where toRgbf (PixelYA16 v _) = PixelRGBF val val val
+            where val = fromIntegral v / 65536.0
+imageToRadiance (ImageRGB16  img) =
+    imageToRadiance . ImageRGBF $ from16toFloat img
+imageToRadiance (ImageRGBA16 img) =
+    imageToRadiance . ImageRGBF $ pixelMap toRgbf img
+    where toRgbf (PixelRGBA16 r g b _) = PixelRGBF (f r) (f g) (f b)
+            where f v = fromIntegral v / 65536.0
+
+-- | This function will try to do anything to encode an image
+-- as JPEG, make all color conversion and such. Equivalent
+-- of 'decodeImage' for jpeg encoding
+-- Save Y or YCbCr Jpeg only, all other colorspaces are converted.
+-- To save a RGB or CMYK JPEG file, use the
+-- 'Codec.Picture.Jpg.Internal.encodeDirectJpegAtQualityWithMetadata' function
+imageToJpg :: Int -> DynamicImage -> L.ByteString
+imageToJpg quality dynImage =
+    let encodeAtQuality = encodeJpegAtQuality (fromIntegral quality)
+        encodeWithMeta = encodeDirectJpegAtQualityWithMetadata (fromIntegral quality) mempty
+    in case dynImage of
+        ImageYCbCr8 img -> encodeAtQuality img
+        ImageCMYK8  img -> imageToJpg quality . ImageRGB8 $ convertImage img
+        ImageCMYK16 img -> imageToJpg quality . ImageRGB16 $ convertImage img
+        ImageRGB8   img -> encodeAtQuality (convertImage img)
+        ImageRGBF   img -> imageToJpg quality . ImageRGB8 $ toStandardDef img
+        ImageRGBA8  img -> encodeAtQuality (convertImage $ dropAlphaLayer img)
+        ImageYF     img -> imageToJpg quality . ImageY8 $ greyScaleToStandardDef img
+        ImageY8     img -> encodeWithMeta img
+        ImageYA8    img -> encodeWithMeta $ dropAlphaLayer img
+        ImageY16    img -> imageToJpg quality . ImageY8 $ from16to8 img
+        ImageYA16   img -> imageToJpg quality . ImageYA8 $ from16to8 img
+        ImageY32    img -> imageToJpg quality . ImageY8 $ from32to8 img
+        ImageRGB16  img -> imageToJpg quality . ImageRGB8 $ from16to8 img
+        ImageRGBA16 img -> imageToJpg quality . ImageRGBA8 $ from16to8 img
+
+-- | This function will try to do anything to encode an image
+-- as PNG, make all color conversion and such. Equivalent
+-- of 'decodeImage' for PNG encoding
+imageToPng :: DynamicImage -> L.ByteString
+imageToPng (ImageYCbCr8 img) = encodePng (convertImage img :: Image PixelRGB8)
+imageToPng (ImageCMYK8 img)  = encodePng (convertImage img :: Image PixelRGB8)
+imageToPng (ImageCMYK16 img) = encodePng (convertImage img :: Image PixelRGB16)
+imageToPng (ImageRGB8   img) = encodePng img
+imageToPng (ImageRGBF   img) = encodePng $ toStandardDef img
+imageToPng (ImageRGBA8  img) = encodePng img
+imageToPng (ImageY8     img) = encodePng img
+imageToPng (ImageYF     img) = encodePng $ greyScaleToStandardDef img
+imageToPng (ImageYA8    img) = encodePng img
+imageToPng (ImageY16    img) = encodePng img
+imageToPng (ImageY32    img) = imageToPng . ImageY16 $ from32to16 img
+imageToPng (ImageYA16   img) = encodePng img
+imageToPng (ImageRGB16  img) = encodePng img
+imageToPng (ImageRGBA16 img) = encodePng img
+
+-- | This function will try to do anything to encode an image
+-- as a Tiff, make all color conversion and such. Equivalent
+-- of 'decodeImage' for Tiff encoding
+imageToTiff :: DynamicImage -> L.ByteString
+imageToTiff (ImageYCbCr8 img) = encodeTiff img
+imageToTiff (ImageCMYK8 img)  = encodeTiff img
+imageToTiff (ImageCMYK16 img) = encodeTiff img
+imageToTiff (ImageRGB8   img) = encodeTiff img
+imageToTiff (ImageRGBF   img) = encodeTiff $ toStandardDef img
+imageToTiff (ImageRGBA8  img) = encodeTiff img
+imageToTiff (ImageY8     img) = encodeTiff img
+imageToTiff (ImageYF     img) = encodeTiff $ greyScaleToStandardDef img
+imageToTiff (ImageYA8    img) = encodeTiff $ dropAlphaLayer img
+imageToTiff (ImageY16    img) = encodeTiff img
+imageToTiff (ImageY32    img) = encodeTiff img
+imageToTiff (ImageYA16   img) = encodeTiff $ dropAlphaLayer img
+imageToTiff (ImageRGB16  img) = encodeTiff img
+imageToTiff (ImageRGBA16 img) = encodeTiff img
+
+-- | This function will try to do anything to encode an image
+-- as bitmap, make all color conversion and such. Equivalent
+-- of 'decodeImage' for Bitmap encoding
+imageToBitmap :: DynamicImage -> L.ByteString
+imageToBitmap (ImageYCbCr8 img) = encodeBitmap (convertImage img :: Image PixelRGB8)
+imageToBitmap (ImageCMYK8  img) = encodeBitmap (convertImage img :: Image PixelRGB8)
+imageToBitmap (ImageCMYK16 img) = imageToBitmap . ImageRGB16 $ convertImage img
+imageToBitmap (ImageRGBF   img) = encodeBitmap $ toStandardDef img
+imageToBitmap (ImageRGB8   img) = encodeBitmap img
+imageToBitmap (ImageRGBA8  img) = encodeBitmap img
+imageToBitmap (ImageY8     img) = encodeBitmap img
+imageToBitmap (ImageYF     img) = encodeBitmap $ greyScaleToStandardDef img
+imageToBitmap (ImageYA8    img) = encodeBitmap (promoteImage img :: Image PixelRGBA8)
+imageToBitmap (ImageY16    img) = imageToBitmap . ImageY8 $ from16to8 img
+imageToBitmap (ImageY32    img) = imageToBitmap . ImageY8 $ from32to8 img
+imageToBitmap (ImageYA16   img) = imageToBitmap . ImageYA8 $ from16to8 img
+imageToBitmap (ImageRGB16  img) = imageToBitmap . ImageRGB8 $ from16to8 img
+imageToBitmap (ImageRGBA16 img) = imageToBitmap . ImageRGBA8 $ from16to8 img
+
+
+-- | This function will try to do anything to encode an image
+-- as a gif, make all color conversion and quantization. Equivalent
+-- of 'decodeImage' for gif encoding
+imageToGif :: DynamicImage -> Either String L.ByteString
+imageToGif (ImageYCbCr8 img) = imageToGif . ImageRGB8 $ convertImage img
+imageToGif (ImageCMYK8  img) = imageToGif . ImageRGB8 $ convertImage img
+imageToGif (ImageCMYK16 img) = imageToGif . ImageRGB16 $ convertImage img
+imageToGif (ImageRGBF   img) = imageToGif . ImageRGB8 $ toStandardDef img
+imageToGif (ImageRGB8   img) = encodeGifImageWithPalette indexed pal
+  where (indexed, pal) = palettize defaultPaletteOptions img
+imageToGif (ImageRGBA8  img) = imageToGif . ImageRGB8 $ dropAlphaLayer img
+imageToGif (ImageY8     img) = Right $ encodeGifImage img
+imageToGif (ImageYF     img) = imageToGif . ImageY8 $ greyScaleToStandardDef img
+imageToGif (ImageYA8    img) = imageToGif . ImageY8 $ dropAlphaLayer img
+imageToGif (ImageY16    img) = imageToGif . ImageY8 $ from16to8 img
+imageToGif (ImageY32    img) = imageToGif . ImageY8 $ from32to8 img
+imageToGif (ImageYA16   img) = imageToGif . ImageYA8 $ from16to8 img
+imageToGif (ImageRGB16  img) = imageToGif . ImageRGB8 $ from16to8 img
+imageToGif (ImageRGBA16 img) = imageToGif . ImageRGBA8 $ from16to8 img
+
+-- | This function will try to do anything to encode an image
+-- as a tga, make all color conversion and quantization. Equivalent
+-- of 'decodeImage' for tga encoding
+imageToTga :: DynamicImage -> L.ByteString
+imageToTga (ImageYCbCr8 img) = encodeTga (convertImage img :: Image PixelRGB8)
+imageToTga (ImageCMYK8  img) = encodeTga (convertImage img :: Image PixelRGB8)
+imageToTga (ImageCMYK16 img) = encodeTga (from16to8 img :: Image PixelRGB8)
+imageToTga (ImageRGBF   img) = encodeTga $ toStandardDef img
+imageToTga (ImageRGB8   img) = encodeTga img
+imageToTga (ImageRGBA8  img) = encodeTga img
+imageToTga (ImageY8     img) = encodeTga img
+imageToTga (ImageYF     img) = encodeTga $ greyScaleToStandardDef img
+imageToTga (ImageYA8    img) = encodeTga (promoteImage img :: Image PixelRGBA8)
+imageToTga (ImageY16    img) = encodeTga (from16to8 img :: Image Pixel8)
+imageToTga (ImageY32    img) = encodeTga (from32to8 img :: Image Pixel8)
+imageToTga (ImageYA16   img) = encodeTga (from16to8 img :: Image PixelRGBA8)
+imageToTga (ImageRGB16  img) = encodeTga (from16to8 img :: Image PixelRGB8)
+imageToTga (ImageRGBA16 img) = encodeTga (from16to8 img :: Image PixelRGBA8)
diff --git a/src/Codec/Picture/Tga.hs b/src/Codec/Picture/Tga.hs
--- a/src/Codec/Picture/Tga.hs
+++ b/src/Codec/Picture/Tga.hs
@@ -1,527 +1,527 @@
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE RankNTypes #-}
-{-# LANGUAGE BangPatterns #-}
-{-# LANGUAGE TupleSections #-}
-{-# LANGUAGE CPP #-}
--- | Module implementing function to read and write
--- Targa (*.tga) files.
-module Codec.Picture.Tga( decodeTga
-                        , decodeTgaWithMetadata
-                        , decodeTgaWithPaletteAndMetadata
-                        , TgaSaveable
-                        , encodeTga
-                        , writeTga
-                        )  where
-
-#if !MIN_VERSION_base(4,8,0)
-import Data.Monoid( mempty )
-import Control.Applicative( (<*>), pure, (<$>) )
-#endif
-
-import Control.Arrow( first )
-import Control.Monad.ST( ST, runST )
-import Data.Bits( (.&.)
-                , (.|.)
-                , bit
-                , testBit
-                , setBit
-                , unsafeShiftL
-                , unsafeShiftR )
-import Data.Word( Word8, Word16 )
-import Data.Binary( Binary( .. ), encode )
-import Data.Binary.Get( Get
-                      , getByteString 
-                      , getWord8
-                      , getWord16le
-                      )
-import Data.Binary.Put( putWord8
-                      , putWord16le
-                      , putByteString
-                      )
-
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as Lb
-import qualified Data.ByteString.Unsafe as U
-import qualified Data.Vector.Storable.Mutable as M
-
-import Codec.Picture.Types
-import Codec.Picture.InternalHelper
-import Codec.Picture.Metadata( Metadatas
-                             , SourceFormat( SourceTGA )
-                             , basicMetadata )
-import Codec.Picture.VectorByteConversion
-
-data TgaColorMapType
-  = ColorMapWithoutTable
-  | ColorMapWithTable
-  | ColorMapUnknown Word8
-
-instance Binary TgaColorMapType where
-  get = do
-    v <- getWord8
-    return $ case v of
-      0 -> ColorMapWithoutTable
-      1 -> ColorMapWithTable
-      n -> ColorMapUnknown n
-
-  put v = case v of
-    ColorMapWithoutTable -> putWord8 0
-    ColorMapWithTable -> putWord8 1
-    (ColorMapUnknown vv) -> putWord8 vv
-
-data TgaImageType
-  = ImageTypeNoData Bool
-  | ImageTypeColorMapped Bool
-  | ImageTypeTrueColor Bool
-  | ImageTypeMonochrome Bool
-
-isRleEncoded :: TgaImageType -> Bool
-isRleEncoded v = case v of
-  ImageTypeNoData      yn -> yn
-  ImageTypeColorMapped yn -> yn
-  ImageTypeTrueColor   yn -> yn
-  ImageTypeMonochrome  yn -> yn
-
-imageTypeOfCode :: Word8 -> Get TgaImageType
-imageTypeOfCode v = case v .&. 3 of
-    0 -> return $ ImageTypeNoData isEncoded
-    1 -> return $ ImageTypeColorMapped isEncoded
-    2 -> return $ ImageTypeTrueColor isEncoded
-    3 -> return $ ImageTypeMonochrome isEncoded
-    _ -> fail $ "Unknown TGA image type " ++ show v
-  where
-    isEncoded = testBit v 3
-
-codeOfImageType :: TgaImageType -> Word8
-codeOfImageType v = case v of
-    ImageTypeNoData encoded -> setVal 0 encoded
-    ImageTypeColorMapped encoded -> setVal 1 encoded
-    ImageTypeTrueColor encoded -> setVal 2 encoded
-    ImageTypeMonochrome encoded -> setVal 3 encoded
-    where
-      setVal vv True = setBit vv 3
-      setVal vv False = vv
-
-instance Binary TgaImageType where
-  get = getWord8 >>= imageTypeOfCode
-  put = putWord8 . codeOfImageType
-    
-data TgaImageDescription = TgaImageDescription
-  { _tgaIdXOrigin       :: Bool
-  , _tgaIdYOrigin       :: Bool
-  , _tgaIdAttributeBits :: Word8
-  }
-
-instance Binary TgaImageDescription where
-  put desc = putWord8 $ xOrig .|. yOrig .|. attr
-    where
-      xOrig | _tgaIdXOrigin desc = bit 4
-            | otherwise = 0
-
-      yOrig | not $ _tgaIdYOrigin desc = bit 5
-            | otherwise = 0
-      
-      attr = _tgaIdAttributeBits desc .&. 0xF
-
-  get = toDescr <$> getWord8 where
-    toDescr v = TgaImageDescription
-      { _tgaIdXOrigin       = testBit v 4
-      , _tgaIdYOrigin       = not $ testBit v 5
-      , _tgaIdAttributeBits = v .&. 0xF
-      }
-
-data TgaHeader = TgaHeader
-  { _tgaHdrIdLength         :: {-# UNPACK #-} !Word8
-  , _tgaHdrColorMapType     :: !TgaColorMapType
-  , _tgaHdrImageType        :: !TgaImageType
-  , _tgaHdrMapStart         :: {-# UNPACK #-} !Word16
-  , _tgaHdrMapLength        :: {-# UNPACK #-} !Word16
-  , _tgaHdrMapDepth         :: {-# UNPACK #-} !Word8
-  , _tgaHdrXOffset          :: {-# UNPACK #-} !Word16
-  , _tgaHdrYOffset          :: {-# UNPACK #-} !Word16
-  , _tgaHdrWidth            :: {-# UNPACK #-} !Word16
-  , _tgaHdrHeight           :: {-# UNPACK #-} !Word16
-  , _tgaHdrPixelDepth       :: {-# UNPACK #-} !Word8
-  , _tgaHdrImageDescription :: {-# UNPACK #-} !TgaImageDescription
-  }
-
-instance Binary TgaHeader where
-  get = TgaHeader
-     <$> g8 <*> get <*> get <*> g16 <*> g16 <*> g8
-     <*> g16 <*> g16 <*> g16 <*> g16 <*> g8 <*> get
-   where g16 = getWord16le
-         g8 = getWord8
-
-  put v = do
-    let p8 = putWord8
-        p16 = putWord16le
-    p8  $ _tgaHdrIdLength v
-    put $ _tgaHdrColorMapType v
-    put $ _tgaHdrImageType v
-
-    p16 $ _tgaHdrMapStart v
-    p16 $ _tgaHdrMapLength v
-    p8  $ _tgaHdrMapDepth v
-    p16 $ _tgaHdrXOffset v
-    p16 $ _tgaHdrYOffset v
-    p16 $ _tgaHdrWidth v
-    p16 $ _tgaHdrHeight v
-    p8  $ _tgaHdrPixelDepth v
-    put $ _tgaHdrImageDescription v
-
-
-data TgaFile = TgaFile
-  { _tgaFileHeader :: !TgaHeader
-  , _tgaFileId     :: !B.ByteString
-  , _tgaPalette    :: !B.ByteString
-  , _tgaFileRest   :: !B.ByteString
-  }
-
-getPalette :: TgaHeader -> Get B.ByteString
-getPalette hdr | _tgaHdrMapLength hdr <= 0 = return mempty
-getPalette hdr = getByteString $ bytePerPixel * pixelCount
-  where
-    bytePerPixel = fromIntegral $ _tgaHdrMapDepth hdr `div` 8
-    pixelCount = fromIntegral $ _tgaHdrMapLength hdr
-
-instance Binary TgaFile where
-  get = do
-    hdr <- get
-    validateTga hdr
-    fileId <- getByteString . fromIntegral $ _tgaHdrIdLength hdr
-    palette <- getPalette hdr
-    rest <- getRemainingBytes
-
-    return TgaFile {
-        _tgaFileHeader = hdr
-      , _tgaFileId = fileId
-      , _tgaPalette = palette
-      , _tgaFileRest = rest
-      }
-
-  put file = do
-    put $ _tgaFileHeader file
-    putByteString $ _tgaFileId file
-    putByteString $ _tgaPalette file
-    putByteString $ _tgaFileRest file
-
-data Depth8 = Depth8
-data Depth15 = Depth15
-data Depth24 = Depth24
-data Depth32 = Depth32
-
-class (Pixel (Unpacked a)) => TGAPixel a where
-   type Unpacked a
-   packedByteSize :: a -> Int
-   tgaUnpack      :: a -> B.ByteString -> Int -> Unpacked a
-
-instance TGAPixel Depth8 where
-   type Unpacked Depth8 = Pixel8
-   packedByteSize _ = 1
-   tgaUnpack _ = U.unsafeIndex
-
-instance TGAPixel Depth15 where
-   type Unpacked Depth15 = PixelRGBA8
-   packedByteSize _ = 2
-   tgaUnpack _ str ix = PixelRGBA8 r g b a
-      where
-        v0 = U.unsafeIndex str ix
-        v1 = U.unsafeIndex str $ ix + 1
-        r = (v1 .&. 0x7c) `unsafeShiftL` 1;
-        g = ((v1 .&. 0x03) `unsafeShiftL` 6) .|. ((v0 .&. 0xe0) `unsafeShiftR` 2);
-        b = (v0 .&. 0x1f) `unsafeShiftL` 3
-        a = 255 -- v1 .&. 0x80
-
-instance TGAPixel Depth24 where
-   type Unpacked Depth24 = PixelRGB8
-   packedByteSize _ = 3
-   tgaUnpack _ str ix = PixelRGB8 r g b
-     where
-       b = U.unsafeIndex str ix
-       g = U.unsafeIndex str (ix + 1)
-       r = U.unsafeIndex str (ix + 2)
-
-instance TGAPixel Depth32 where
-   type Unpacked Depth32 = PixelRGBA8
-   packedByteSize _ = 4
-   tgaUnpack _ str ix = PixelRGBA8 r g b a
-     where
-       b = U.unsafeIndex str ix
-       g = U.unsafeIndex str (ix + 1)
-       r = U.unsafeIndex str (ix + 2)
-       a = U.unsafeIndex str (ix + 3)
-
-prepareUnpacker :: TgaFile
-                -> (forall tgapx. (TGAPixel tgapx) => tgapx -> TgaFile -> Image (Unpacked tgapx))
-                -> Either String DynamicImage
-prepareUnpacker file f =
-  let hdr = _tgaFileHeader file
-      flipper :: (Pixel px) => Image px -> Image px
-      flipper = flipImage $ _tgaHdrImageDescription hdr
-  in
-  case _tgaHdrPixelDepth hdr of
-    8  -> pure . ImageY8 . flipper $ f Depth8 file
-    16 -> pure . ImageRGBA8 . flipper $ f Depth15 file
-    24 -> pure . ImageRGB8 . flipper $ f Depth24 file
-    32 -> pure . ImageRGBA8 . flipper $ f Depth32 file
-    n  -> Left $ "Invalid bit depth (" ++ show n ++ ")"
-
-toPaletted :: (Pixel px)
-           => (Image Pixel8 -> Palette' px -> PalettedImage) -> Image px
-           -> DynamicImage
-           -> Either String PalettedImage
-toPaletted f palette (ImageY8 img) = pure $ f img pal where
-  pal = Palette' 
-    { _paletteSize = imageWidth palette
-    , _paletteData = imageData palette
-    }
-toPaletted _ _ _ = Left "Bad colorspace for image"
-
-unparse :: TgaFile -> Either String (PalettedImage, Metadatas)
-unparse file =
-  let hdr = _tgaFileHeader file
-      imageType = _tgaHdrImageType hdr
-
-      unpacker :: forall tgapx. (TGAPixel tgapx)
-               => tgapx -> TgaFile -> Image (Unpacked tgapx)
-      unpacker | isRleEncoded imageType = unpackRLETga
-               | otherwise = unpackUncompressedTga
-
-      metas = basicMetadata SourceTGA (_tgaHdrWidth hdr) (_tgaHdrHeight hdr)
-      decodedPalette = unparse file
-        { _tgaFileHeader = hdr
-            { _tgaHdrHeight = 1
-            , _tgaHdrWidth = _tgaHdrMapLength hdr
-            , _tgaHdrPixelDepth = _tgaHdrMapDepth hdr
-            , _tgaHdrImageType = ImageTypeTrueColor False
-            }
-        , _tgaFileRest = _tgaPalette file
-        }
-  in
-  case imageType of
-    ImageTypeNoData _ -> Left "No data detected in TGA file"
-    ImageTypeTrueColor _ ->
-      fmap ((, metas) . TrueColorImage) $ prepareUnpacker file unpacker
-    ImageTypeMonochrome _ ->
-      fmap ((, metas) . TrueColorImage) $ prepareUnpacker file unpacker
-    ImageTypeColorMapped _ ->
-      case decodedPalette of
-        Left str -> Left str
-        Right (TrueColorImage (ImageY8 img), _) ->
-          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedY8 img
-        Right (TrueColorImage (ImageRGB8 img), _) ->
-          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedRGB8 img
-        Right (TrueColorImage (ImageRGBA8 img), _) ->
-          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedRGBA8 img
-        Right _ -> Left "Unknown pixel type"
-
-writeRun :: (Pixel px)
-         => M.STVector s (PixelBaseComponent px) -> Int -> px -> Int
-         -> ST s Int
-writeRun imgData localMaxi px = run
-  where
-    writeDelta = componentCount px
-    run writeIndex 
-      | writeIndex >= localMaxi = return writeIndex
-    run writeIndex = do
-      unsafeWritePixel imgData writeIndex px
-      run $ writeIndex + writeDelta
-
-copyData :: forall tgapx s
-          . (TGAPixel tgapx)
-         => tgapx
-         -> M.STVector s (PixelBaseComponent (Unpacked tgapx))
-         -> B.ByteString
-         -> Int -> Int
-         -> Int -> Int
-         -> ST s (Int, Int)
-copyData tgapx imgData readData maxi maxRead = go
-  where
-    readDelta = packedByteSize tgapx
-    writeDelta = componentCount (undefined :: Unpacked tgapx)
-
-    go writeIndex readIndex
-      | writeIndex >= maxi ||
-        readIndex >= maxRead = return (writeIndex, readIndex)
-    go writeIndex readIndex = do
-      let px = tgaUnpack tgapx readData readIndex :: Unpacked tgapx
-      unsafeWritePixel imgData writeIndex px
-      go (writeIndex + writeDelta) (readIndex + readDelta)
-
-unpackUncompressedTga :: forall tgapx
-                       . (TGAPixel tgapx)
-                      => tgapx -- ^ Type witness
-                      -> TgaFile
-                      -> Image (Unpacked tgapx)
-unpackUncompressedTga tga file = runST $ do
-    img <- MutableImage width height <$> M.new maxi
-    let imgData = mutableImageData img
-    _ <- copyData tga imgData readData maxi maxRead 0 0
-    unsafeFreezeImage img
-
-  where
-    hdr = _tgaFileHeader file
-    width = fromIntegral $ _tgaHdrWidth hdr
-    height = fromIntegral $ _tgaHdrHeight hdr
-    readData = _tgaFileRest file
-    compCount = componentCount (undefined :: Unpacked tgapx)
-    maxi = width * height * compCount
-    maxRead = B.length readData
-
-isRleChunk :: Word8 -> Bool
-isRleChunk v = testBit v 7
-
-runLength :: Word8 -> Int
-runLength v = fromIntegral (v .&. 0x7F) + 1
-
-unpackRLETga :: forall tgapx
-              . (TGAPixel tgapx)
-             => tgapx -- ^ Type witness
-             -> TgaFile
-             -> Image (Unpacked tgapx)
-unpackRLETga tga file = runST $ do
-    img <- MutableImage width height <$> M.new maxi
-    let imgData = mutableImageData img
-
-        go writeIndex readIndex
-            | writeIndex >= maxi = return () 
-            | readIndex >= maxRead = return ()
-        go writeIndex readIndex = do
-          let code = U.unsafeIndex readData readIndex
-              copyMax = min maxi $ writeIndex + runLength code * compCount
-          
-          if isRleChunk code then do
-            let px = tgaUnpack tga readData (readIndex + 1) :: Unpacked tgapx
-            lastWriteIndex <- writeRun imgData copyMax px writeIndex
-            go lastWriteIndex $ readIndex + 1 + readDelta
-
-          else do
-            (newWrite, newRead) <-
-                copyData tga imgData readData copyMax maxRead
-                    writeIndex (readIndex + 1)
-            go newWrite newRead
-
-    go 0 0
-    unsafeFreezeImage img
-
-  where
-    hdr = _tgaFileHeader file
-    width = fromIntegral $ _tgaHdrWidth hdr
-    height = fromIntegral $ _tgaHdrHeight hdr
-    readData = _tgaFileRest file
-    compCount = componentCount (undefined :: Unpacked tgapx)
-    maxi = width * height * compCount
-    maxRead = B.length readData
-    readDelta = packedByteSize tga
-
-flipImage :: (Pixel px)
-          => TgaImageDescription -> Image px -> Image px
-flipImage desc img
-    | xFlip && yFlip =
-        generateImage (\x y -> pixelAt img (wMax - x) (hMax - y)) w h
-    | xFlip =
-        generateImage (\x y -> pixelAt img (wMax - x) y) w h
-    | yFlip =
-        generateImage (\x y -> pixelAt img x (hMax - y)) w h
-    | otherwise = img
-  where
-    xFlip = _tgaIdXOrigin desc
-    yFlip = _tgaIdYOrigin desc
-    w = imageWidth img
-    h = imageHeight img
-
-    !wMax = w - 1
-    !hMax = h - 1
-
-validateTga :: TgaHeader -> Get ()
-validateTga hdr
-    | _tgaHdrWidth hdr <= 0 = fail "Width is null or negative"
-    | _tgaHdrHeight hdr <= 0 = fail "Height is null or negative"
-validateTga _ = return ()
-
--- | Transform a raw tga image to an image, without modifying
--- the underlying pixel type.
---
--- This function can output the following images:
---
---  * 'ImageY8'
---
---  * 'ImageRGB8'
---
---  * 'ImageRGBA8'
---
-decodeTga :: B.ByteString -> Either String DynamicImage
-decodeTga byte = fst <$> decodeTgaWithMetadata byte
-
--- | Equivalent to decodeTga but also provide metadata
-decodeTgaWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
-decodeTgaWithMetadata byte = first palettedToTrueColor <$> decodeTgaWithPaletteAndMetadata byte
-
--- | Equivalent to decodeTga but with metdata and palette if any
-decodeTgaWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
-decodeTgaWithPaletteAndMetadata byte = runGetStrict get byte >>= unparse
-
--- | This typeclass determine if a pixel can be saved in the
--- TGA format.
-class TgaSaveable a where
-    tgaDataOfImage :: Image a -> B.ByteString
-    tgaPixelDepthOfImage :: Image a -> Word8
-    tgaTypeOfImage :: Image a -> TgaImageType
-
-instance TgaSaveable Pixel8 where
-    tgaDataOfImage = toByteString . imageData
-    tgaPixelDepthOfImage _ = 8
-    tgaTypeOfImage _ = ImageTypeMonochrome False
-
-instance TgaSaveable PixelRGB8 where
-    tgaPixelDepthOfImage _ = 24
-    tgaTypeOfImage _ = ImageTypeTrueColor False
-    tgaDataOfImage = toByteString . imageData . pixelMap flipRgb
-      where
-        flipRgb (PixelRGB8 r g b) = PixelRGB8 b g r
-
-instance TgaSaveable PixelRGBA8 where
-    tgaPixelDepthOfImage _ = 32
-    tgaTypeOfImage _ = ImageTypeTrueColor False
-    tgaDataOfImage = toByteString . imageData . pixelMap flipRgba
-      where
-        flipRgba (PixelRGBA8 r g b a) = PixelRGBA8 b g r a
-
--- | Helper function to directly write an image a tga on disk.
-writeTga :: (TgaSaveable pixel) => FilePath -> Image pixel -> IO ()
-writeTga path img = Lb.writeFile path $ encodeTga img
-
--- | Transform a compatible image to a raw bytestring
--- representing a Targa file.
-encodeTga :: (TgaSaveable px) => Image px -> Lb.ByteString
-encodeTga img = encode file
-  where
-    file = TgaFile
-      { _tgaFileHeader = TgaHeader
-            { _tgaHdrIdLength         = 0
-            , _tgaHdrColorMapType     = ColorMapWithoutTable
-            , _tgaHdrImageType        = tgaTypeOfImage img
-            , _tgaHdrMapStart         = 0
-            , _tgaHdrMapLength        = 0
-            , _tgaHdrMapDepth         = 0
-            , _tgaHdrXOffset          = 0
-            , _tgaHdrYOffset          = 0
-            , _tgaHdrWidth            = fromIntegral $ imageWidth img
-            , _tgaHdrHeight           = fromIntegral $ imageHeight img
-            , _tgaHdrPixelDepth       = tgaPixelDepthOfImage img
-            , _tgaHdrImageDescription = TgaImageDescription
-                    { _tgaIdXOrigin       = False
-                    , _tgaIdYOrigin       = False
-                    , _tgaIdAttributeBits = 0
-                    }
-            }
-      , _tgaFileId     = mempty
-      , _tgaPalette    = mempty
-      , _tgaFileRest   = tgaDataOfImage img
-      }
-
-{-# ANN module "HLint: ignore Reduce duplication" #-}
-
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE CPP #-}
+-- | Module implementing function to read and write
+-- Targa (*.tga) files.
+module Codec.Picture.Tga( decodeTga
+                        , decodeTgaWithMetadata
+                        , decodeTgaWithPaletteAndMetadata
+                        , TgaSaveable
+                        , encodeTga
+                        , writeTga
+                        )  where
+
+#if !MIN_VERSION_base(4,8,0)
+import Data.Monoid( mempty )
+import Control.Applicative( (<*>), pure, (<$>) )
+#endif
+
+import Control.Arrow( first )
+import Control.Monad.ST( ST, runST )
+import Data.Bits( (.&.)
+                , (.|.)
+                , bit
+                , testBit
+                , setBit
+                , unsafeShiftL
+                , unsafeShiftR )
+import Data.Word( Word8, Word16 )
+import Data.Binary( Binary( .. ), encode )
+import Data.Binary.Get( Get
+                      , getByteString 
+                      , getWord8
+                      , getWord16le
+                      )
+import Data.Binary.Put( putWord8
+                      , putWord16le
+                      , putByteString
+                      )
+
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as Lb
+import qualified Data.ByteString.Unsafe as U
+import qualified Data.Vector.Storable.Mutable as M
+
+import Codec.Picture.Types
+import Codec.Picture.InternalHelper
+import Codec.Picture.Metadata( Metadatas
+                             , SourceFormat( SourceTGA )
+                             , basicMetadata )
+import Codec.Picture.VectorByteConversion
+
+data TgaColorMapType
+  = ColorMapWithoutTable
+  | ColorMapWithTable
+  | ColorMapUnknown Word8
+
+instance Binary TgaColorMapType where
+  get = do
+    v <- getWord8
+    return $ case v of
+      0 -> ColorMapWithoutTable
+      1 -> ColorMapWithTable
+      n -> ColorMapUnknown n
+
+  put v = case v of
+    ColorMapWithoutTable -> putWord8 0
+    ColorMapWithTable -> putWord8 1
+    (ColorMapUnknown vv) -> putWord8 vv
+
+data TgaImageType
+  = ImageTypeNoData Bool
+  | ImageTypeColorMapped Bool
+  | ImageTypeTrueColor Bool
+  | ImageTypeMonochrome Bool
+
+isRleEncoded :: TgaImageType -> Bool
+isRleEncoded v = case v of
+  ImageTypeNoData      yn -> yn
+  ImageTypeColorMapped yn -> yn
+  ImageTypeTrueColor   yn -> yn
+  ImageTypeMonochrome  yn -> yn
+
+imageTypeOfCode :: Word8 -> Get TgaImageType
+imageTypeOfCode v = case v .&. 3 of
+    0 -> return $ ImageTypeNoData isEncoded
+    1 -> return $ ImageTypeColorMapped isEncoded
+    2 -> return $ ImageTypeTrueColor isEncoded
+    3 -> return $ ImageTypeMonochrome isEncoded
+    _ -> fail $ "Unknown TGA image type " ++ show v
+  where
+    isEncoded = testBit v 3
+
+codeOfImageType :: TgaImageType -> Word8
+codeOfImageType v = case v of
+    ImageTypeNoData encoded -> setVal 0 encoded
+    ImageTypeColorMapped encoded -> setVal 1 encoded
+    ImageTypeTrueColor encoded -> setVal 2 encoded
+    ImageTypeMonochrome encoded -> setVal 3 encoded
+    where
+      setVal vv True = setBit vv 3
+      setVal vv False = vv
+
+instance Binary TgaImageType where
+  get = getWord8 >>= imageTypeOfCode
+  put = putWord8 . codeOfImageType
+    
+data TgaImageDescription = TgaImageDescription
+  { _tgaIdXOrigin       :: Bool
+  , _tgaIdYOrigin       :: Bool
+  , _tgaIdAttributeBits :: Word8
+  }
+
+instance Binary TgaImageDescription where
+  put desc = putWord8 $ xOrig .|. yOrig .|. attr
+    where
+      xOrig | _tgaIdXOrigin desc = bit 4
+            | otherwise = 0
+
+      yOrig | not $ _tgaIdYOrigin desc = bit 5
+            | otherwise = 0
+      
+      attr = _tgaIdAttributeBits desc .&. 0xF
+
+  get = toDescr <$> getWord8 where
+    toDescr v = TgaImageDescription
+      { _tgaIdXOrigin       = testBit v 4
+      , _tgaIdYOrigin       = not $ testBit v 5
+      , _tgaIdAttributeBits = v .&. 0xF
+      }
+
+data TgaHeader = TgaHeader
+  { _tgaHdrIdLength         :: {-# UNPACK #-} !Word8
+  , _tgaHdrColorMapType     :: !TgaColorMapType
+  , _tgaHdrImageType        :: !TgaImageType
+  , _tgaHdrMapStart         :: {-# UNPACK #-} !Word16
+  , _tgaHdrMapLength        :: {-# UNPACK #-} !Word16
+  , _tgaHdrMapDepth         :: {-# UNPACK #-} !Word8
+  , _tgaHdrXOffset          :: {-# UNPACK #-} !Word16
+  , _tgaHdrYOffset          :: {-# UNPACK #-} !Word16
+  , _tgaHdrWidth            :: {-# UNPACK #-} !Word16
+  , _tgaHdrHeight           :: {-# UNPACK #-} !Word16
+  , _tgaHdrPixelDepth       :: {-# UNPACK #-} !Word8
+  , _tgaHdrImageDescription :: {-# UNPACK #-} !TgaImageDescription
+  }
+
+instance Binary TgaHeader where
+  get = TgaHeader
+     <$> g8 <*> get <*> get <*> g16 <*> g16 <*> g8
+     <*> g16 <*> g16 <*> g16 <*> g16 <*> g8 <*> get
+   where g16 = getWord16le
+         g8 = getWord8
+
+  put v = do
+    let p8 = putWord8
+        p16 = putWord16le
+    p8  $ _tgaHdrIdLength v
+    put $ _tgaHdrColorMapType v
+    put $ _tgaHdrImageType v
+
+    p16 $ _tgaHdrMapStart v
+    p16 $ _tgaHdrMapLength v
+    p8  $ _tgaHdrMapDepth v
+    p16 $ _tgaHdrXOffset v
+    p16 $ _tgaHdrYOffset v
+    p16 $ _tgaHdrWidth v
+    p16 $ _tgaHdrHeight v
+    p8  $ _tgaHdrPixelDepth v
+    put $ _tgaHdrImageDescription v
+
+
+data TgaFile = TgaFile
+  { _tgaFileHeader :: !TgaHeader
+  , _tgaFileId     :: !B.ByteString
+  , _tgaPalette    :: !B.ByteString
+  , _tgaFileRest   :: !B.ByteString
+  }
+
+getPalette :: TgaHeader -> Get B.ByteString
+getPalette hdr | _tgaHdrMapLength hdr <= 0 = return mempty
+getPalette hdr = getByteString $ bytePerPixel * pixelCount
+  where
+    bytePerPixel = fromIntegral $ _tgaHdrMapDepth hdr `div` 8
+    pixelCount = fromIntegral $ _tgaHdrMapLength hdr
+
+instance Binary TgaFile where
+  get = do
+    hdr <- get
+    validateTga hdr
+    fileId <- getByteString . fromIntegral $ _tgaHdrIdLength hdr
+    palette <- getPalette hdr
+    rest <- getRemainingBytes
+
+    return TgaFile {
+        _tgaFileHeader = hdr
+      , _tgaFileId = fileId
+      , _tgaPalette = palette
+      , _tgaFileRest = rest
+      }
+
+  put file = do
+    put $ _tgaFileHeader file
+    putByteString $ _tgaFileId file
+    putByteString $ _tgaPalette file
+    putByteString $ _tgaFileRest file
+
+data Depth8 = Depth8
+data Depth15 = Depth15
+data Depth24 = Depth24
+data Depth32 = Depth32
+
+class (Pixel (Unpacked a)) => TGAPixel a where
+   type Unpacked a
+   packedByteSize :: a -> Int
+   tgaUnpack      :: a -> B.ByteString -> Int -> Unpacked a
+
+instance TGAPixel Depth8 where
+   type Unpacked Depth8 = Pixel8
+   packedByteSize _ = 1
+   tgaUnpack _ = U.unsafeIndex
+
+instance TGAPixel Depth15 where
+   type Unpacked Depth15 = PixelRGBA8
+   packedByteSize _ = 2
+   tgaUnpack _ str ix = PixelRGBA8 r g b a
+      where
+        v0 = U.unsafeIndex str ix
+        v1 = U.unsafeIndex str $ ix + 1
+        r = (v1 .&. 0x7c) `unsafeShiftL` 1;
+        g = ((v1 .&. 0x03) `unsafeShiftL` 6) .|. ((v0 .&. 0xe0) `unsafeShiftR` 2);
+        b = (v0 .&. 0x1f) `unsafeShiftL` 3
+        a = 255 -- v1 .&. 0x80
+
+instance TGAPixel Depth24 where
+   type Unpacked Depth24 = PixelRGB8
+   packedByteSize _ = 3
+   tgaUnpack _ str ix = PixelRGB8 r g b
+     where
+       b = U.unsafeIndex str ix
+       g = U.unsafeIndex str (ix + 1)
+       r = U.unsafeIndex str (ix + 2)
+
+instance TGAPixel Depth32 where
+   type Unpacked Depth32 = PixelRGBA8
+   packedByteSize _ = 4
+   tgaUnpack _ str ix = PixelRGBA8 r g b a
+     where
+       b = U.unsafeIndex str ix
+       g = U.unsafeIndex str (ix + 1)
+       r = U.unsafeIndex str (ix + 2)
+       a = U.unsafeIndex str (ix + 3)
+
+prepareUnpacker :: TgaFile
+                -> (forall tgapx. (TGAPixel tgapx) => tgapx -> TgaFile -> Image (Unpacked tgapx))
+                -> Either String DynamicImage
+prepareUnpacker file f =
+  let hdr = _tgaFileHeader file
+      flipper :: (Pixel px) => Image px -> Image px
+      flipper = flipImage $ _tgaHdrImageDescription hdr
+  in
+  case _tgaHdrPixelDepth hdr of
+    8  -> pure . ImageY8 . flipper $ f Depth8 file
+    16 -> pure . ImageRGBA8 . flipper $ f Depth15 file
+    24 -> pure . ImageRGB8 . flipper $ f Depth24 file
+    32 -> pure . ImageRGBA8 . flipper $ f Depth32 file
+    n  -> Left $ "Invalid bit depth (" ++ show n ++ ")"
+
+toPaletted :: (Pixel px)
+           => (Image Pixel8 -> Palette' px -> PalettedImage) -> Image px
+           -> DynamicImage
+           -> Either String PalettedImage
+toPaletted f palette (ImageY8 img) = pure $ f img pal where
+  pal = Palette' 
+    { _paletteSize = imageWidth palette
+    , _paletteData = imageData palette
+    }
+toPaletted _ _ _ = Left "Bad colorspace for image"
+
+unparse :: TgaFile -> Either String (PalettedImage, Metadatas)
+unparse file =
+  let hdr = _tgaFileHeader file
+      imageType = _tgaHdrImageType hdr
+
+      unpacker :: forall tgapx. (TGAPixel tgapx)
+               => tgapx -> TgaFile -> Image (Unpacked tgapx)
+      unpacker | isRleEncoded imageType = unpackRLETga
+               | otherwise = unpackUncompressedTga
+
+      metas = basicMetadata SourceTGA (_tgaHdrWidth hdr) (_tgaHdrHeight hdr)
+      decodedPalette = unparse file
+        { _tgaFileHeader = hdr
+            { _tgaHdrHeight = 1
+            , _tgaHdrWidth = _tgaHdrMapLength hdr
+            , _tgaHdrPixelDepth = _tgaHdrMapDepth hdr
+            , _tgaHdrImageType = ImageTypeTrueColor False
+            }
+        , _tgaFileRest = _tgaPalette file
+        }
+  in
+  case imageType of
+    ImageTypeNoData _ -> Left "No data detected in TGA file"
+    ImageTypeTrueColor _ ->
+      fmap ((, metas) . TrueColorImage) $ prepareUnpacker file unpacker
+    ImageTypeMonochrome _ ->
+      fmap ((, metas) . TrueColorImage) $ prepareUnpacker file unpacker
+    ImageTypeColorMapped _ ->
+      case decodedPalette of
+        Left str -> Left str
+        Right (TrueColorImage (ImageY8 img), _) ->
+          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedY8 img
+        Right (TrueColorImage (ImageRGB8 img), _) ->
+          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedRGB8 img
+        Right (TrueColorImage (ImageRGBA8 img), _) ->
+          fmap (, metas) $ prepareUnpacker file unpacker >>= toPaletted PalettedRGBA8 img
+        Right _ -> Left "Unknown pixel type"
+
+writeRun :: (Pixel px)
+         => M.STVector s (PixelBaseComponent px) -> Int -> px -> Int
+         -> ST s Int
+writeRun imgData localMaxi px = run
+  where
+    writeDelta = componentCount px
+    run writeIndex 
+      | writeIndex >= localMaxi = return writeIndex
+    run writeIndex = do
+      unsafeWritePixel imgData writeIndex px
+      run $ writeIndex + writeDelta
+
+copyData :: forall tgapx s
+          . (TGAPixel tgapx)
+         => tgapx
+         -> M.STVector s (PixelBaseComponent (Unpacked tgapx))
+         -> B.ByteString
+         -> Int -> Int
+         -> Int -> Int
+         -> ST s (Int, Int)
+copyData tgapx imgData readData maxi maxRead = go
+  where
+    readDelta = packedByteSize tgapx
+    writeDelta = componentCount (undefined :: Unpacked tgapx)
+
+    go writeIndex readIndex
+      | writeIndex >= maxi ||
+        readIndex >= maxRead = return (writeIndex, readIndex)
+    go writeIndex readIndex = do
+      let px = tgaUnpack tgapx readData readIndex :: Unpacked tgapx
+      unsafeWritePixel imgData writeIndex px
+      go (writeIndex + writeDelta) (readIndex + readDelta)
+
+unpackUncompressedTga :: forall tgapx
+                       . (TGAPixel tgapx)
+                      => tgapx -- ^ Type witness
+                      -> TgaFile
+                      -> Image (Unpacked tgapx)
+unpackUncompressedTga tga file = runST $ do
+    img <- MutableImage width height <$> M.new maxi
+    let imgData = mutableImageData img
+    _ <- copyData tga imgData readData maxi maxRead 0 0
+    unsafeFreezeImage img
+
+  where
+    hdr = _tgaFileHeader file
+    width = fromIntegral $ _tgaHdrWidth hdr
+    height = fromIntegral $ _tgaHdrHeight hdr
+    readData = _tgaFileRest file
+    compCount = componentCount (undefined :: Unpacked tgapx)
+    maxi = width * height * compCount
+    maxRead = B.length readData
+
+isRleChunk :: Word8 -> Bool
+isRleChunk v = testBit v 7
+
+runLength :: Word8 -> Int
+runLength v = fromIntegral (v .&. 0x7F) + 1
+
+unpackRLETga :: forall tgapx
+              . (TGAPixel tgapx)
+             => tgapx -- ^ Type witness
+             -> TgaFile
+             -> Image (Unpacked tgapx)
+unpackRLETga tga file = runST $ do
+    img <- MutableImage width height <$> M.new maxi
+    let imgData = mutableImageData img
+
+        go writeIndex readIndex
+            | writeIndex >= maxi = return () 
+            | readIndex >= maxRead = return ()
+        go writeIndex readIndex = do
+          let code = U.unsafeIndex readData readIndex
+              copyMax = min maxi $ writeIndex + runLength code * compCount
+          
+          if isRleChunk code then do
+            let px = tgaUnpack tga readData (readIndex + 1) :: Unpacked tgapx
+            lastWriteIndex <- writeRun imgData copyMax px writeIndex
+            go lastWriteIndex $ readIndex + 1 + readDelta
+
+          else do
+            (newWrite, newRead) <-
+                copyData tga imgData readData copyMax maxRead
+                    writeIndex (readIndex + 1)
+            go newWrite newRead
+
+    go 0 0
+    unsafeFreezeImage img
+
+  where
+    hdr = _tgaFileHeader file
+    width = fromIntegral $ _tgaHdrWidth hdr
+    height = fromIntegral $ _tgaHdrHeight hdr
+    readData = _tgaFileRest file
+    compCount = componentCount (undefined :: Unpacked tgapx)
+    maxi = width * height * compCount
+    maxRead = B.length readData
+    readDelta = packedByteSize tga
+
+flipImage :: (Pixel px)
+          => TgaImageDescription -> Image px -> Image px
+flipImage desc img
+    | xFlip && yFlip =
+        generateImage (\x y -> pixelAt img (wMax - x) (hMax - y)) w h
+    | xFlip =
+        generateImage (\x y -> pixelAt img (wMax - x) y) w h
+    | yFlip =
+        generateImage (\x y -> pixelAt img x (hMax - y)) w h
+    | otherwise = img
+  where
+    xFlip = _tgaIdXOrigin desc
+    yFlip = _tgaIdYOrigin desc
+    w = imageWidth img
+    h = imageHeight img
+
+    !wMax = w - 1
+    !hMax = h - 1
+
+validateTga :: TgaHeader -> Get ()
+validateTga hdr
+    | _tgaHdrWidth hdr <= 0 = fail "Width is null or negative"
+    | _tgaHdrHeight hdr <= 0 = fail "Height is null or negative"
+validateTga _ = return ()
+
+-- | Transform a raw tga image to an image, without modifying
+-- the underlying pixel type.
+--
+-- This function can output the following images:
+--
+--  * 'ImageY8'
+--
+--  * 'ImageRGB8'
+--
+--  * 'ImageRGBA8'
+--
+decodeTga :: B.ByteString -> Either String DynamicImage
+decodeTga byte = fst <$> decodeTgaWithMetadata byte
+
+-- | Equivalent to decodeTga but also provide metadata
+decodeTgaWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
+decodeTgaWithMetadata byte = first palettedToTrueColor <$> decodeTgaWithPaletteAndMetadata byte
+
+-- | Equivalent to decodeTga but with metadata and palette if any
+decodeTgaWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
+decodeTgaWithPaletteAndMetadata byte = runGetStrict get byte >>= unparse
+
+-- | This typeclass determine if a pixel can be saved in the
+-- TGA format.
+class TgaSaveable a where
+    tgaDataOfImage :: Image a -> B.ByteString
+    tgaPixelDepthOfImage :: Image a -> Word8
+    tgaTypeOfImage :: Image a -> TgaImageType
+
+instance TgaSaveable Pixel8 where
+    tgaDataOfImage = toByteString . imageData
+    tgaPixelDepthOfImage _ = 8
+    tgaTypeOfImage _ = ImageTypeMonochrome False
+
+instance TgaSaveable PixelRGB8 where
+    tgaPixelDepthOfImage _ = 24
+    tgaTypeOfImage _ = ImageTypeTrueColor False
+    tgaDataOfImage = toByteString . imageData . pixelMap flipRgb
+      where
+        flipRgb (PixelRGB8 r g b) = PixelRGB8 b g r
+
+instance TgaSaveable PixelRGBA8 where
+    tgaPixelDepthOfImage _ = 32
+    tgaTypeOfImage _ = ImageTypeTrueColor False
+    tgaDataOfImage = toByteString . imageData . pixelMap flipRgba
+      where
+        flipRgba (PixelRGBA8 r g b a) = PixelRGBA8 b g r a
+
+-- | Helper function to directly write an image a tga on disk.
+writeTga :: (TgaSaveable pixel) => FilePath -> Image pixel -> IO ()
+writeTga path img = Lb.writeFile path $ encodeTga img
+
+-- | Transform a compatible image to a raw bytestring
+-- representing a Targa file.
+encodeTga :: (TgaSaveable px) => Image px -> Lb.ByteString
+encodeTga img = encode file
+  where
+    file = TgaFile
+      { _tgaFileHeader = TgaHeader
+            { _tgaHdrIdLength         = 0
+            , _tgaHdrColorMapType     = ColorMapWithoutTable
+            , _tgaHdrImageType        = tgaTypeOfImage img
+            , _tgaHdrMapStart         = 0
+            , _tgaHdrMapLength        = 0
+            , _tgaHdrMapDepth         = 0
+            , _tgaHdrXOffset          = 0
+            , _tgaHdrYOffset          = 0
+            , _tgaHdrWidth            = fromIntegral $ imageWidth img
+            , _tgaHdrHeight           = fromIntegral $ imageHeight img
+            , _tgaHdrPixelDepth       = tgaPixelDepthOfImage img
+            , _tgaHdrImageDescription = TgaImageDescription
+                    { _tgaIdXOrigin       = False
+                    , _tgaIdYOrigin       = False
+                    , _tgaIdAttributeBits = 0
+                    }
+            }
+      , _tgaFileId     = mempty
+      , _tgaPalette    = mempty
+      , _tgaFileRest   = tgaDataOfImage img
+      }
+
+{-# ANN module "HLint: ignore Reduce duplication" #-}
+
diff --git a/src/Codec/Picture/Tiff.hs b/src/Codec/Picture/Tiff.hs
--- a/src/Codec/Picture/Tiff.hs
+++ b/src/Codec/Picture/Tiff.hs
@@ -1,941 +1,946 @@
-{-# LANGUAGE TupleSections #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE InstanceSigs #-}
-{-# LANGUAGE CPP #-}
--- | Module implementing TIFF decoding.
---
--- Supported compression schemes:
---
---   * Uncompressed
---
---   * PackBits
---
---   * LZW
---
--- Supported bit depth:
---
---   * 2 bits
---
---   * 4 bits
---
---   * 8 bits
---
---   * 16 bits
---
-module Codec.Picture.Tiff( decodeTiff
-                         , decodeTiffWithMetadata
-                         , decodeTiffWithPaletteAndMetadata
-                         , TiffSaveable
-                         , encodeTiff
-                         , writeTiff
-                         ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>), (<*>), pure )
-import Data.Monoid( mempty )
-#endif
-
-import Control.Arrow( first )
-import Control.Monad( when, foldM_, unless, forM_ )
-import Control.Monad.ST( ST, runST )
-import Control.Monad.Writer.Strict( execWriter, tell, Writer )
-import Data.Int( Int8 )
-import Data.Word( Word8, Word16, Word32 )
-import Data.Bits( (.&.), (.|.), unsafeShiftL, unsafeShiftR )
-import Data.Binary.Get( Get )
-import Data.Binary.Put( runPut )
-
-import qualified Data.Vector as V
-import qualified Data.Vector.Storable as VS
-import qualified Data.Vector.Storable.Mutable as M
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy as Lb
-import qualified Data.ByteString.Unsafe as BU
-
-import Foreign.Storable( sizeOf )
-
-import Codec.Picture.Metadata.Exif
-import Codec.Picture.Metadata( Metadatas )
-import Codec.Picture.InternalHelper
-import Codec.Picture.BitWriter
-import Codec.Picture.Types
-import Codec.Picture.Gif.Internal.LZW
-import Codec.Picture.Tiff.Internal.Types
-import Codec.Picture.Tiff.Internal.Metadata
-import Codec.Picture.VectorByteConversion( toByteString )
-
-data TiffInfo = TiffInfo
-  { tiffHeader             :: TiffHeader
-  , tiffWidth              :: Word32
-  , tiffHeight             :: Word32
-  , tiffColorspace         :: TiffColorspace
-  , tiffSampleCount        :: Word32
-  , tiffRowPerStrip        :: Word32
-  , tiffPlaneConfiguration :: TiffPlanarConfiguration
-  , tiffSampleFormat       :: [TiffSampleFormat]
-  , tiffBitsPerSample      :: V.Vector Word32
-  , tiffCompression        :: TiffCompression
-  , tiffStripSize          :: V.Vector Word32
-  , tiffOffsets            :: V.Vector Word32
-  , tiffPalette            :: Maybe (Image PixelRGB16)
-  , tiffYCbCrSubsampling   :: V.Vector Word32
-  , tiffExtraSample        :: Maybe ExtraSample
-  , tiffPredictor          :: Predictor
-  , tiffMetadatas          :: Metadatas
-  }
-
-unLong :: String -> ExifData -> Get (V.Vector Word32)
-unLong _ (ExifLong v)   = pure $ V.singleton v
-unLong _ (ExifShort v)  = pure $ V.singleton (fromIntegral v)
-unLong _ (ExifShorts v) = pure $ V.map fromIntegral v
-unLong _ (ExifLongs v) = pure v
-unLong errMessage _ = fail errMessage
-
-findIFD :: String -> ExifTag -> [ImageFileDirectory]
-        -> Get ImageFileDirectory
-findIFD errorMessage tag lst =
-  case [v | v <- lst, ifdIdentifier v == tag] of
-    [] -> fail errorMessage
-    (x:_) -> pure x
-
-findPalette :: [ImageFileDirectory] -> Get (Maybe (Image PixelRGB16))
-findPalette ifds =
-    case [v | v <- ifds, ifdIdentifier v == TagColorMap] of
-        (ImageFileDirectory { ifdExtended = ExifShorts vec }:_) ->
-            pure . Just . Image pixelCount 1 $ VS.generate (V.length vec) axx
-                where pixelCount = V.length vec `div` 3
-                      axx v = vec `V.unsafeIndex` (idx + color * pixelCount)
-                          where (idx, color) = v `divMod` 3
-
-        _ -> pure Nothing
-
-findIFDData :: String -> ExifTag -> [ImageFileDirectory] -> Get Word32
-findIFDData msg tag lst = ifdOffset <$> findIFD msg tag lst
-
-findIFDDefaultData :: Word32 -> ExifTag -> [ImageFileDirectory] -> Get Word32
-findIFDDefaultData d tag lst =
-    case [v | v <- lst, ifdIdentifier v == tag] of
-        [] -> pure d
-        (x:_) -> pure $ ifdOffset x
-
-findIFDExt :: String -> ExifTag -> [ImageFileDirectory] -> Get ExifData
-findIFDExt msg tag lst = do
-    val <- findIFD msg tag lst
-    case val of
-      ImageFileDirectory
-        { ifdCount = 1, ifdOffset = ofs, ifdType = TypeShort } ->
-               pure . ExifShorts . V.singleton $ fromIntegral ofs
-      ImageFileDirectory
-        { ifdCount = 1, ifdOffset = ofs, ifdType = TypeLong } ->
-               pure . ExifLongs  . V.singleton $ fromIntegral ofs
-      ImageFileDirectory { ifdExtended = v } -> pure v
-
-
-findIFDExtDefaultData :: [Word32] -> ExifTag -> [ImageFileDirectory]
-                      -> Get [Word32]
-findIFDExtDefaultData d tag lst =
-    case [v | v <- lst, ifdIdentifier v == tag] of
-        [] -> pure d
-        (ImageFileDirectory { ifdExtended = ExifNone }:_) -> return d
-        (x:_) -> V.toList <$> unLong errorMessage (ifdExtended x)
-            where errorMessage =
-                    "Can't parse tag " ++ show tag ++ " " ++ show (ifdExtended x)
-
--- It's temporary, remove once tiff decoding is better
--- handled.
-{-  
-instance Show (Image PixelRGB16) where
-    show _ = "Image PixelRGB16"
--}
-copyByteString :: B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32)
-               -> ST s Int
-copyByteString str vec stride startWrite (from, count) = inner startWrite fromi
-  where fromi = fromIntegral from
-        maxi = fromi + fromIntegral count
-
-        inner writeIdx i | i >= maxi = pure writeIdx
-        inner writeIdx i = do
-            let v = str `BU.unsafeIndex` i
-            (vec `M.unsafeWrite` writeIdx) v
-            inner (writeIdx + stride) $ i + 1
-
-unpackPackBit :: B.ByteString -> M.STVector s Word8 -> Int -> Int
-              -> (Word32, Word32)
-              -> ST s Int
-unpackPackBit str outVec stride writeIndex (offset, size) = loop fromi writeIndex
-  where fromi = fromIntegral offset
-        maxi = fromi + fromIntegral size
-
-        replicateByte writeIdx _     0 = pure writeIdx
-        replicateByte writeIdx v count = do
-            (outVec `M.unsafeWrite` writeIdx) v
-            replicateByte (writeIdx + stride) v $ count - 1
-
-        loop i writeIdx | i >= maxi = pure writeIdx
-        loop i writeIdx = choice
-          {-where v = fromIntegral (str `BU.unsafeIndex` i) :: Int8-}
-          where v = fromIntegral (str `B.index` i) :: Int8
-
-                choice
-                    -- data
-                    | 0    <= v =
-                        copyByteString str outVec stride writeIdx
-                                        (fromIntegral $ i + 1, fromIntegral v + 1)
-                            >>= loop (i + 2 + fromIntegral v)
-                    -- run
-                    | -127 <= v = do
-                        {-let nextByte = str `BU.unsafeIndex` (i + 1)-}
-                        let nextByte = str `B.index` (i + 1)
-                            count = negate (fromIntegral v) + 1 :: Int
-                        replicateByte writeIdx nextByte count
-                            >>= loop (i + 2)
-
-                    -- noop
-                    | otherwise = loop writeIdx $ i + 1
-
-uncompressAt :: TiffCompression
-             -> B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32)
-             -> ST s Int
-uncompressAt CompressionNone = copyByteString
-uncompressAt CompressionPackBit = unpackPackBit
-uncompressAt CompressionLZW =  \str outVec _stride writeIndex (offset, size) -> do
-    let toDecode = B.take (fromIntegral size) $ B.drop (fromIntegral offset) str
-    runBoolReader $ decodeLzwTiff toDecode outVec writeIndex
-    return 0
-uncompressAt _ = error "Unhandled compression"
-
-class Unpackable a where
-    type StorageType a :: *
-
-    outAlloc :: a -> Int -> ST s (M.STVector s (StorageType a))
-
-    -- | Final image and size, return offset and vector
-    allocTempBuffer :: a  -> M.STVector s (StorageType a) -> Int
-                    -> ST s (M.STVector s Word8)
-
-    offsetStride :: a -> Int -> Int -> (Int, Int)
-
-    mergeBackTempBuffer :: a    -- ^ Type witness, just for the type checker.
-                        -> Endianness
-                        -> M.STVector s Word8 -- ^ Temporary buffer handling decompression.
-                        -> Int  -- ^ Line size in pixels
-                        -> Int  -- ^ Write index, in bytes
-                        -> Word32  -- ^ size, in bytes
-                        -> Int  -- ^ Stride
-                        -> M.STVector s (StorageType a) -- ^ Final buffer
-                        -> ST s ()
-
--- | The Word8 instance is just a passthrough, to avoid
--- copying memory twice
-instance Unpackable Word8 where
-  type StorageType Word8 = Word8
-
-  offsetStride _ i stride = (i, stride)
-  allocTempBuffer _ buff _ = pure buff
-  mergeBackTempBuffer _ _ _ _ _ _ _ _ = pure ()
-  outAlloc _ count = M.replicate count 0 -- M.new
-
-instance Unpackable Word16 where
-  type StorageType Word16 = Word16
-
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  allocTempBuffer _ _ s = M.new $ s * 2
-  mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec =
-        looperLe index 0
-    where looperLe _ readIndex | readIndex >= fromIntegral size = pure ()
-          looperLe writeIndex readIndex = do
-              v1 <- tempVec `M.read` readIndex
-              v2 <- tempVec `M.read` (readIndex + 1)
-              let finalValue =
-                    (fromIntegral v2 `unsafeShiftL` 8) .|. fromIntegral v1
-              (outVec `M.write` writeIndex) finalValue
-
-              looperLe (writeIndex + stride) (readIndex + 2)
-  mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec =
-         looperBe index 0
-    where looperBe _ readIndex | readIndex >= fromIntegral size = pure ()
-          looperBe writeIndex readIndex = do
-              v1 <- tempVec `M.read` readIndex
-              v2 <- tempVec `M.read` (readIndex + 1)
-              let finalValue =
-                    (fromIntegral v1 `unsafeShiftL` 8) .|. fromIntegral v2
-              (outVec `M.write` writeIndex) finalValue
-
-              looperBe (writeIndex + stride) (readIndex + 2)
-
-instance Unpackable Word32 where
-  type StorageType Word32 = Word32
-
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  allocTempBuffer _ _ s = M.new $ s * 4
-  mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec =
-        looperLe index 0
-    where looperLe _ readIndex | readIndex >= fromIntegral size = pure ()
-          looperLe writeIndex readIndex = do
-              v1 <- tempVec `M.read` readIndex
-              v2 <- tempVec `M.read` (readIndex + 1)
-              v3 <- tempVec `M.read` (readIndex + 2)
-              v4 <- tempVec `M.read` (readIndex + 3)
-              let finalValue =
-                    (fromIntegral v4 `unsafeShiftL` 24) .|.
-                    (fromIntegral v3 `unsafeShiftL` 16) .|.
-                    (fromIntegral v2 `unsafeShiftL` 8) .|.
-                    fromIntegral v1
-              (outVec `M.write` writeIndex) finalValue
-
-              looperLe (writeIndex + stride) (readIndex + 4)
-  mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec =
-         looperBe index 0
-    where looperBe _ readIndex | readIndex >= fromIntegral size = pure ()
-          looperBe writeIndex readIndex = do
-              v1 <- tempVec `M.read` readIndex
-              v2 <- tempVec `M.read` (readIndex + 1)
-              v3 <- tempVec `M.read` (readIndex + 2)
-              v4 <- tempVec `M.read` (readIndex + 3)
-              let finalValue =
-                    (fromIntegral v1 `unsafeShiftL` 24) .|.
-                    (fromIntegral v2 `unsafeShiftL` 16) .|.
-                    (fromIntegral v3 `unsafeShiftL` 8) .|.
-                    fromIntegral v4
-              (outVec `M.write` writeIndex) finalValue
-
-              looperBe (writeIndex + stride) (readIndex + 4)
-
-instance Unpackable Float where
-  type StorageType Float = Float
-
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  allocTempBuffer _ _ s = M.new $ s * 4
-  mergeBackTempBuffer :: forall s. Float
-                      -> Endianness
-                      -> M.STVector s Word8
-                      -> Int
-                      -> Int
-                      -> Word32
-                      -> Int
-                      -> M.STVector s (StorageType Float)
-                      -> ST s ()
-  mergeBackTempBuffer _ endianness tempVec lineSize index size stride outVec =
-        let outVecWord32 :: M.STVector s Word32
-            outVecWord32 = M.unsafeCast outVec
-        in mergeBackTempBuffer (0 :: Word32)
-                               endianness
-                               tempVec
-                               lineSize
-                               index
-                               size
-                               stride
-                               outVecWord32
-
-data Pack4 = Pack4
-
-instance Unpackable Pack4 where
-  type StorageType Pack4 = Word8
-  allocTempBuffer _ _ = M.new
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
-        inner 0 index pxCount
-    where pxCount = lineSize `div` stride
-
-          maxWrite = M.length outVec
-          inner readIdx writeIdx _
-                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
-          inner readIdx writeIdx line
-                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
-          inner readIdx writeIdx line = do
-            v <- tempVec `M.read` readIdx
-            let high = (v `unsafeShiftR` 4) .&. 0xF
-                low = v .&. 0xF
-            (outVec `M.write` writeIdx) high
-            when (writeIdx + stride < maxWrite) $
-                 (outVec `M.write` (writeIdx + stride)) low
-
-            inner (readIdx + 1) (writeIdx + 2 * stride) (line - 2)
-
-data Pack2 = Pack2
-
-instance Unpackable Pack2 where
-  type StorageType Pack2 = Word8
-  allocTempBuffer _ _ = M.new
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
-        inner 0 index pxCount
-    where pxCount = lineSize `div` stride
-
-          maxWrite = M.length outVec
-          inner readIdx writeIdx _
-                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
-          inner readIdx writeIdx line
-                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
-          inner readIdx writeIdx line = do
-            v <- tempVec `M.read` readIdx
-            let v0 = (v `unsafeShiftR` 6) .&. 0x3
-                v1 = (v `unsafeShiftR` 4) .&. 0x3
-                v2 = (v `unsafeShiftR` 2) .&. 0x3
-                v3 = v .&. 0x3
-
-            (outVec `M.write` writeIdx) v0
-            when (writeIdx + 1 * stride < maxWrite) $
-                 (outVec `M.write` (writeIdx + stride)) v1
-
-            when (writeIdx + 2 * stride < maxWrite) $
-                 (outVec `M.write` (writeIdx + stride * 2)) v2
-
-            when (writeIdx + 3 * stride < maxWrite) $
-                 (outVec `M.write` (writeIdx + stride * 3)) v3
-
-            inner (readIdx + 1) (writeIdx + 4 * stride) (line - 4)
-
-data Pack12 = Pack12
-
-instance Unpackable Pack12 where
-  type StorageType Pack12 = Word16
-  allocTempBuffer _ _ = M.new
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
-        inner 0 index pxCount
-    where pxCount = lineSize `div` stride
-
-          maxWrite = M.length outVec
-          inner readIdx writeIdx _
-                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
-          inner readIdx writeIdx line
-                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
-          inner readIdx writeIdx line = do
-            v0 <- tempVec `M.read` readIdx
-            v1 <- if readIdx + 1 < fromIntegral size
-                then tempVec `M.read` (readIdx + 1)
-                else pure 0
-            v2 <- if readIdx + 2 < fromIntegral size
-                then tempVec `M.read` (readIdx + 2)
-                else pure 0
-
-            let high0 = fromIntegral v0 `unsafeShiftL` 4
-                low0 = (fromIntegral v1 `unsafeShiftR` 4) .&. 0xF
-
-                p0 = high0 .|. low0
-
-                high1 = (fromIntegral v1 .&. 0xF) `unsafeShiftL` 8
-                low1 = fromIntegral v2
-                p1 = high1 .|. low1
-
-            (outVec `M.write` writeIdx) p0
-            when (writeIdx + 1 * stride < maxWrite) $
-                 (outVec `M.write` (writeIdx + stride)) p1
-
-            inner (readIdx + 3) (writeIdx + 2 * stride) (line - 2)
-
-data YCbCrSubsampling = YCbCrSubsampling
-    { ycbcrWidth        :: !Int
-    , ycbcrHeight       :: !Int
-    , ycbcrImageWidth   :: !Int
-    , ycbcrStripHeight  :: !Int
-    }
-
-instance Unpackable YCbCrSubsampling where
-  type StorageType YCbCrSubsampling = Word8
-
-  offsetStride _ _ _ = (0, 1)
-  outAlloc _ = M.new
-  allocTempBuffer _ _ = M.new
-  mergeBackTempBuffer subSampling _ tempVec _ index size _ outVec =
-      foldM_ unpacker 0 [(bx, by) | by <- [0, h .. lineCount - 1]
-                                  , bx <- [0, w .. imgWidth - 1]]
-    where w = ycbcrWidth subSampling
-          h = ycbcrHeight subSampling
-          imgWidth = ycbcrImageWidth subSampling
-          lineCount = ycbcrStripHeight subSampling
-
-          lumaCount = w * h
-          blockSize = lumaCount + 2
-
-          maxOut = M.length outVec
-
-          unpacker readIdx _ | readIdx >= fromIntegral size * 3 = pure readIdx
-          unpacker readIdx (bx, by) = do
-              cb <- tempVec `M.read` (readIdx + lumaCount)
-              cr <- tempVec `M.read` (readIdx + lumaCount + 1)
-
-              let pixelIndices =
-                        [index + ((by + y) * imgWidth + bx + x) * 3 | y <- [0 .. h - 1], x <- [0 .. w - 1]]
-
-                  writer readIndex writeIdx | writeIdx + 3 > maxOut = pure readIndex
-                  writer readIndex writeIdx = do
-                    y <- tempVec `M.read` readIndex
-                    (outVec `M.write` writeIdx) y
-                    (outVec `M.write` (writeIdx + 1)) cb
-                    (outVec `M.write` (writeIdx + 2)) cr
-                    return $ readIndex + 1
-
-              foldM_ writer readIdx pixelIndices
-
-              return $ readIdx + blockSize
-
-gatherStrips :: ( Unpackable comp
-                , Pixel pixel
-                , StorageType comp ~ PixelBaseComponent pixel
-                )
-             => comp -> B.ByteString -> TiffInfo -> Image pixel
-gatherStrips comp str nfo = runST $ do
-  let width = fromIntegral $ tiffWidth nfo
-      height = fromIntegral $ tiffHeight nfo
-      sampleCount = if tiffSampleCount nfo /= 0
-        then fromIntegral $ tiffSampleCount nfo
-        else V.length $ tiffBitsPerSample nfo
-
-      rowPerStrip = fromIntegral $ tiffRowPerStrip nfo
-      endianness = hdrEndianness $ tiffHeader nfo
-
-      stripCount = V.length $ tiffOffsets nfo
-      compression = tiffCompression nfo
-
-  outVec <- outAlloc comp $ width * height * sampleCount
-  tempVec <- allocTempBuffer comp outVec
-                        (rowPerStrip * width * sampleCount)
-
-  let mutableImage = MutableImage
-                   { mutableImageWidth = fromIntegral width
-                   , mutableImageHeight = fromIntegral height
-                   , mutableImageData = outVec
-                   }
-
-  case tiffPlaneConfiguration nfo of
-    PlanarConfigContig -> V.mapM_ unpacker sizes
-        where unpacker (idx, stripSampleCount, offset, packedSize) = do
-                  let (writeIdx, tempStride)  = offsetStride comp idx 1
-                  _ <- uncompressAt compression str tempVec tempStride
-                                    writeIdx (offset, packedSize)
-                  let typ :: M.MVector s a -> a
-                      typ = const undefined
-                      sampleSize = sizeOf (typ outVec)
-                  mergeBackTempBuffer comp endianness tempVec (width * sampleCount)
-                                      idx (fromIntegral $ stripSampleCount * sampleSize) 1 outVec
-
-
-              fullStripSampleCount = rowPerStrip * width * sampleCount
-              startWriteOffset = V.generate stripCount (fullStripSampleCount *)
-              stripSampleCounts = V.map strip startWriteOffset
-                  where
-                      strip start = min fullStripSampleCount (width * height * sampleCount - start)
-
-              sizes = V.zip4 startWriteOffset stripSampleCounts
-                             (tiffOffsets nfo) (tiffStripSize nfo)
-
-    PlanarConfigSeparate -> V.mapM_ unpacker sizes
-        where unpacker (idx, offset, size) = do
-                  let (writeIdx, tempStride) = offsetStride comp idx stride
-                  _ <- uncompressAt compression str tempVec tempStride
-                                    writeIdx (offset, size)
-                  mergeBackTempBuffer comp endianness tempVec (width * sampleCount)
-                                      idx size stride outVec
-
-              stride = V.length $ tiffOffsets nfo
-              idxVector = V.enumFromN 0 stride
-              sizes = V.zip3 idxVector (tiffOffsets nfo) (tiffStripSize nfo)
-
-  when (tiffPredictor nfo == PredictorHorizontalDifferencing) $ do
-    let f _ c1 c2 = c1 + c2
-    forM_ [0 .. height - 1] $ \y ->
-      forM_ [1 .. width - 1] $ \x -> do
-        p <- readPixel mutableImage (x - 1) y
-        q <- readPixel mutableImage x y
-        writePixel mutableImage x y $ mixWith f p q
-
-  unsafeFreezeImage mutableImage
-
-ifdSingleLong :: ExifTag -> Word32 -> Writer [ImageFileDirectory] ()
-ifdSingleLong tag = ifdMultiLong tag . V.singleton
-
-ifdSingleShort :: Endianness -> ExifTag -> Word16
-               -> Writer [ImageFileDirectory] ()
-ifdSingleShort endian tag = ifdMultiShort endian tag . V.singleton . fromIntegral
-
-ifdMultiLong :: ExifTag -> V.Vector Word32 -> Writer [ImageFileDirectory] ()
-ifdMultiLong tag v = tell . pure $ ImageFileDirectory
-        { ifdIdentifier = tag
-        , ifdType       = TypeLong
-        , ifdCount      = fromIntegral $ V.length v
-        , ifdOffset     = offset
-        , ifdExtended   = extended
-        }
-  where (offset, extended)
-                | V.length v > 1 = (0, ExifLongs v)
-                | otherwise = (V.head v, ExifNone)
-
-ifdMultiShort :: Endianness -> ExifTag -> V.Vector Word32
-              -> Writer [ImageFileDirectory] ()
-ifdMultiShort endian tag v = tell . pure $ ImageFileDirectory
-        { ifdIdentifier = tag
-        , ifdType       = TypeShort
-        , ifdCount      = size
-        , ifdOffset     = offset
-        , ifdExtended   = extended
-        }
-    where size = fromIntegral $ V.length v
-          (offset, extended)
-                | size > 2 = (0, ExifShorts $ V.map fromIntegral v)
-                | size == 2 =
-                    let v1 = fromIntegral $ V.head v
-                        v2 = fromIntegral $ v `V.unsafeIndex` 1
-                    in
-                    case endian of
-                      EndianLittle -> (v2 `unsafeShiftL` 16 .|. v1, ExifNone)
-                      EndianBig -> (v1 `unsafeShiftL` 16 .|. v2, ExifNone)
-
-                | otherwise = case endian of
-                    EndianLittle -> (V.head v, ExifNone)
-                    EndianBig -> (V.head v `unsafeShiftL` 16, ExifNone)
-
-instance BinaryParam B.ByteString TiffInfo where
-  putP rawData nfo = putP rawData (tiffHeader nfo, [list]) where
-    endianness = hdrEndianness $ tiffHeader nfo
-
-    ifdShort = ifdSingleShort endianness
-    ifdShorts = ifdMultiShort endianness
-
-    list = execWriter $ do
-      ifdSingleLong TagImageWidth $ tiffWidth nfo
-      ifdSingleLong TagImageLength $ tiffHeight nfo
-      ifdShorts TagBitsPerSample $ tiffBitsPerSample nfo
-      ifdSingleLong TagSamplesPerPixel $ tiffSampleCount nfo
-      ifdSingleLong TagRowPerStrip $ tiffRowPerStrip nfo
-      ifdShort TagPhotometricInterpretation
-                                  . packPhotometricInterpretation
-                                  $ tiffColorspace nfo
-      ifdShort TagPlanarConfiguration
-              . constantToPlaneConfiguration $ tiffPlaneConfiguration nfo
-      ifdMultiLong TagSampleFormat
-                                  . V.fromList
-                                  . map packSampleFormat
-                                  $ tiffSampleFormat nfo
-      ifdShort TagCompression . packCompression
-                                    $ tiffCompression nfo
-      ifdMultiLong TagStripOffsets $ tiffOffsets nfo
-
-      ifdMultiLong TagStripByteCounts $ tiffStripSize nfo
-
-      maybe (return ())
-            (ifdShort TagExtraSample . codeOfExtraSample)
-          $ tiffExtraSample nfo
-
-      let subSampling = tiffYCbCrSubsampling nfo
-      unless (V.null subSampling) $
-           ifdShorts TagYCbCrSubsampling subSampling
-
-  getP rawData = do
-    (hdr, cleanedFull :: [[ImageFileDirectory]]) <- getP rawData
-
-    let cleaned = concat cleanedFull
-        dataFind str tag = findIFDData str tag cleaned
-        dataDefault def tag = findIFDDefaultData def tag cleaned
-        extFind str tag = findIFDExt str tag cleaned
-        extDefault def tag = findIFDExtDefaultData def tag cleaned
-
-    TiffInfo hdr
-        <$> dataFind "Can't find width" TagImageWidth
-        <*> dataFind "Can't find height" TagImageLength
-        <*> (dataFind "Can't find color space" TagPhotometricInterpretation
-                     >>= unpackPhotometricInterpretation)
-        <*> dataFind "Can't find sample per pixel" TagSamplesPerPixel
-        <*> dataFind "Can't find row per strip" TagRowPerStrip
-        <*> (dataDefault 1 TagPlanarConfiguration
-                     >>= planarConfgOfConstant)
-        <*> (extDefault [1] TagSampleFormat
-                     >>= mapM unpackSampleFormat)
-        <*> (extFind "Can't find bit per sample" TagBitsPerSample
-                     >>= unLong "Can't find bit depth")
-        <*> (dataFind "Can't find Compression" TagCompression
-                     >>= unPackCompression)
-        <*> (extFind "Can't find byte counts" TagStripByteCounts
-                     >>= unLong "Can't find bit per sample")
-        <*> (extFind "Strip offsets missing" TagStripOffsets
-                     >>= unLong "Can't find strip offsets")
-        <*> findPalette cleaned
-        <*> (V.fromList <$> extDefault [2, 2] TagYCbCrSubsampling)
-        <*> pure Nothing
-        <*> (dataDefault 1 TagPredictor
-                     >>= predictorOfConstant)
-        <*> pure (extractTiffMetadata cleaned)
-
-palette16Of :: Image PixelRGB16 -> Palette' PixelRGB16
-palette16Of p = Palette'
-    { _paletteSize = imageWidth p
-    , _paletteData = imageData p
-    }
-
-unpack :: B.ByteString -> TiffInfo -> Either String PalettedImage
--- | while mandatory some images don't put correct
--- rowperstrip. So replacing 0 with actual image height.
-unpack file nfo@TiffInfo { tiffRowPerStrip = 0 } =
-    unpack file $ nfo { tiffRowPerStrip = tiffHeight nfo }
-unpack file nfo@TiffInfo { tiffColorspace = TiffPaleted
-                         , tiffBitsPerSample = lst
-                         , tiffSampleFormat = format
-                         , tiffPalette = Just p
-                         }
-  | lst == V.singleton 8 && format == [TiffSampleUint] =
-      pure . PalettedRGB16 (gatherStrips (0 :: Word8) file nfo) $ palette16Of p
-  | lst == V.singleton 4 && format == [TiffSampleUint] =
-      pure . PalettedRGB16 (gatherStrips Pack4 file nfo) $ palette16Of p
-  | lst == V.singleton 2 && format == [TiffSampleUint] =
-      pure . PalettedRGB16 (gatherStrips Pack2 file nfo) $ palette16Of p
-
-unpack file nfo@TiffInfo { tiffColorspace = TiffCMYK
-                         , tiffBitsPerSample = lst
-                         , tiffSampleFormat = format }
-  | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageCMYK8 $ gatherStrips (0 :: Word8) file nfo
-
-  | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageCMYK16 $ gatherStrips (0 :: Word16) file nfo
-
-unpack file nfo@TiffInfo { tiffColorspace = TiffMonochromeWhite0 } = do
-    img <- unpack file (nfo { tiffColorspace = TiffMonochrome })
-    case img of
-      TrueColorImage (ImageY8 i) -> pure . TrueColorImage . ImageY8 $ pixelMap (maxBound -) i
-      TrueColorImage (ImageY16 i) -> pure . TrueColorImage . ImageY16 $ pixelMap (maxBound -) i
-      TrueColorImage (ImageYA8 i) -> let negative (PixelYA8 y a) = PixelYA8 (maxBound - y) a
-                    in pure . TrueColorImage . ImageYA8 $ pixelMap negative i
-      TrueColorImage (ImageYA16 i) -> let negative (PixelYA16 y a) = PixelYA16 (maxBound - y) a
-                     in pure . TrueColorImage . ImageYA16 $ pixelMap negative i
-      _ -> Left "Unsupported color type used with colorspace MonochromeWhite0"
-
-unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome
-                         , tiffBitsPerSample = lst
-                         , tiffSampleFormat = format }
-  | lst == V.singleton 2 && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageY8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
-  | lst == V.singleton 4 && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageY8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
-  | lst == V.singleton 8 && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageY8 $ gatherStrips (0 :: Word8) file nfo
-  | lst == V.singleton 12 && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageY16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo
-  | lst == V.singleton 16 && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageY16 $ gatherStrips (0 :: Word16) file nfo
-  | lst == V.singleton 32 && all (TiffSampleUint ==) format =
-        let img = gatherStrips (0 :: Word32) file nfo :: Image Pixel32
-        in pure $ TrueColorImage $ ImageY32 $ img
-  | lst == V.singleton 32 && all (TiffSampleFloat ==) format =
-        let img = gatherStrips (0 :: Float) file nfo :: Image PixelF
-        in pure $ TrueColorImage $ ImageYF $ img
-  | lst == V.singleton 64 = Left "Failure to unpack TIFF file, 64-bit samples unsupported."
-  | lst == V.fromList [2, 2] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageYA8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
-  | lst == V.fromList [4, 4] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageYA8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
-  | lst == V.fromList [8, 8] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageYA8 $ gatherStrips (0 :: Word8) file nfo
-  | lst == V.fromList [12, 12] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageYA16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo
-  | lst == V.fromList [16, 16] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageYA16 $ gatherStrips (0 :: Word16) file nfo
-    where
-      expand12to16 x = x `unsafeShiftL` 4 + x `unsafeShiftR` (12 - 4)
-
-unpack file nfo@TiffInfo { tiffColorspace = TiffYCbCr
-                         , tiffBitsPerSample = lst
-                         , tiffPlaneConfiguration = PlanarConfigContig
-                         , tiffSampleFormat = format }
-  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
-    pure . TrueColorImage . ImageYCbCr8 $ gatherStrips cbcrConf  file nfo
-      where defaulting 0 = 2
-            defaulting n = n
-
-            w = defaulting $ tiffYCbCrSubsampling nfo V.! 0
-            h = defaulting $ tiffYCbCrSubsampling nfo V.! 1
-            cbcrConf = YCbCrSubsampling
-                { ycbcrWidth        = fromIntegral w
-                , ycbcrHeight       = fromIntegral h
-                , ycbcrImageWidth   = fromIntegral $ tiffWidth nfo
-                , ycbcrStripHeight  = fromIntegral $ tiffRowPerStrip nfo
-                }
-
-unpack file nfo@TiffInfo { tiffColorspace = TiffRGB
-                         , tiffBitsPerSample = lst
-                         , tiffSampleFormat = format }
-  | lst == V.fromList [2, 2, 2] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGB8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
-  | lst == V.fromList [4, 4, 4] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGB8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
-  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo
-  | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGBA8 $ gatherStrips (0 :: Word8) file nfo
-  | lst == V.fromList [16, 16, 16] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGB16 $ gatherStrips (0 :: Word16) file nfo
-  | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGBA16 $ gatherStrips (0 :: Word16) file nfo
-unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome
-                         , tiffBitsPerSample = lst
-                         , tiffSampleFormat = format }
-  -- some files are a little bit borked...
-  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
-        pure . TrueColorImage . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo
-
-unpack _ _ = Left "Failure to unpack TIFF file"
-
--- | Decode a tiff encoded image while preserving the underlying
--- pixel type (except for Y32 which is truncated to 16 bits).
---
--- This function can output the following images:
---
---  * 'ImageY8'
---
---  * 'ImageY16'
---
---  * 'ImageY32'
---
---  * 'ImageYF'
---
---  * 'ImageYA8'
---
---  * 'ImageYA16'
---
---  * 'ImageRGB8'
---
---  * 'ImageRGB16'
---
---  * 'ImageRGBA8'
---
---  * 'ImageRGBA16'
---
---  * 'ImageCMYK8'
---
---  * 'ImageCMYK16'
---
-decodeTiff :: B.ByteString -> Either String DynamicImage
-decodeTiff = fmap fst . decodeTiffWithMetadata 
-
--- | Like 'decodeTiff' but also provides some metdata present
--- in the Tiff file.
---
--- The metadata extracted are the 'Codec.Picture.Metadata.DpiX' &
--- 'Codec.Picture.Metadata.DpiY' information alongside the EXIF informations.
-decodeTiffWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
-decodeTiffWithMetadata str = first palettedToTrueColor <$> decodeTiffWithPaletteAndMetadata str
-
--- | Decode TIFF and provide separated palette and metadata
-decodeTiffWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
-decodeTiffWithPaletteAndMetadata file = runGetStrict (getP file) file >>= go
-  where
-    go tinfo = (, tiffMetadatas tinfo) <$> unpack file tinfo
-    
-
--- | Class defining which pixel types can be serialized in a
--- Tiff file.
-class (Pixel px) => TiffSaveable px where
-  colorSpaceOfPixel :: px -> TiffColorspace
-
-  extraSampleCodeOfPixel :: px -> Maybe ExtraSample
-  extraSampleCodeOfPixel _ = Nothing
-
-  subSamplingInfo   :: px -> V.Vector Word32
-  subSamplingInfo _ = V.empty
-
-  sampleFormat :: px -> [TiffSampleFormat]
-  sampleFormat _ = [TiffSampleUint]
-
-instance TiffSaveable Pixel8 where
-  colorSpaceOfPixel _ = TiffMonochrome
-
-instance TiffSaveable Pixel16 where
-  colorSpaceOfPixel _ = TiffMonochrome
-
-instance TiffSaveable Pixel32 where
-  colorSpaceOfPixel _ = TiffMonochrome
-
-instance TiffSaveable PixelF where
-  colorSpaceOfPixel _ = TiffMonochrome
-  sampleFormat _      = [TiffSampleFloat]
-
-instance TiffSaveable PixelYA8 where
-  colorSpaceOfPixel _ = TiffMonochrome
-  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
-
-instance TiffSaveable PixelYA16 where
-  colorSpaceOfPixel _ = TiffMonochrome
-  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
-
-instance TiffSaveable PixelCMYK8 where
-  colorSpaceOfPixel _ = TiffCMYK
-
-instance TiffSaveable PixelCMYK16 where
-  colorSpaceOfPixel _ = TiffCMYK
-
-instance TiffSaveable PixelRGB8 where
-  colorSpaceOfPixel  _ = TiffRGB
-
-instance TiffSaveable PixelRGB16 where
-  colorSpaceOfPixel  _ = TiffRGB
-
-instance TiffSaveable PixelRGBA8 where
-  colorSpaceOfPixel _ = TiffRGB
-  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
-
-instance TiffSaveable PixelRGBA16 where
-  colorSpaceOfPixel _ = TiffRGB
-  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
-
-instance TiffSaveable PixelYCbCr8 where
-  colorSpaceOfPixel _ = TiffYCbCr
-  subSamplingInfo _ = V.fromListN 2 [1, 1]
-
--- | Transform an image into a Tiff encoded bytestring, ready to be
--- written as a file.
-encodeTiff :: forall px. (TiffSaveable px) => Image px -> Lb.ByteString
-encodeTiff img = runPut $ putP rawPixelData hdr
-  where intSampleCount = componentCount (undefined :: px)
-        sampleCount = fromIntegral intSampleCount
-
-        sampleType = undefined :: PixelBaseComponent px
-        pixelData = imageData img
-
-        rawPixelData = toByteString pixelData
-        width = fromIntegral $ imageWidth img
-        height = fromIntegral $ imageHeight img
-        intSampleSize = sizeOf sampleType
-        sampleSize = fromIntegral intSampleSize
-        bitPerSample = sampleSize * 8
-        imageSize = width * height * sampleCount * sampleSize
-        headerSize = 8
-
-        hdr = TiffInfo
-            { tiffHeader             = TiffHeader
-                                            { hdrEndianness = EndianLittle
-                                            , hdrOffset = headerSize + imageSize
-                                            }
-            , tiffWidth              = width
-            , tiffHeight             = height
-            , tiffColorspace         = colorSpaceOfPixel (undefined :: px)
-            , tiffSampleCount        = fromIntegral sampleCount
-            , tiffRowPerStrip        = fromIntegral $ imageHeight img
-            , tiffPlaneConfiguration = PlanarConfigContig
-            , tiffSampleFormat       = sampleFormat (undefined :: px)
-            , tiffBitsPerSample      = V.replicate intSampleCount bitPerSample
-            , tiffCompression        = CompressionNone
-            , tiffStripSize          = V.singleton imageSize
-            , tiffOffsets            = V.singleton headerSize
-            , tiffPalette            = Nothing
-            , tiffYCbCrSubsampling   = subSamplingInfo (undefined :: px)
-            , tiffExtraSample        = extraSampleCodeOfPixel (undefined :: px)
-            , tiffPredictor          = PredictorNone -- not used when writing
-            , tiffMetadatas          = mempty
-            }
-
--- | Helper function to directly write an image as a tiff on disk.
-writeTiff :: (TiffSaveable pixel) => FilePath -> Image pixel -> IO ()
-writeTiff path img = Lb.writeFile path $ encodeTiff img
-
-{-# ANN module "HLint: ignore Reduce duplication" #-}
-
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE InstanceSigs #-}
+{-# LANGUAGE CPP #-}
+-- | Module implementing TIFF decoding.
+--
+-- Supported compression schemes:
+--
+--   * Uncompressed
+--
+--   * PackBits
+--
+--   * LZW
+--
+-- Supported bit depth:
+--
+--   * 2 bits
+--
+--   * 4 bits
+--
+--   * 8 bits
+--
+--   * 16 bits
+--
+module Codec.Picture.Tiff( decodeTiff
+                         , decodeTiffWithMetadata
+                         , decodeTiffWithPaletteAndMetadata
+                         , TiffSaveable
+                         , encodeTiff
+                         , writeTiff
+                         ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>), (<*>), pure )
+import Data.Monoid( mempty )
+#endif
+
+import Control.Arrow( first )
+import Control.Monad( when, foldM_, unless, forM_ )
+import Control.Monad.ST( ST, runST )
+import Control.Monad.Writer.Strict( execWriter, tell, Writer )
+import Data.Int( Int8 )
+import Data.Word( Word8, Word16, Word32 )
+import Data.Bits( (.&.), (.|.), unsafeShiftL, unsafeShiftR )
+import Data.Binary.Get( Get )
+import Data.Binary.Put( runPut )
+
+import qualified Data.Vector as V
+import qualified Data.Vector.Storable as VS
+import qualified Data.Vector.Storable.Mutable as M
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Lazy as Lb
+import qualified Data.ByteString.Unsafe as BU
+
+import Foreign.Storable( sizeOf )
+
+import Codec.Picture.Metadata.Exif
+import Codec.Picture.Metadata( Metadatas )
+import Codec.Picture.InternalHelper
+import Codec.Picture.BitWriter
+import Codec.Picture.Types
+import Codec.Picture.Gif.Internal.LZW
+import Codec.Picture.Tiff.Internal.Types
+import Codec.Picture.Tiff.Internal.Metadata
+import Codec.Picture.VectorByteConversion( toByteString )
+
+data TiffInfo = TiffInfo
+  { tiffHeader             :: TiffHeader
+  , tiffWidth              :: Word32
+  , tiffHeight             :: Word32
+  , tiffColorspace         :: TiffColorspace
+  , tiffSampleCount        :: Word32
+  , tiffRowPerStrip        :: Word32
+  , tiffPlaneConfiguration :: TiffPlanarConfiguration
+  , tiffSampleFormat       :: [TiffSampleFormat]
+  , tiffBitsPerSample      :: V.Vector Word32
+  , tiffCompression        :: TiffCompression
+  , tiffStripSize          :: V.Vector Word32
+  , tiffOffsets            :: V.Vector Word32
+  , tiffPalette            :: Maybe (Image PixelRGB16)
+  , tiffYCbCrSubsampling   :: V.Vector Word32
+  , tiffExtraSample        :: Maybe ExtraSample
+  , tiffPredictor          :: Predictor
+  , tiffMetadatas          :: Metadatas
+  }
+
+unLong :: String -> ExifData -> Get (V.Vector Word32)
+unLong _ (ExifLong v)   = pure $ V.singleton v
+unLong _ (ExifShort v)  = pure $ V.singleton (fromIntegral v)
+unLong _ (ExifShorts v) = pure $ V.map fromIntegral v
+unLong _ (ExifLongs v) = pure v
+unLong errMessage _ = fail errMessage
+
+findIFD :: String -> ExifTag -> [ImageFileDirectory]
+        -> Get ImageFileDirectory
+findIFD errorMessage tag lst =
+  case [v | v <- lst, ifdIdentifier v == tag] of
+    [] -> fail errorMessage
+    (x:_) -> pure x
+
+findPalette :: [ImageFileDirectory] -> Get (Maybe (Image PixelRGB16))
+findPalette ifds =
+    case [v | v <- ifds, ifdIdentifier v == TagColorMap] of
+        (ImageFileDirectory { ifdExtended = ExifShorts vec }:_) ->
+            pure . Just . Image pixelCount 1 $ VS.generate (V.length vec) axx
+                where pixelCount = V.length vec `div` 3
+                      axx v = vec `V.unsafeIndex` (idx + color * pixelCount)
+                          where (idx, color) = v `divMod` 3
+
+        _ -> pure Nothing
+
+findIFDData :: String -> ExifTag -> [ImageFileDirectory] -> Get Word32
+findIFDData msg tag lst = ifdOffset <$> findIFD msg tag lst
+
+findIFDDefaultData :: Word32 -> ExifTag -> [ImageFileDirectory] -> Get Word32
+findIFDDefaultData d tag lst =
+    case [v | v <- lst, ifdIdentifier v == tag] of
+        [] -> pure d
+        (x:_) -> pure $ ifdOffset x
+
+findIFDExt :: String -> ExifTag -> [ImageFileDirectory] -> Get ExifData
+findIFDExt msg tag lst = do
+    val <- findIFD msg tag lst
+    case val of
+      ImageFileDirectory
+        { ifdCount = 1, ifdOffset = ofs, ifdType = TypeShort } ->
+               pure . ExifShorts . V.singleton $ fromIntegral ofs
+      ImageFileDirectory
+        { ifdCount = 1, ifdOffset = ofs, ifdType = TypeLong } ->
+               pure . ExifLongs  . V.singleton $ fromIntegral ofs
+      ImageFileDirectory { ifdExtended = v } -> pure v
+
+
+findIFDExtDefaultData :: [Word32] -> ExifTag -> [ImageFileDirectory]
+                      -> Get [Word32]
+findIFDExtDefaultData d tag lst =
+    case [v | v <- lst, ifdIdentifier v == tag] of
+        [] -> pure d
+        (ImageFileDirectory { ifdExtended = ExifNone }:_) -> return d
+        (x:_) -> V.toList <$> unLong errorMessage (ifdExtended x)
+            where errorMessage =
+                    "Can't parse tag " ++ show tag ++ " " ++ show (ifdExtended x)
+
+-- It's temporary, remove once tiff decoding is better
+-- handled.
+{-  
+instance Show (Image PixelRGB16) where
+    show _ = "Image PixelRGB16"
+-}
+copyByteString :: B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32)
+               -> ST s Int
+copyByteString str vec stride startWrite (from, count) = inner startWrite fromi
+  where fromi = fromIntegral from
+        maxi = fromi + fromIntegral count
+        maxWrite = M.length vec
+
+        inner writeIdx i | i >= maxi || writeIdx >= maxWrite = pure writeIdx
+        inner writeIdx i = do
+            let v = str `BU.unsafeIndex` i
+            (vec `M.unsafeWrite` writeIdx) v
+            inner (writeIdx + stride) $ i + 1
+
+unpackPackBit :: B.ByteString -> M.STVector s Word8 -> Int -> Int
+              -> (Word32, Word32)
+              -> ST s Int
+unpackPackBit str outVec stride writeIndex (offset, size) = loop fromi writeIndex
+  where fromi = fromIntegral offset
+        maxi = fromi + fromIntegral size
+        maxWrite = M.length outVec
+
+        replicateByte writeIdx _ 0 = pure writeIdx
+        replicateByte writeIdx v count
+            | writeIdx >= maxWrite = pure writeIdx
+            | otherwise = do
+                (outVec `M.unsafeWrite` writeIdx) v
+                replicateByte (writeIdx + stride) v $ count - 1
+
+        loop i writeIdx | i >= maxi || writeIdx >= maxWrite = pure writeIdx
+        loop i writeIdx = choice
+          {-where v = fromIntegral (str `BU.unsafeIndex` i) :: Int8-}
+          where v = fromIntegral (str `B.index` i) :: Int8
+
+                choice
+                    -- data
+                    | 0    <= v =
+                        copyByteString str outVec stride writeIdx
+                                        (fromIntegral $ i + 1, fromIntegral v + 1)
+                            >>= loop (i + 2 + fromIntegral v)
+                    -- run
+                    | -127 <= v = do
+                        {-let nextByte = str `BU.unsafeIndex` (i + 1)-}
+                        let nextByte = str `B.index` (i + 1)
+                            count = negate (fromIntegral v) + 1 :: Int
+                        replicateByte writeIdx nextByte count
+                            >>= loop (i + 2)
+
+                    -- noop
+                    | otherwise = loop writeIdx $ i + 1
+
+uncompressAt :: TiffCompression
+             -> B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32)
+             -> ST s Int
+uncompressAt CompressionNone = copyByteString
+uncompressAt CompressionPackBit = unpackPackBit
+uncompressAt CompressionLZW =  \str outVec _stride writeIndex (offset, size) -> do
+    let toDecode = B.take (fromIntegral size) $ B.drop (fromIntegral offset) str
+    runBoolReader $ decodeLzwTiff toDecode outVec writeIndex
+    return 0
+uncompressAt _ = error "Unhandled compression"
+
+class Unpackable a where
+    type StorageType a :: *
+
+    outAlloc :: a -> Int -> ST s (M.STVector s (StorageType a))
+
+    -- | Final image and size, return offset and vector
+    allocTempBuffer :: a  -> M.STVector s (StorageType a) -> Int
+                    -> ST s (M.STVector s Word8)
+
+    offsetStride :: a -> Int -> Int -> (Int, Int)
+
+    mergeBackTempBuffer :: a    -- ^ Type witness, just for the type checker.
+                        -> Endianness
+                        -> M.STVector s Word8 -- ^ Temporary buffer handling decompression.
+                        -> Int  -- ^ Line size in pixels
+                        -> Int  -- ^ Write index, in bytes
+                        -> Word32  -- ^ size, in bytes
+                        -> Int  -- ^ Stride
+                        -> M.STVector s (StorageType a) -- ^ Final buffer
+                        -> ST s ()
+
+-- | The Word8 instance is just a passthrough, to avoid
+-- copying memory twice
+instance Unpackable Word8 where
+  type StorageType Word8 = Word8
+
+  offsetStride _ i stride = (i, stride)
+  allocTempBuffer _ buff _ = pure buff
+  mergeBackTempBuffer _ _ _ _ _ _ _ _ = pure ()
+  outAlloc _ count = M.replicate count 0 -- M.new
+
+instance Unpackable Word16 where
+  type StorageType Word16 = Word16
+
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  allocTempBuffer _ _ s = M.new $ s * 2
+  mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec =
+        looperLe index 0
+    where looperLe _ readIndex | readIndex >= fromIntegral size = pure ()
+          looperLe writeIndex readIndex = do
+              v1 <- tempVec `M.read` readIndex
+              v2 <- tempVec `M.read` (readIndex + 1)
+              let finalValue =
+                    (fromIntegral v2 `unsafeShiftL` 8) .|. fromIntegral v1
+              (outVec `M.write` writeIndex) finalValue
+
+              looperLe (writeIndex + stride) (readIndex + 2)
+  mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec =
+         looperBe index 0
+    where looperBe _ readIndex | readIndex >= fromIntegral size = pure ()
+          looperBe writeIndex readIndex = do
+              v1 <- tempVec `M.read` readIndex
+              v2 <- tempVec `M.read` (readIndex + 1)
+              let finalValue =
+                    (fromIntegral v1 `unsafeShiftL` 8) .|. fromIntegral v2
+              (outVec `M.write` writeIndex) finalValue
+
+              looperBe (writeIndex + stride) (readIndex + 2)
+
+instance Unpackable Word32 where
+  type StorageType Word32 = Word32
+
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  allocTempBuffer _ _ s = M.new $ s * 4
+  mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec =
+        looperLe index 0
+    where looperLe _ readIndex | readIndex >= fromIntegral size = pure ()
+          looperLe writeIndex readIndex = do
+              v1 <- tempVec `M.read` readIndex
+              v2 <- tempVec `M.read` (readIndex + 1)
+              v3 <- tempVec `M.read` (readIndex + 2)
+              v4 <- tempVec `M.read` (readIndex + 3)
+              let finalValue =
+                    (fromIntegral v4 `unsafeShiftL` 24) .|.
+                    (fromIntegral v3 `unsafeShiftL` 16) .|.
+                    (fromIntegral v2 `unsafeShiftL` 8) .|.
+                    fromIntegral v1
+              (outVec `M.write` writeIndex) finalValue
+
+              looperLe (writeIndex + stride) (readIndex + 4)
+  mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec =
+         looperBe index 0
+    where looperBe _ readIndex | readIndex >= fromIntegral size = pure ()
+          looperBe writeIndex readIndex = do
+              v1 <- tempVec `M.read` readIndex
+              v2 <- tempVec `M.read` (readIndex + 1)
+              v3 <- tempVec `M.read` (readIndex + 2)
+              v4 <- tempVec `M.read` (readIndex + 3)
+              let finalValue =
+                    (fromIntegral v1 `unsafeShiftL` 24) .|.
+                    (fromIntegral v2 `unsafeShiftL` 16) .|.
+                    (fromIntegral v3 `unsafeShiftL` 8) .|.
+                    fromIntegral v4
+              (outVec `M.write` writeIndex) finalValue
+
+              looperBe (writeIndex + stride) (readIndex + 4)
+
+instance Unpackable Float where
+  type StorageType Float = Float
+
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  allocTempBuffer _ _ s = M.new $ s * 4
+  mergeBackTempBuffer :: forall s. Float
+                      -> Endianness
+                      -> M.STVector s Word8
+                      -> Int
+                      -> Int
+                      -> Word32
+                      -> Int
+                      -> M.STVector s (StorageType Float)
+                      -> ST s ()
+  mergeBackTempBuffer _ endianness tempVec lineSize index size stride outVec =
+        let outVecWord32 :: M.STVector s Word32
+            outVecWord32 = M.unsafeCast outVec
+        in mergeBackTempBuffer (0 :: Word32)
+                               endianness
+                               tempVec
+                               lineSize
+                               index
+                               size
+                               stride
+                               outVecWord32
+
+data Pack4 = Pack4
+
+instance Unpackable Pack4 where
+  type StorageType Pack4 = Word8
+  allocTempBuffer _ _ = M.new
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
+        inner 0 index pxCount
+    where pxCount = lineSize `div` stride
+
+          maxWrite = M.length outVec
+          inner readIdx writeIdx _
+                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
+          inner readIdx writeIdx line
+                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
+          inner readIdx writeIdx line = do
+            v <- tempVec `M.read` readIdx
+            let high = (v `unsafeShiftR` 4) .&. 0xF
+                low = v .&. 0xF
+            (outVec `M.write` writeIdx) high
+            when (writeIdx + stride < maxWrite) $
+                 (outVec `M.write` (writeIdx + stride)) low
+
+            inner (readIdx + 1) (writeIdx + 2 * stride) (line - 2)
+
+data Pack2 = Pack2
+
+instance Unpackable Pack2 where
+  type StorageType Pack2 = Word8
+  allocTempBuffer _ _ = M.new
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
+        inner 0 index pxCount
+    where pxCount = lineSize `div` stride
+
+          maxWrite = M.length outVec
+          inner readIdx writeIdx _
+                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
+          inner readIdx writeIdx line
+                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
+          inner readIdx writeIdx line = do
+            v <- tempVec `M.read` readIdx
+            let v0 = (v `unsafeShiftR` 6) .&. 0x3
+                v1 = (v `unsafeShiftR` 4) .&. 0x3
+                v2 = (v `unsafeShiftR` 2) .&. 0x3
+                v3 = v .&. 0x3
+
+            (outVec `M.write` writeIdx) v0
+            when (writeIdx + 1 * stride < maxWrite) $
+                 (outVec `M.write` (writeIdx + stride)) v1
+
+            when (writeIdx + 2 * stride < maxWrite) $
+                 (outVec `M.write` (writeIdx + stride * 2)) v2
+
+            when (writeIdx + 3 * stride < maxWrite) $
+                 (outVec `M.write` (writeIdx + stride * 3)) v3
+
+            inner (readIdx + 1) (writeIdx + 4 * stride) (line - 4)
+
+data Pack12 = Pack12
+
+instance Unpackable Pack12 where
+  type StorageType Pack12 = Word16
+  allocTempBuffer _ _ = M.new
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec =
+        inner 0 index pxCount
+    where pxCount = lineSize `div` stride
+
+          maxWrite = M.length outVec
+          inner readIdx writeIdx _
+                | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure ()
+          inner readIdx writeIdx line
+                | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount
+          inner readIdx writeIdx line = do
+            v0 <- tempVec `M.read` readIdx
+            v1 <- if readIdx + 1 < fromIntegral size
+                then tempVec `M.read` (readIdx + 1)
+                else pure 0
+            v2 <- if readIdx + 2 < fromIntegral size
+                then tempVec `M.read` (readIdx + 2)
+                else pure 0
+
+            let high0 = fromIntegral v0 `unsafeShiftL` 4
+                low0 = (fromIntegral v1 `unsafeShiftR` 4) .&. 0xF
+
+                p0 = high0 .|. low0
+
+                high1 = (fromIntegral v1 .&. 0xF) `unsafeShiftL` 8
+                low1 = fromIntegral v2
+                p1 = high1 .|. low1
+
+            (outVec `M.write` writeIdx) p0
+            when (writeIdx + 1 * stride < maxWrite) $
+                 (outVec `M.write` (writeIdx + stride)) p1
+
+            inner (readIdx + 3) (writeIdx + 2 * stride) (line - 2)
+
+data YCbCrSubsampling = YCbCrSubsampling
+    { ycbcrWidth        :: !Int
+    , ycbcrHeight       :: !Int
+    , ycbcrImageWidth   :: !Int
+    , ycbcrStripHeight  :: !Int
+    }
+
+instance Unpackable YCbCrSubsampling where
+  type StorageType YCbCrSubsampling = Word8
+
+  offsetStride _ _ _ = (0, 1)
+  outAlloc _ = M.new
+  allocTempBuffer _ _ = M.new
+  mergeBackTempBuffer subSampling _ tempVec _ index size _ outVec =
+      foldM_ unpacker 0 [(bx, by) | by <- [0, h .. lineCount - 1]
+                                  , bx <- [0, w .. imgWidth - 1]]
+    where w = ycbcrWidth subSampling
+          h = ycbcrHeight subSampling
+          imgWidth = ycbcrImageWidth subSampling
+          lineCount = ycbcrStripHeight subSampling
+
+          lumaCount = w * h
+          blockSize = lumaCount + 2
+
+          maxOut = M.length outVec
+
+          unpacker readIdx _ | readIdx >= fromIntegral size * 3 = pure readIdx
+          unpacker readIdx (bx, by) = do
+              cb <- tempVec `M.read` (readIdx + lumaCount)
+              cr <- tempVec `M.read` (readIdx + lumaCount + 1)
+
+              let pixelIndices =
+                        [index + ((by + y) * imgWidth + bx + x) * 3 | y <- [0 .. h - 1], x <- [0 .. w - 1]]
+
+                  writer readIndex writeIdx | writeIdx + 3 > maxOut = pure readIndex
+                  writer readIndex writeIdx = do
+                    y <- tempVec `M.read` readIndex
+                    (outVec `M.write` writeIdx) y
+                    (outVec `M.write` (writeIdx + 1)) cb
+                    (outVec `M.write` (writeIdx + 2)) cr
+                    return $ readIndex + 1
+
+              foldM_ writer readIdx pixelIndices
+
+              return $ readIdx + blockSize
+
+gatherStrips :: ( Unpackable comp
+                , Pixel pixel
+                , StorageType comp ~ PixelBaseComponent pixel
+                )
+             => comp -> B.ByteString -> TiffInfo -> Image pixel
+gatherStrips comp str nfo = runST $ do
+  let width = fromIntegral $ tiffWidth nfo
+      height = fromIntegral $ tiffHeight nfo
+      sampleCount = if tiffSampleCount nfo /= 0
+        then fromIntegral $ tiffSampleCount nfo
+        else V.length $ tiffBitsPerSample nfo
+
+      rowPerStrip = fromIntegral $ tiffRowPerStrip nfo
+      endianness = hdrEndianness $ tiffHeader nfo
+
+      stripCount = V.length $ tiffOffsets nfo
+      compression = tiffCompression nfo
+
+  outVec <- outAlloc comp $ width * height * sampleCount
+  tempVec <- allocTempBuffer comp outVec
+                        (rowPerStrip * width * sampleCount)
+
+  let mutableImage = MutableImage
+                   { mutableImageWidth = fromIntegral width
+                   , mutableImageHeight = fromIntegral height
+                   , mutableImageData = outVec
+                   }
+
+  case tiffPlaneConfiguration nfo of
+    PlanarConfigContig -> V.mapM_ unpacker sizes
+        where unpacker (idx, stripSampleCount, offset, packedSize) = do
+                  let (writeIdx, tempStride)  = offsetStride comp idx 1
+                  _ <- uncompressAt compression str tempVec tempStride
+                                    writeIdx (offset, packedSize)
+                  let typ :: M.MVector s a -> a
+                      typ = const undefined
+                      sampleSize = sizeOf (typ outVec)
+                  mergeBackTempBuffer comp endianness tempVec (width * sampleCount)
+                                      idx (fromIntegral $ stripSampleCount * sampleSize) 1 outVec
+
+
+              fullStripSampleCount = rowPerStrip * width * sampleCount
+              rasterSampleCount = width * height * sampleCount
+              startWriteOffset = V.generate stripCount (\i -> max 0 $ min rasterSampleCount (i * fullStripSampleCount))
+              stripSampleCounts = V.map strip startWriteOffset
+                  where
+                      strip start = min fullStripSampleCount (max 0 (rasterSampleCount - start))
+
+              sizes = V.zip4 startWriteOffset stripSampleCounts
+                             (tiffOffsets nfo) (tiffStripSize nfo)
+
+    PlanarConfigSeparate -> V.mapM_ unpacker sizes
+        where unpacker (idx, offset, size) = do
+                  let (writeIdx, tempStride) = offsetStride comp idx stride
+                  _ <- uncompressAt compression str tempVec tempStride
+                                    writeIdx (offset, size)
+                  mergeBackTempBuffer comp endianness tempVec (width * sampleCount)
+                                      idx size stride outVec
+
+              stride = V.length $ tiffOffsets nfo
+              idxVector = V.enumFromN 0 stride
+              sizes = V.zip3 idxVector (tiffOffsets nfo) (tiffStripSize nfo)
+
+  when (tiffPredictor nfo == PredictorHorizontalDifferencing) $ do
+    let f _ c1 c2 = c1 + c2
+    forM_ [0 .. height - 1] $ \y ->
+      forM_ [1 .. width - 1] $ \x -> do
+        p <- readPixel mutableImage (x - 1) y
+        q <- readPixel mutableImage x y
+        writePixel mutableImage x y $ mixWith f p q
+
+  unsafeFreezeImage mutableImage
+
+ifdSingleLong :: ExifTag -> Word32 -> Writer [ImageFileDirectory] ()
+ifdSingleLong tag = ifdMultiLong tag . V.singleton
+
+ifdSingleShort :: Endianness -> ExifTag -> Word16
+               -> Writer [ImageFileDirectory] ()
+ifdSingleShort endian tag = ifdMultiShort endian tag . V.singleton . fromIntegral
+
+ifdMultiLong :: ExifTag -> V.Vector Word32 -> Writer [ImageFileDirectory] ()
+ifdMultiLong tag v = tell . pure $ ImageFileDirectory
+        { ifdIdentifier = tag
+        , ifdType       = TypeLong
+        , ifdCount      = fromIntegral $ V.length v
+        , ifdOffset     = offset
+        , ifdExtended   = extended
+        }
+  where (offset, extended)
+                | V.length v > 1 = (0, ExifLongs v)
+                | otherwise = (V.head v, ExifNone)
+
+ifdMultiShort :: Endianness -> ExifTag -> V.Vector Word32
+              -> Writer [ImageFileDirectory] ()
+ifdMultiShort endian tag v = tell . pure $ ImageFileDirectory
+        { ifdIdentifier = tag
+        , ifdType       = TypeShort
+        , ifdCount      = size
+        , ifdOffset     = offset
+        , ifdExtended   = extended
+        }
+    where size = fromIntegral $ V.length v
+          (offset, extended)
+                | size > 2 = (0, ExifShorts $ V.map fromIntegral v)
+                | size == 2 =
+                    let v1 = fromIntegral $ V.head v
+                        v2 = fromIntegral $ v `V.unsafeIndex` 1
+                    in
+                    case endian of
+                      EndianLittle -> (v2 `unsafeShiftL` 16 .|. v1, ExifNone)
+                      EndianBig -> (v1 `unsafeShiftL` 16 .|. v2, ExifNone)
+
+                | otherwise = case endian of
+                    EndianLittle -> (V.head v, ExifNone)
+                    EndianBig -> (V.head v `unsafeShiftL` 16, ExifNone)
+
+instance BinaryParam B.ByteString TiffInfo where
+  putP rawData nfo = putP rawData (tiffHeader nfo, [list]) where
+    endianness = hdrEndianness $ tiffHeader nfo
+
+    ifdShort = ifdSingleShort endianness
+    ifdShorts = ifdMultiShort endianness
+
+    list = execWriter $ do
+      ifdSingleLong TagImageWidth $ tiffWidth nfo
+      ifdSingleLong TagImageLength $ tiffHeight nfo
+      ifdShorts TagBitsPerSample $ tiffBitsPerSample nfo
+      ifdSingleLong TagSamplesPerPixel $ tiffSampleCount nfo
+      ifdSingleLong TagRowPerStrip $ tiffRowPerStrip nfo
+      ifdShort TagPhotometricInterpretation
+                                  . packPhotometricInterpretation
+                                  $ tiffColorspace nfo
+      ifdShort TagPlanarConfiguration
+              . constantToPlaneConfiguration $ tiffPlaneConfiguration nfo
+      ifdMultiLong TagSampleFormat
+                                  . V.fromList
+                                  . map packSampleFormat
+                                  $ tiffSampleFormat nfo
+      ifdShort TagCompression . packCompression
+                                    $ tiffCompression nfo
+      ifdMultiLong TagStripOffsets $ tiffOffsets nfo
+
+      ifdMultiLong TagStripByteCounts $ tiffStripSize nfo
+
+      maybe (return ())
+            (ifdShort TagExtraSample . codeOfExtraSample)
+          $ tiffExtraSample nfo
+
+      let subSampling = tiffYCbCrSubsampling nfo
+      unless (V.null subSampling) $
+           ifdShorts TagYCbCrSubsampling subSampling
+
+  getP rawData = do
+    (hdr, cleanedFull :: [[ImageFileDirectory]]) <- getP rawData
+
+    let cleaned = concat cleanedFull
+        dataFind str tag = findIFDData str tag cleaned
+        dataDefault def tag = findIFDDefaultData def tag cleaned
+        extFind str tag = findIFDExt str tag cleaned
+        extDefault def tag = findIFDExtDefaultData def tag cleaned
+
+    TiffInfo hdr
+        <$> dataFind "Can't find width" TagImageWidth
+        <*> dataFind "Can't find height" TagImageLength
+        <*> (dataFind "Can't find color space" TagPhotometricInterpretation
+                     >>= unpackPhotometricInterpretation)
+        <*> dataFind "Can't find sample per pixel" TagSamplesPerPixel
+        <*> dataFind "Can't find row per strip" TagRowPerStrip
+        <*> (dataDefault 1 TagPlanarConfiguration
+                     >>= planarConfgOfConstant)
+        <*> (extDefault [1] TagSampleFormat
+                     >>= mapM unpackSampleFormat)
+        <*> (extFind "Can't find bit per sample" TagBitsPerSample
+                     >>= unLong "Can't find bit depth")
+        <*> (dataFind "Can't find Compression" TagCompression
+                     >>= unPackCompression)
+        <*> (extFind "Can't find byte counts" TagStripByteCounts
+                     >>= unLong "Can't find bit per sample")
+        <*> (extFind "Strip offsets missing" TagStripOffsets
+                     >>= unLong "Can't find strip offsets")
+        <*> findPalette cleaned
+        <*> (V.fromList <$> extDefault [2, 2] TagYCbCrSubsampling)
+        <*> pure Nothing
+        <*> (dataDefault 1 TagPredictor
+                     >>= predictorOfConstant)
+        <*> pure (extractTiffMetadata cleaned)
+
+palette16Of :: Image PixelRGB16 -> Palette' PixelRGB16
+palette16Of p = Palette'
+    { _paletteSize = imageWidth p
+    , _paletteData = imageData p
+    }
+
+unpack :: B.ByteString -> TiffInfo -> Either String PalettedImage
+-- | while mandatory some images don't put correct
+-- rowperstrip. So replacing 0 with actual image height.
+unpack file nfo@TiffInfo { tiffRowPerStrip = 0 } =
+    unpack file $ nfo { tiffRowPerStrip = tiffHeight nfo }
+unpack file nfo@TiffInfo { tiffColorspace = TiffPaleted
+                         , tiffBitsPerSample = lst
+                         , tiffSampleFormat = format
+                         , tiffPalette = Just p
+                         }
+  | lst == V.singleton 8 && format == [TiffSampleUint] =
+      pure . PalettedRGB16 (gatherStrips (0 :: Word8) file nfo) $ palette16Of p
+  | lst == V.singleton 4 && format == [TiffSampleUint] =
+      pure . PalettedRGB16 (gatherStrips Pack4 file nfo) $ palette16Of p
+  | lst == V.singleton 2 && format == [TiffSampleUint] =
+      pure . PalettedRGB16 (gatherStrips Pack2 file nfo) $ palette16Of p
+
+unpack file nfo@TiffInfo { tiffColorspace = TiffCMYK
+                         , tiffBitsPerSample = lst
+                         , tiffSampleFormat = format }
+  | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageCMYK8 $ gatherStrips (0 :: Word8) file nfo
+
+  | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageCMYK16 $ gatherStrips (0 :: Word16) file nfo
+
+unpack file nfo@TiffInfo { tiffColorspace = TiffMonochromeWhite0 } = do
+    img <- unpack file (nfo { tiffColorspace = TiffMonochrome })
+    case img of
+      TrueColorImage (ImageY8 i) -> pure . TrueColorImage . ImageY8 $ pixelMap (maxBound -) i
+      TrueColorImage (ImageY16 i) -> pure . TrueColorImage . ImageY16 $ pixelMap (maxBound -) i
+      TrueColorImage (ImageYA8 i) -> let negative (PixelYA8 y a) = PixelYA8 (maxBound - y) a
+                    in pure . TrueColorImage . ImageYA8 $ pixelMap negative i
+      TrueColorImage (ImageYA16 i) -> let negative (PixelYA16 y a) = PixelYA16 (maxBound - y) a
+                     in pure . TrueColorImage . ImageYA16 $ pixelMap negative i
+      _ -> Left "Unsupported color type used with colorspace MonochromeWhite0"
+
+unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome
+                         , tiffBitsPerSample = lst
+                         , tiffSampleFormat = format }
+  | lst == V.singleton 2 && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageY8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
+  | lst == V.singleton 4 && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageY8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
+  | lst == V.singleton 8 && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageY8 $ gatherStrips (0 :: Word8) file nfo
+  | lst == V.singleton 12 && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageY16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo
+  | lst == V.singleton 16 && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageY16 $ gatherStrips (0 :: Word16) file nfo
+  | lst == V.singleton 32 && all (TiffSampleUint ==) format =
+        let img = gatherStrips (0 :: Word32) file nfo :: Image Pixel32
+        in pure $ TrueColorImage $ ImageY32 $ img
+  | lst == V.singleton 32 && all (TiffSampleFloat ==) format =
+        let img = gatherStrips (0 :: Float) file nfo :: Image PixelF
+        in pure $ TrueColorImage $ ImageYF $ img
+  | lst == V.singleton 64 = Left "Failure to unpack TIFF file, 64-bit samples unsupported."
+  | lst == V.fromList [2, 2] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageYA8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
+  | lst == V.fromList [4, 4] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageYA8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
+  | lst == V.fromList [8, 8] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageYA8 $ gatherStrips (0 :: Word8) file nfo
+  | lst == V.fromList [12, 12] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageYA16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo
+  | lst == V.fromList [16, 16] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageYA16 $ gatherStrips (0 :: Word16) file nfo
+    where
+      expand12to16 x = x `unsafeShiftL` 4 + x `unsafeShiftR` (12 - 4)
+
+unpack file nfo@TiffInfo { tiffColorspace = TiffYCbCr
+                         , tiffBitsPerSample = lst
+                         , tiffPlaneConfiguration = PlanarConfigContig
+                         , tiffSampleFormat = format }
+  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
+    pure . TrueColorImage . ImageYCbCr8 $ gatherStrips cbcrConf  file nfo
+      where defaulting 0 = 2
+            defaulting n = n
+
+            w = defaulting $ tiffYCbCrSubsampling nfo V.! 0
+            h = defaulting $ tiffYCbCrSubsampling nfo V.! 1
+            cbcrConf = YCbCrSubsampling
+                { ycbcrWidth        = fromIntegral w
+                , ycbcrHeight       = fromIntegral h
+                , ycbcrImageWidth   = fromIntegral $ tiffWidth nfo
+                , ycbcrStripHeight  = fromIntegral $ tiffRowPerStrip nfo
+                }
+
+unpack file nfo@TiffInfo { tiffColorspace = TiffRGB
+                         , tiffBitsPerSample = lst
+                         , tiffSampleFormat = format }
+  | lst == V.fromList [2, 2, 2] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGB8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo
+  | lst == V.fromList [4, 4, 4] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGB8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo
+  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo
+  | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGBA8 $ gatherStrips (0 :: Word8) file nfo
+  | lst == V.fromList [16, 16, 16] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGB16 $ gatherStrips (0 :: Word16) file nfo
+  | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGBA16 $ gatherStrips (0 :: Word16) file nfo
+unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome
+                         , tiffBitsPerSample = lst
+                         , tiffSampleFormat = format }
+  -- some files are a little bit borked...
+  | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format =
+        pure . TrueColorImage . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo
+
+unpack _ _ = Left "Failure to unpack TIFF file"
+
+-- | Decode a tiff encoded image while preserving the underlying
+-- pixel type (except for Y32 which is truncated to 16 bits).
+--
+-- This function can output the following images:
+--
+--  * 'ImageY8'
+--
+--  * 'ImageY16'
+--
+--  * 'ImageY32'
+--
+--  * 'ImageYF'
+--
+--  * 'ImageYA8'
+--
+--  * 'ImageYA16'
+--
+--  * 'ImageRGB8'
+--
+--  * 'ImageRGB16'
+--
+--  * 'ImageRGBA8'
+--
+--  * 'ImageRGBA16'
+--
+--  * 'ImageCMYK8'
+--
+--  * 'ImageCMYK16'
+--
+decodeTiff :: B.ByteString -> Either String DynamicImage
+decodeTiff = fmap fst . decodeTiffWithMetadata 
+
+-- | Like 'decodeTiff' but also provides some metadata present
+-- in the Tiff file.
+--
+-- The metadata extracted are the 'Codec.Picture.Metadata.DpiX' &
+-- 'Codec.Picture.Metadata.DpiY' information alongside the EXIF information.
+decodeTiffWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas)
+decodeTiffWithMetadata str = first palettedToTrueColor <$> decodeTiffWithPaletteAndMetadata str
+
+-- | Decode TIFF and provide separated palette and metadata
+decodeTiffWithPaletteAndMetadata :: B.ByteString -> Either String (PalettedImage, Metadatas)
+decodeTiffWithPaletteAndMetadata file = runGetStrict (getP file) file >>= go
+  where
+    go tinfo = (, tiffMetadatas tinfo) <$> unpack file tinfo
+    
+
+-- | Class defining which pixel types can be serialized in a
+-- Tiff file.
+class (Pixel px) => TiffSaveable px where
+  colorSpaceOfPixel :: px -> TiffColorspace
+
+  extraSampleCodeOfPixel :: px -> Maybe ExtraSample
+  extraSampleCodeOfPixel _ = Nothing
+
+  subSamplingInfo   :: px -> V.Vector Word32
+  subSamplingInfo _ = V.empty
+
+  sampleFormat :: px -> [TiffSampleFormat]
+  sampleFormat _ = [TiffSampleUint]
+
+instance TiffSaveable Pixel8 where
+  colorSpaceOfPixel _ = TiffMonochrome
+
+instance TiffSaveable Pixel16 where
+  colorSpaceOfPixel _ = TiffMonochrome
+
+instance TiffSaveable Pixel32 where
+  colorSpaceOfPixel _ = TiffMonochrome
+
+instance TiffSaveable PixelF where
+  colorSpaceOfPixel _ = TiffMonochrome
+  sampleFormat _      = [TiffSampleFloat]
+
+instance TiffSaveable PixelYA8 where
+  colorSpaceOfPixel _ = TiffMonochrome
+  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
+
+instance TiffSaveable PixelYA16 where
+  colorSpaceOfPixel _ = TiffMonochrome
+  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
+
+instance TiffSaveable PixelCMYK8 where
+  colorSpaceOfPixel _ = TiffCMYK
+
+instance TiffSaveable PixelCMYK16 where
+  colorSpaceOfPixel _ = TiffCMYK
+
+instance TiffSaveable PixelRGB8 where
+  colorSpaceOfPixel  _ = TiffRGB
+
+instance TiffSaveable PixelRGB16 where
+  colorSpaceOfPixel  _ = TiffRGB
+
+instance TiffSaveable PixelRGBA8 where
+  colorSpaceOfPixel _ = TiffRGB
+  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
+
+instance TiffSaveable PixelRGBA16 where
+  colorSpaceOfPixel _ = TiffRGB
+  extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha
+
+instance TiffSaveable PixelYCbCr8 where
+  colorSpaceOfPixel _ = TiffYCbCr
+  subSamplingInfo _ = V.fromListN 2 [1, 1]
+
+-- | Transform an image into a Tiff encoded bytestring, ready to be
+-- written as a file.
+encodeTiff :: forall px. (TiffSaveable px) => Image px -> Lb.ByteString
+encodeTiff img = runPut $ putP rawPixelData hdr
+  where intSampleCount = componentCount (undefined :: px)
+        sampleCount = fromIntegral intSampleCount
+
+        sampleType = undefined :: PixelBaseComponent px
+        pixelData = imageData img
+
+        rawPixelData = toByteString pixelData
+        width = fromIntegral $ imageWidth img
+        height = fromIntegral $ imageHeight img
+        intSampleSize = sizeOf sampleType
+        sampleSize = fromIntegral intSampleSize
+        bitPerSample = sampleSize * 8
+        imageSize = width * height * sampleCount * sampleSize
+        headerSize = 8
+
+        hdr = TiffInfo
+            { tiffHeader             = TiffHeader
+                                            { hdrEndianness = EndianLittle
+                                            , hdrOffset = headerSize + imageSize
+                                            }
+            , tiffWidth              = width
+            , tiffHeight             = height
+            , tiffColorspace         = colorSpaceOfPixel (undefined :: px)
+            , tiffSampleCount        = fromIntegral sampleCount
+            , tiffRowPerStrip        = fromIntegral $ imageHeight img
+            , tiffPlaneConfiguration = PlanarConfigContig
+            , tiffSampleFormat       = sampleFormat (undefined :: px)
+            , tiffBitsPerSample      = V.replicate intSampleCount bitPerSample
+            , tiffCompression        = CompressionNone
+            , tiffStripSize          = V.singleton imageSize
+            , tiffOffsets            = V.singleton headerSize
+            , tiffPalette            = Nothing
+            , tiffYCbCrSubsampling   = subSamplingInfo (undefined :: px)
+            , tiffExtraSample        = extraSampleCodeOfPixel (undefined :: px)
+            , tiffPredictor          = PredictorNone -- not used when writing
+            , tiffMetadatas          = mempty
+            }
+
+-- | Helper function to directly write an image as a tiff on disk.
+writeTiff :: (TiffSaveable pixel) => FilePath -> Image pixel -> IO ()
+writeTiff path img = Lb.writeFile path $ encodeTiff img
+
+{-# ANN module "HLint: ignore Reduce duplication" #-}
+
diff --git a/src/Codec/Picture/Tiff/Internal/Metadata.hs b/src/Codec/Picture/Tiff/Internal/Metadata.hs
--- a/src/Codec/Picture/Tiff/Internal/Metadata.hs
+++ b/src/Codec/Picture/Tiff/Internal/Metadata.hs
@@ -1,239 +1,239 @@
-{-# LANGUAGE CPP #-}
-module Codec.Picture.Tiff.Internal.Metadata
-    ( extractTiffMetadata
-    , encodeTiffStringMetadata
-    , exifOffsetIfd
-    ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Data.Monoid( mempty )
-import Data.Foldable( foldMap )
-import Control.Applicative( (<$>) )
-#endif
-
-import Data.Bits( unsafeShiftL, (.|.) )
-import Data.Foldable( find )
-import Data.List( sortBy )
-import Data.Function( on )
-import qualified Data.Foldable as F
-#if !MIN_VERSION_base(4,11,0)
-import Data.Monoid( (<>) )
-#endif
-import Codec.Picture.Metadata( Metadatas )
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Char8 as BC
-import qualified Codec.Picture.Metadata as Met
-import qualified Data.Vector.Generic as V
-import Codec.Picture.Tiff.Internal.Types
-import Codec.Picture.Metadata( extractExifMetas )
-import Codec.Picture.Metadata.Exif
-
-exifOffsetIfd :: ImageFileDirectory
-exifOffsetIfd = ImageFileDirectory
-  { ifdIdentifier = TagExifOffset
-  , ifdCount = 1
-  , ifdType = TypeLong
-  , ifdOffset = 0
-  , ifdExtended = ExifNone
-  }
-
-typeOfData :: ExifData -> IfdType
-typeOfData d = case d of
-  ExifNone -> error "Impossible - typeOfData : ExifNone"
-  ExifIFD _exifs -> error "Impossible - typeOfData : ExifIFD"
-  ExifLong _l -> TypeLong
-  ExifLongs _l -> TypeLong
-  ExifShort _s -> TypeShort
-  ExifShorts _s -> TypeShort
-  ExifString _str -> TypeAscii
-  ExifUndefined _undef -> TypeUndefined
-  ExifRational _r1 _r2 -> TypeRational
-  ExifSignedRational _sr1 _sr2 -> TypeSignedRational
-
-makeIfd :: ExifTag -> ExifData -> ImageFileDirectory
-makeIfd t (ExifShort v) = ImageFileDirectory
-  { ifdIdentifier = t
-  , ifdType = TypeShort
-  , ifdCount = 1
-  , ifdOffset = fromIntegral v `unsafeShiftL` 16
-  , ifdExtended = ExifNone
-  }
-makeIfd t (ExifLong v) = ImageFileDirectory 
-  { ifdIdentifier = t
-  , ifdType = TypeLong
-  , ifdCount = 1
-  , ifdOffset = fromIntegral v
-  , ifdExtended = ExifNone
-  }
-makeIfd t d@(ExifShorts v)
-  | size == 2 = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeShort
-    , ifdCount = 2
-    , ifdOffset = combined
-    , ifdExtended = ExifNone
-    }
-  | otherwise = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeShort
-    , ifdCount = size
-    , ifdOffset = 0
-    , ifdExtended = d
-    }
-  where
-    size = fromIntegral $ F.length v
-    at i = fromIntegral $ v V.! i
-    combined = (at 0  `unsafeShiftL` 16) .|. at 1
-makeIfd t d@(ExifLongs v)
-  | size == 1 = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeLong
-    , ifdCount = 1
-    , ifdOffset = v V.! 0
-    , ifdExtended = ExifNone
-    }
-  | otherwise = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeLong
-    , ifdCount = size
-    , ifdOffset = 0
-    , ifdExtended = d
-    }
-  where size = fromIntegral $ F.length v
-makeIfd t s@(ExifString str) = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeAscii
-    , ifdCount = fromIntegral $ BC.length str
-    , ifdOffset = 0
-    , ifdExtended = s
-    }
-makeIfd t s@(ExifUndefined str)
-  | size > 4 = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeUndefined
-    , ifdCount = size
-    , ifdOffset = 0
-    , ifdExtended = s
-    }
-  | otherwise = ImageFileDirectory
-    { ifdIdentifier = t
-    , ifdType = TypeUndefined
-    , ifdCount = size
-    , ifdOffset = ofs
-    , ifdExtended = ExifNone
-    }
-  where
-    size = fromIntegral $ BC.length str
-    at ix
-      | fromIntegral ix < size = fromIntegral $ B.index str ix `unsafeShiftL` (4 - (8 * ix))
-      | otherwise = 0
-    ofs = at 0 .|. at 1 .|. at 2 .|. at 3
-makeIfd t d = ImageFileDirectory
-  { ifdIdentifier = t
-  , ifdType = typeOfData d
-  , ifdCount = 1
-  , ifdOffset = 0
-  , ifdExtended = d
-  }
-
-encodeTiffStringMetadata :: Metadatas -> [ImageFileDirectory]
-encodeTiffStringMetadata metas = sortBy (compare `on` word16OfTag . ifdIdentifier) $ allTags where
-  keyStr tag k = case Met.lookup k metas of
-    Nothing -> mempty
-    Just v -> pure . makeIfd tag . ExifString $ BC.pack v
-  allTags = copyright <> artist <> title <> description <> software <> allPureExif
-
-  allPureExif = fmap (uncurry makeIfd) $ extractExifMetas metas
-
-  copyright = keyStr TagCopyright Met.Copyright
-  artist = keyStr TagArtist Met.Author
-  title = keyStr TagDocumentName Met.Title
-  description = keyStr TagImageDescription Met.Description
-  software = keyStr TagSoftware Met.Software
-
-extractTiffStringMetadata :: [ImageFileDirectory] -> Metadatas
-extractTiffStringMetadata = Met.insert Met.Format Met.SourceTiff . foldMap go where
-  strMeta k = Met.singleton k . BC.unpack
-  exif ifd =
-    Met.singleton (Met.Exif $ ifdIdentifier ifd) $ ifdExtended ifd
-  inserter acc (k, v) = Met.insert (Met.Exif k) v acc
-  exifShort ifd =
-    Met.singleton (Met.Exif $ ifdIdentifier ifd) . (ExifShort . fromIntegral) $ ifdOffset ifd
-
-  go :: ImageFileDirectory -> Metadatas
-  go ifd = case (ifdIdentifier ifd, ifdExtended ifd) of
-    (TagArtist, ExifString v) -> strMeta Met.Author v
-    (TagBitsPerSample, _) -> mempty
-    (TagColorMap, _) -> mempty
-    (TagCompression, _) -> mempty
-    (TagCopyright, ExifString v) -> strMeta Met.Copyright v
-    (TagDocumentName, ExifString v) -> strMeta Met.Title v
-    (TagExifOffset, ExifIFD lst) -> F.foldl' inserter mempty lst
-    (TagImageDescription, ExifString v) -> strMeta Met.Description v
-    (TagImageLength, _) -> Met.singleton Met.Height . fromIntegral $ ifdOffset ifd
-    (TagImageWidth, _) -> Met.singleton Met.Width . fromIntegral $ ifdOffset ifd
-    (TagJPEGACTables, _) -> mempty
-    (TagJPEGDCTables, _) -> mempty
-    (TagJPEGInterchangeFormat, _) -> mempty
-    (TagJPEGInterchangeFormatLength, _) -> mempty
-    (TagJPEGLosslessPredictors, _) -> mempty
-    (TagJPEGPointTransforms, _) -> mempty
-    (TagJPEGQTables, _) -> mempty
-    (TagJPEGRestartInterval, _) -> mempty
-    (TagJpegProc, _) -> mempty
-    (TagModel, v) -> Met.singleton (Met.Exif TagModel) v
-    (TagMake, v) -> Met.singleton (Met.Exif TagMake) v
-    (TagOrientation, _) -> exifShort ifd
-    (TagResolutionUnit, _) -> mempty
-    (TagRowPerStrip, _) -> mempty
-    (TagSamplesPerPixel, _) -> mempty
-    (TagSoftware, ExifString v) -> strMeta Met.Software v
-    (TagStripByteCounts, _) -> mempty
-    (TagStripOffsets, _) -> mempty
-    (TagTileByteCount, _) -> mempty
-    (TagTileLength, _) -> mempty
-    (TagTileOffset, _) -> mempty
-    (TagTileWidth, _) -> mempty
-    (TagUnknown _, _) -> exif ifd
-    (TagXResolution, _) -> mempty
-    (TagYCbCrCoeff, _) -> mempty
-    (TagYCbCrPositioning, _) -> mempty
-    (TagYCbCrSubsampling, _) -> mempty
-    (TagYResolution, _) -> mempty
-    _ -> mempty
-
-byTag :: ExifTag -> ImageFileDirectory -> Bool
-byTag t ifd = ifdIdentifier ifd == t
-
-data TiffResolutionUnit
-  = ResolutionUnitUnknown
-  | ResolutionUnitInch
-  | ResolutionUnitCentimeter
-
-unitOfIfd :: ImageFileDirectory -> TiffResolutionUnit
-unitOfIfd ifd = case (ifdType ifd, ifdOffset ifd) of
-  (TypeShort, 1) -> ResolutionUnitUnknown
-  (TypeShort, 2) -> ResolutionUnitInch
-  (TypeShort, 3) -> ResolutionUnitCentimeter
-  _ -> ResolutionUnitUnknown
-
-extractTiffDpiMetadata :: [ImageFileDirectory] -> Metadatas
-extractTiffDpiMetadata lst = go where
-  go = case unitOfIfd <$> find (byTag TagResolutionUnit) lst of
-    Nothing -> mempty
-    Just ResolutionUnitUnknown -> mempty
-    Just ResolutionUnitCentimeter -> findDpis Met.dotsPerCentiMeterToDotPerInch mempty
-    Just ResolutionUnitInch -> findDpis id mempty
-
-  findDpis toDpi =
-     findDpi Met.DpiX TagXResolution toDpi . findDpi Met.DpiY TagYResolution toDpi
-
-  findDpi k tag toDpi metas = case find (byTag tag) lst of
-    Nothing -> metas
-    Just ImageFileDirectory { ifdExtended = ExifRational num den } ->
-      Met.insert k (toDpi . fromIntegral $ num `div` den) metas
-    Just _ -> metas
-
-extractTiffMetadata :: [ImageFileDirectory] -> Metadatas
-extractTiffMetadata lst = extractTiffDpiMetadata lst <> extractTiffStringMetadata lst
-
+{-# LANGUAGE CPP #-}
+module Codec.Picture.Tiff.Internal.Metadata
+    ( extractTiffMetadata
+    , encodeTiffStringMetadata
+    , exifOffsetIfd
+    ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Data.Monoid( mempty )
+import Data.Foldable( foldMap )
+import Control.Applicative( (<$>) )
+#endif
+
+import Data.Bits( unsafeShiftL, (.|.) )
+import Data.Foldable( find )
+import Data.List( sortBy )
+import Data.Function( on )
+import qualified Data.Foldable as F
+#if !MIN_VERSION_base(4,11,0)
+import Data.Monoid( (<>) )
+#endif
+import Codec.Picture.Metadata( Metadatas )
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as BC
+import qualified Codec.Picture.Metadata as Met
+import qualified Data.Vector.Generic as V
+import Codec.Picture.Tiff.Internal.Types
+import Codec.Picture.Metadata( extractExifMetas )
+import Codec.Picture.Metadata.Exif
+
+exifOffsetIfd :: ImageFileDirectory
+exifOffsetIfd = ImageFileDirectory
+  { ifdIdentifier = TagExifOffset
+  , ifdCount = 1
+  , ifdType = TypeLong
+  , ifdOffset = 0
+  , ifdExtended = ExifNone
+  }
+
+typeOfData :: ExifData -> IfdType
+typeOfData d = case d of
+  ExifNone -> error "Impossible - typeOfData : ExifNone"
+  ExifIFD _exifs -> error "Impossible - typeOfData : ExifIFD"
+  ExifLong _l -> TypeLong
+  ExifLongs _l -> TypeLong
+  ExifShort _s -> TypeShort
+  ExifShorts _s -> TypeShort
+  ExifString _str -> TypeAscii
+  ExifUndefined _undef -> TypeUndefined
+  ExifRational _r1 _r2 -> TypeRational
+  ExifSignedRational _sr1 _sr2 -> TypeSignedRational
+
+makeIfd :: ExifTag -> ExifData -> ImageFileDirectory
+makeIfd t (ExifShort v) = ImageFileDirectory
+  { ifdIdentifier = t
+  , ifdType = TypeShort
+  , ifdCount = 1
+  , ifdOffset = fromIntegral v `unsafeShiftL` 16
+  , ifdExtended = ExifNone
+  }
+makeIfd t (ExifLong v) = ImageFileDirectory 
+  { ifdIdentifier = t
+  , ifdType = TypeLong
+  , ifdCount = 1
+  , ifdOffset = fromIntegral v
+  , ifdExtended = ExifNone
+  }
+makeIfd t d@(ExifShorts v)
+  | size == 2 = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeShort
+    , ifdCount = 2
+    , ifdOffset = combined
+    , ifdExtended = ExifNone
+    }
+  | otherwise = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeShort
+    , ifdCount = size
+    , ifdOffset = 0
+    , ifdExtended = d
+    }
+  where
+    size = fromIntegral $ F.length v
+    at i = fromIntegral $ v V.! i
+    combined = (at 0  `unsafeShiftL` 16) .|. at 1
+makeIfd t d@(ExifLongs v)
+  | size == 1 = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeLong
+    , ifdCount = 1
+    , ifdOffset = v V.! 0
+    , ifdExtended = ExifNone
+    }
+  | otherwise = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeLong
+    , ifdCount = size
+    , ifdOffset = 0
+    , ifdExtended = d
+    }
+  where size = fromIntegral $ F.length v
+makeIfd t s@(ExifString str) = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeAscii
+    , ifdCount = fromIntegral $ BC.length str
+    , ifdOffset = 0
+    , ifdExtended = s
+    }
+makeIfd t s@(ExifUndefined str)
+  | size > 4 = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeUndefined
+    , ifdCount = size
+    , ifdOffset = 0
+    , ifdExtended = s
+    }
+  | otherwise = ImageFileDirectory
+    { ifdIdentifier = t
+    , ifdType = TypeUndefined
+    , ifdCount = size
+    , ifdOffset = ofs
+    , ifdExtended = ExifNone
+    }
+  where
+    size = fromIntegral $ BC.length str
+    at ix
+      | fromIntegral ix < size = fromIntegral $ B.index str ix `unsafeShiftL` (4 - (8 * ix))
+      | otherwise = 0
+    ofs = at 0 .|. at 1 .|. at 2 .|. at 3
+makeIfd t d = ImageFileDirectory
+  { ifdIdentifier = t
+  , ifdType = typeOfData d
+  , ifdCount = 1
+  , ifdOffset = 0
+  , ifdExtended = d
+  }
+
+encodeTiffStringMetadata :: Metadatas -> [ImageFileDirectory]
+encodeTiffStringMetadata metas = sortBy (compare `on` word16OfTag . ifdIdentifier) $ allTags where
+  keyStr tag k = case Met.lookup k metas of
+    Nothing -> mempty
+    Just v -> pure . makeIfd tag . ExifString $ BC.pack v
+  allTags = copyright <> artist <> title <> description <> software <> allPureExif
+
+  allPureExif = fmap (uncurry makeIfd) $ extractExifMetas metas
+
+  copyright = keyStr TagCopyright Met.Copyright
+  artist = keyStr TagArtist Met.Author
+  title = keyStr TagDocumentName Met.Title
+  description = keyStr TagImageDescription Met.Description
+  software = keyStr TagSoftware Met.Software
+
+extractTiffStringMetadata :: [ImageFileDirectory] -> Metadatas
+extractTiffStringMetadata = Met.insert Met.Format Met.SourceTiff . foldMap go where
+  strMeta k = Met.singleton k . BC.unpack
+  exif ifd =
+    Met.singleton (Met.Exif $ ifdIdentifier ifd) $ ifdExtended ifd
+  inserter acc (k, v) = Met.insert (Met.Exif k) v acc
+  exifShort ifd =
+    Met.singleton (Met.Exif $ ifdIdentifier ifd) . (ExifShort . fromIntegral) $ ifdOffset ifd
+
+  go :: ImageFileDirectory -> Metadatas
+  go ifd = case (ifdIdentifier ifd, ifdExtended ifd) of
+    (TagArtist, ExifString v) -> strMeta Met.Author v
+    (TagBitsPerSample, _) -> mempty
+    (TagColorMap, _) -> mempty
+    (TagCompression, _) -> mempty
+    (TagCopyright, ExifString v) -> strMeta Met.Copyright v
+    (TagDocumentName, ExifString v) -> strMeta Met.Title v
+    (TagExifOffset, ExifIFD lst) -> F.foldl' inserter mempty lst
+    (TagImageDescription, ExifString v) -> strMeta Met.Description v
+    (TagImageLength, _) -> Met.singleton Met.Height . fromIntegral $ ifdOffset ifd
+    (TagImageWidth, _) -> Met.singleton Met.Width . fromIntegral $ ifdOffset ifd
+    (TagJPEGACTables, _) -> mempty
+    (TagJPEGDCTables, _) -> mempty
+    (TagJPEGInterchangeFormat, _) -> mempty
+    (TagJPEGInterchangeFormatLength, _) -> mempty
+    (TagJPEGLosslessPredictors, _) -> mempty
+    (TagJPEGPointTransforms, _) -> mempty
+    (TagJPEGQTables, _) -> mempty
+    (TagJPEGRestartInterval, _) -> mempty
+    (TagJpegProc, _) -> mempty
+    (TagModel, v) -> Met.singleton (Met.Exif TagModel) v
+    (TagMake, v) -> Met.singleton (Met.Exif TagMake) v
+    (TagOrientation, _) -> exifShort ifd
+    (TagResolutionUnit, _) -> mempty
+    (TagRowPerStrip, _) -> mempty
+    (TagSamplesPerPixel, _) -> mempty
+    (TagSoftware, ExifString v) -> strMeta Met.Software v
+    (TagStripByteCounts, _) -> mempty
+    (TagStripOffsets, _) -> mempty
+    (TagTileByteCount, _) -> mempty
+    (TagTileLength, _) -> mempty
+    (TagTileOffset, _) -> mempty
+    (TagTileWidth, _) -> mempty
+    (TagUnknown _, _) -> exif ifd
+    (TagXResolution, _) -> mempty
+    (TagYCbCrCoeff, _) -> mempty
+    (TagYCbCrPositioning, _) -> mempty
+    (TagYCbCrSubsampling, _) -> mempty
+    (TagYResolution, _) -> mempty
+    _ -> mempty
+
+byTag :: ExifTag -> ImageFileDirectory -> Bool
+byTag t ifd = ifdIdentifier ifd == t
+
+data TiffResolutionUnit
+  = ResolutionUnitUnknown
+  | ResolutionUnitInch
+  | ResolutionUnitCentimeter
+
+unitOfIfd :: ImageFileDirectory -> TiffResolutionUnit
+unitOfIfd ifd = case (ifdType ifd, ifdOffset ifd) of
+  (TypeShort, 1) -> ResolutionUnitUnknown
+  (TypeShort, 2) -> ResolutionUnitInch
+  (TypeShort, 3) -> ResolutionUnitCentimeter
+  _ -> ResolutionUnitUnknown
+
+extractTiffDpiMetadata :: [ImageFileDirectory] -> Metadatas
+extractTiffDpiMetadata lst = go where
+  go = case unitOfIfd <$> find (byTag TagResolutionUnit) lst of
+    Nothing -> mempty
+    Just ResolutionUnitUnknown -> mempty
+    Just ResolutionUnitCentimeter -> findDpis Met.dotsPerCentiMeterToDotPerInch mempty
+    Just ResolutionUnitInch -> findDpis id mempty
+
+  findDpis toDpi =
+     findDpi Met.DpiX TagXResolution toDpi . findDpi Met.DpiY TagYResolution toDpi
+
+  findDpi k tag toDpi metas = case find (byTag tag) lst of
+    Nothing -> metas
+    Just ImageFileDirectory { ifdExtended = ExifRational num den } ->
+      Met.insert k (toDpi . fromIntegral $ num `div` den) metas
+    Just _ -> metas
+
+extractTiffMetadata :: [ImageFileDirectory] -> Metadatas
+extractTiffMetadata lst = extractTiffDpiMetadata lst <> extractTiffStringMetadata lst
+
diff --git a/src/Codec/Picture/Tiff/Internal/Types.hs b/src/Codec/Picture/Tiff/Internal/Types.hs
--- a/src/Codec/Picture/Tiff/Internal/Types.hs
+++ b/src/Codec/Picture/Tiff/Internal/Types.hs
@@ -1,504 +1,504 @@
-{-# LANGUAGE CPP #-}
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE FlexibleInstances #-}
-{-# LANGUAGE FlexibleContexts #-}
-module Codec.Picture.Tiff.Internal.Types
-    ( BinaryParam( .. )
-    , Endianness( .. )
-    , TiffHeader( .. )
-    , TiffPlanarConfiguration( .. )
-    , TiffCompression( .. )
-    , IfdType( .. )
-    , TiffColorspace( .. )
-    , TiffSampleFormat( .. )
-    , ImageFileDirectory( .. )
-    , ExtraSample( .. )
-    , Predictor( .. )
-
-    , planarConfgOfConstant
-    , constantToPlaneConfiguration
-    , unpackSampleFormat
-    , packSampleFormat
-    , word16OfTag
-    , unpackPhotometricInterpretation
-    , packPhotometricInterpretation
-    , codeOfExtraSample
-    , unPackCompression
-    , packCompression 
-    , predictorOfConstant
-    ) where
-
-#if !MIN_VERSION_base(4,8,0)
-import Control.Applicative( (<$>), (<*>), pure )
-#endif
-
-import Control.DeepSeq( NFData(..) )
-import Control.Monad( forM_, when, replicateM, )
-import Data.Bits( (.&.), unsafeShiftR )
-import Data.Binary( Binary( .. ) )
-import Data.Binary.Get( Get
-                      , getWord16le, getWord16be
-                      , getWord32le, getWord32be
-                      , bytesRead
-                      , skip
-                      , getByteString
-                      )
-import Data.Binary.Put( Put
-                      , putWord16le, putWord16be
-                      , putWord32le, putWord32be
-                      , putByteString
-                      )
-import Data.Function( on )
-import Data.List( sortBy, mapAccumL )
-import qualified Data.Vector as V
-import qualified Data.ByteString as B
-import Data.Int( Int32 )
-import Data.Word( Word8, Word16, Word32 )
-import GHC.Generics( Generic )
-
-import Codec.Picture.Metadata.Exif
-{-import Debug.Trace-}
-
-data Endianness
-  = EndianLittle
-  | EndianBig
-  deriving (Eq, Show)
-
-instance Binary Endianness where
-  put EndianLittle = putWord16le 0x4949
-  put EndianBig = putWord16le 0x4D4D
-
-  get = do
-    tag <- getWord16le
-    case tag of
-      0x4949 -> return EndianLittle
-      0x4D4D -> return EndianBig
-      _ -> fail "Invalid endian tag value"
-
--- | Because having a polymorphic get with endianness is to nice
--- to pass on, introducing this helper type class, which is just
--- a superset of Binary, but formalising a parameter passing
--- into it.
-class BinaryParam a b where
-  getP :: a -> Get b
-  putP :: a -> b -> Put
-
-data TiffHeader = TiffHeader
-  { hdrEndianness :: !Endianness
-  , hdrOffset     :: {-# UNPACK #-} !Word32
-  }
-  deriving (Eq, Show)
-
-instance BinaryParam Endianness Word16 where
-  putP EndianLittle = putWord16le
-  putP EndianBig = putWord16be
-
-  getP EndianLittle = getWord16le
-  getP EndianBig = getWord16be
-
-instance BinaryParam Endianness Int32 where
-  putP en v = putP en $ (fromIntegral v :: Word32)
-  getP en = fromIntegral <$> (getP en :: Get Word32) 
-
-instance BinaryParam Endianness Word32 where
-  putP EndianLittle = putWord32le
-  putP EndianBig = putWord32be
-
-  getP EndianLittle = getWord32le
-  getP EndianBig = getWord32be
-
-instance Binary TiffHeader where
-  put hdr = do
-    let endian = hdrEndianness hdr
-    put endian
-    putP endian (42 :: Word16)
-    putP endian $ hdrOffset hdr
-
-  get = do
-    endian <- get
-    magic <- getP endian
-    let magicValue = 42 :: Word16
-    when (magic /= magicValue)
-         (fail "Invalid TIFF magic number")
-    TiffHeader endian <$> getP endian
-
-data TiffPlanarConfiguration
-  = PlanarConfigContig    -- = 1
-  | PlanarConfigSeparate  -- = 2
-
-planarConfgOfConstant :: Word32 -> Get TiffPlanarConfiguration
-planarConfgOfConstant 0 = pure PlanarConfigContig
-planarConfgOfConstant 1 = pure PlanarConfigContig
-planarConfgOfConstant 2 = pure PlanarConfigSeparate
-planarConfgOfConstant v = fail $ "Unknown planar constant (" ++ show v ++ ")"
-
-constantToPlaneConfiguration :: TiffPlanarConfiguration -> Word16
-constantToPlaneConfiguration PlanarConfigContig = 1
-constantToPlaneConfiguration PlanarConfigSeparate = 2
-
-data TiffCompression
-  = CompressionNone           -- 1
-  | CompressionModifiedRLE    -- 2
-  | CompressionLZW            -- 5
-  | CompressionJPEG           -- 6
-  | CompressionPackBit        -- 32273
-
-data IfdType
-  = TypeByte
-  | TypeAscii
-  | TypeShort
-  | TypeLong
-  | TypeRational
-  | TypeSByte
-  | TypeUndefined
-  | TypeSignedShort
-  | TypeSignedLong
-  | TypeSignedRational
-  | TypeFloat
-  | TypeDouble
-  deriving (Eq, Show, Generic)
-instance NFData IfdType
-
-instance BinaryParam Endianness IfdType where
-    getP endianness = getP endianness >>= conv where
-      conv :: Word16 -> Get IfdType
-      conv v = case v of
-        1  -> return TypeByte
-        2  -> return TypeAscii
-        3  -> return TypeShort
-        4  -> return TypeLong
-        5  -> return TypeRational
-        6  -> return TypeSByte
-        7  -> return TypeUndefined
-        8  -> return TypeSignedShort
-        9  -> return TypeSignedLong
-        10 -> return TypeSignedRational
-        11 -> return TypeFloat
-        12 -> return TypeDouble
-        _  -> fail "Invalid TIF directory type"
-
-    putP endianness = putP endianness . conv where
-      conv :: IfdType -> Word16
-      conv v = case v of
-        TypeByte -> 1
-        TypeAscii -> 2
-        TypeShort -> 3
-        TypeLong -> 4
-        TypeRational -> 5
-        TypeSByte -> 6
-        TypeUndefined -> 7
-        TypeSignedShort -> 8
-        TypeSignedLong -> 9
-        TypeSignedRational -> 10
-        TypeFloat -> 11
-        TypeDouble -> 12
-
-instance BinaryParam Endianness ExifTag where
-  getP endianness = tagOfWord16 <$> getP endianness
-  putP endianness = putP endianness . word16OfTag
-
-data Predictor
-  = PredictorNone                   -- 1
-  | PredictorHorizontalDifferencing -- 2
-  deriving Eq
-
-predictorOfConstant :: Word32 -> Get Predictor
-predictorOfConstant 1 = pure PredictorNone
-predictorOfConstant 2 = pure PredictorHorizontalDifferencing
-predictorOfConstant v = fail $ "Unknown predictor (" ++ show v ++ ")"
-
-paddWrite :: B.ByteString -> Put
-paddWrite str = putByteString str >> padding where
-  zero = 0 :: Word8
-  padding = when (odd (B.length str)) $ put zero
-
-instance BinaryParam (Endianness, Int, ImageFileDirectory) ExifData where
-  putP (endianness, _, _) = dump
-    where
-      dump ExifNone = pure ()
-      dump (ExifLong _) = pure ()
-      dump (ExifShort _) = pure ()
-      dump (ExifIFD _) = pure ()
-      dump (ExifString bstr) = paddWrite bstr
-      dump (ExifUndefined bstr) = paddWrite bstr
-      -- wrong if length == 2
-      dump (ExifShorts shorts) = V.mapM_ (putP endianness) shorts
-      dump (ExifLongs longs) = V.mapM_ (putP endianness) longs
-      dump (ExifRational a b) = putP endianness a >> putP endianness b
-      dump (ExifSignedRational a b) = putP endianness a >> putP endianness b
-
-  getP (endianness, maxi, ifd) = fetcher ifd
-    where
-      align ImageFileDirectory { ifdOffset = offset } act = do
-        readed <- bytesRead
-        let delta = fromIntegral offset - readed
-        if offset >= fromIntegral maxi || fromIntegral readed > offset then
-          pure ExifNone
-        else do
-          skip $ fromIntegral delta
-          act
-
-      getE :: (BinaryParam Endianness a) => Get a
-      getE = getP endianness
-
-      getVec count = V.replicateM (fromIntegral count)
-
-      immediateBytes ofs =
-        let bytes = [fromIntegral $ (ofs .&. 0xFF000000) `unsafeShiftR` (3 * 8)
-                    ,fromIntegral $ (ofs .&. 0x00FF0000) `unsafeShiftR` (2 * 8)
-                    ,fromIntegral $ (ofs .&. 0x0000FF00) `unsafeShiftR` (1 * 8)
-                    ,fromIntegral $  ofs .&. 0x000000FF
-                    ]
-        in case endianness of
-             EndianLittle -> reverse bytes
-             EndianBig    -> bytes
-
-      fetcher ImageFileDirectory { ifdIdentifier = TagExifOffset
-                                 , ifdType = TypeLong
-                                 , ifdCount = 1 } = do
-         align ifd $ do
-            let byOffset = sortBy (compare `on` ifdOffset)
-                cleansIfds = fmap (cleanImageFileDirectory endianness)
-            subIfds <- cleansIfds . byOffset <$> getP endianness
-            cleaned <- fetchExtended endianness maxi $ sortBy (compare `on` ifdOffset) subIfds
-            pure $ ExifIFD [(ifdIdentifier fd, ifdExtended fd) | fd <- cleaned]
-         {-  
-      fetcher ImageFileDirectory { ifdIdentifier = TagGPSInfo
-                                 , ifdType = TypeLong
-                                 , ifdCount = 1 } = do
-         align ifd 
-         subIfds <- fmap (cleanImageFileDirectory endianness) <$> getP endianness
-         cleaned <- fetchExtended endianness subIfds
-         pure $ ExifIFD [(ifdIdentifier fd, ifdExtended fd) | fd <- cleaned]
-        -}
-      fetcher ImageFileDirectory { ifdType = TypeUndefined, ifdCount = count } | count > 4 =
-         align ifd $ ExifUndefined <$> getByteString (fromIntegral count)
-      fetcher ImageFileDirectory { ifdType = TypeUndefined, ifdOffset = ofs } =
-          pure . ExifUndefined . B.pack $ take (fromIntegral $ ifdCount ifd)
-              (immediateBytes ofs)
-      fetcher ImageFileDirectory { ifdType = TypeAscii, ifdCount = count } | count > 4 =
-          align ifd $ ExifString <$> getByteString (fromIntegral count)
-      fetcher ImageFileDirectory { ifdType = TypeAscii, ifdOffset = ofs } =
-          pure . ExifString . B.pack $ take (fromIntegral $ ifdCount ifd)
-              (immediateBytes ofs)
-      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = 2, ifdOffset = ofs } =
-          pure . ExifShorts $ V.fromListN 2 valList
-            where high = fromIntegral $ ofs `unsafeShiftR` 16
-                  low = fromIntegral $ ofs .&. 0xFFFF
-                  valList = case endianness of
-                    EndianLittle -> [low, high]
-                    EndianBig -> [high, low]
-      fetcher ImageFileDirectory { ifdType = TypeRational, ifdCount = 1 } = do
-          align ifd $ ExifRational <$> getP EndianLittle <*> getP EndianLittle
-      fetcher ImageFileDirectory { ifdType = TypeSignedRational, ifdCount = 1 } = do
-          align ifd $ ExifSignedRational <$> getP EndianLittle <*> getP EndianLittle
-      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = 1 } =
-          pure . ExifShort . fromIntegral $ ifdOffset ifd
-      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = count } | count > 2 =
-          align ifd $ ExifShorts <$> getVec count getE
-      fetcher ImageFileDirectory { ifdType = TypeLong, ifdCount = 1 } =
-          pure . ExifLong . fromIntegral $ ifdOffset ifd
-      fetcher ImageFileDirectory { ifdType = TypeLong, ifdCount = count } | count > 1 =
-          align ifd $ ExifLongs <$> getVec count getE
-      fetcher _ = pure ExifNone
-
-cleanImageFileDirectory :: Endianness -> ImageFileDirectory -> ImageFileDirectory
-cleanImageFileDirectory EndianBig ifd@(ImageFileDirectory { ifdCount = 1 }) = aux $ ifdType ifd
-  where
-    aux TypeShort = ifd { ifdOffset = ifdOffset ifd `unsafeShiftR` 16 }
-    aux _ = ifd
-cleanImageFileDirectory _ ifd = ifd
-
-fetchExtended :: Endianness -> Int -> [ImageFileDirectory] -> Get [ImageFileDirectory]
-fetchExtended endian maxi = mapM $ \ifd -> do
-  v <- getP (endian, maxi, ifd)
-  pure $ ifd { ifdExtended = v }
-
--- | All the IFD must be written in order according to the tag
--- value of the IFD. To avoid getting to much restriction in the
--- serialization code, just sort it.
-orderIfdByTag :: [ImageFileDirectory] -> [ImageFileDirectory]
-orderIfdByTag = sortBy comparer where
-  comparer a b = compare t1 t2 where
-    t1 = word16OfTag $ ifdIdentifier a
-    t2 = word16OfTag $ ifdIdentifier b
-
--- | Given an official offset and a list of IFD, update the offset information
--- of the IFD with extended data.
-setupIfdOffsets :: Word32 -> [ImageFileDirectory] -> (Word32, [ImageFileDirectory])
-setupIfdOffsets initialOffset lst = mapAccumL updater startExtended lst
-  where ifdElementCount = fromIntegral $ length lst
-        ifdSize = 12
-        ifdCountSize = 2
-        nextOffsetSize = 4
-        startExtended = initialOffset
-                     + ifdElementCount * ifdSize
-                     + ifdCountSize + nextOffsetSize
-
-        paddedSize blob = fromIntegral $ blobLength + padding where
-          blobLength = B.length blob
-          padding = if odd blobLength then 1 else 0
-
-        updater ix ifd@(ImageFileDirectory { ifdIdentifier = TagExifOffset }) =
-            (ix, ifd { ifdOffset = ix } )
-        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifUndefined b }) =
-            (ix + paddedSize b, ifd { ifdOffset = ix } )
-        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifString b }) =
-            (ix + paddedSize b, ifd { ifdOffset = ix } )
-        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifLongs v })
-            | V.length v > 1 = ( ix + fromIntegral (V.length v * 4)
-                               , ifd { ifdOffset = ix } )
-        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifShorts v })
-            | V.length v > 2 = ( ix + fromIntegral (V.length v * 2)
-                             , ifd { ifdOffset = ix })
-        updater ix ifd = (ix, ifd)
-
-instance BinaryParam B.ByteString (TiffHeader, [[ImageFileDirectory]]) where
-  putP rawData (hdr, ifds) = do
-    put hdr
-    putByteString rawData
-    let endianness = hdrEndianness hdr
-        (_, offseted) = mapAccumL
-            (\ix ifd -> setupIfdOffsets ix $ orderIfdByTag ifd)
-            (hdrOffset hdr)
-            ifds
-    forM_ offseted $ \list -> do
-        putP endianness list
-        mapM_ (\field -> putP (endianness, (0::Int), field) $ ifdExtended field) list
-
-  getP raw = do
-    hdr <- get
-    readed <- bytesRead
-    skip . fromIntegral $ fromIntegral (hdrOffset hdr) - readed
-    let endian = hdrEndianness hdr
-        byOffset = sortBy (compare `on` ifdOffset)
-        cleanIfds = fmap (cleanImageFileDirectory endian)
-
-    ifd <-  cleanIfds . byOffset <$> getP endian
-    cleaned <- fetchExtended endian (B.length raw) ifd
-    return (hdr, [cleaned])
-
-data TiffSampleFormat
-  = TiffSampleUint
-  | TiffSampleInt
-  | TiffSampleFloat
-  | TiffSampleUnknown
-  deriving Eq
-
-unpackSampleFormat :: Word32 -> Get TiffSampleFormat
-unpackSampleFormat v = case v of
-  1 -> pure TiffSampleUint
-  2 -> pure TiffSampleInt
-  3 -> pure TiffSampleFloat
-  4 -> pure TiffSampleUnknown
-  vv -> fail $ "Undefined data format (" ++ show vv ++ ")"
-
-packSampleFormat :: TiffSampleFormat -> Word32
-packSampleFormat TiffSampleUint    = 1
-packSampleFormat TiffSampleInt     = 2
-packSampleFormat TiffSampleFloat   = 3
-packSampleFormat TiffSampleUnknown = 4
-
-data ImageFileDirectory = ImageFileDirectory
-  { ifdIdentifier :: !ExifTag -- Word16
-  , ifdType       :: !IfdType -- Word16
-  , ifdCount      :: !Word32
-  , ifdOffset     :: !Word32
-  , ifdExtended   :: !ExifData
-  }
-  deriving (Eq, Show, Generic)
-instance NFData ImageFileDirectory
-
-instance BinaryParam Endianness ImageFileDirectory where
-  getP endianness =
-    ImageFileDirectory <$> getE <*> getE <*> getE <*> getE
-                       <*> pure ExifNone
-        where getE :: (BinaryParam Endianness a) => Get a
-              getE = getP endianness
-
-  putP endianness ifd = do
-    let putE :: (BinaryParam Endianness a) => a -> Put
-        putE = putP endianness
-    putE $ ifdIdentifier ifd
-    putE $ ifdType ifd
-    putE $ ifdCount ifd
-    putE $ ifdOffset ifd
-
-instance BinaryParam Endianness [ImageFileDirectory] where
-  getP endianness = do
-    count <- getP endianness :: Get Word16
-    rez <- replicateM (fromIntegral count) $ getP endianness
-    _ <- getP endianness :: Get Word32
-    pure rez
-
-
-  putP endianness lst = do
-    let count = fromIntegral $ length lst :: Word16
-    putP endianness count
-    mapM_ (putP endianness) lst
-    putP endianness (0 :: Word32)
-
-data TiffColorspace
-  = TiffMonochromeWhite0 -- ^ 0
-  | TiffMonochrome       -- ^ 1
-  | TiffRGB              -- ^ 2
-  | TiffPaleted          -- ^ 3
-  | TiffTransparencyMask -- ^ 4
-  | TiffCMYK             -- ^ 5
-  | TiffYCbCr            -- ^ 6
-  | TiffCIELab           -- ^ 8
-
-
-packPhotometricInterpretation :: TiffColorspace -> Word16
-packPhotometricInterpretation v = case v of
-  TiffMonochromeWhite0 -> 0
-  TiffMonochrome       -> 1
-  TiffRGB              -> 2
-  TiffPaleted          -> 3
-  TiffTransparencyMask -> 4
-  TiffCMYK             -> 5
-  TiffYCbCr            -> 6
-  TiffCIELab           -> 8
-
-unpackPhotometricInterpretation :: Word32 -> Get TiffColorspace
-unpackPhotometricInterpretation v = case v of
-  0 -> pure TiffMonochromeWhite0
-  1 -> pure TiffMonochrome
-  2 -> pure TiffRGB
-  3 -> pure TiffPaleted
-  4 -> pure TiffTransparencyMask
-  5 -> pure TiffCMYK
-  6 -> pure TiffYCbCr
-  8 -> pure TiffCIELab
-  vv -> fail $ "Unrecognized color space " ++ show vv
-
-data ExtraSample
-  = ExtraSampleUnspecified       -- ^ 0
-  | ExtraSampleAssociatedAlpha   -- ^ 1
-  | ExtraSampleUnassociatedAlpha -- ^ 2
-
-codeOfExtraSample :: ExtraSample -> Word16
-codeOfExtraSample v = case v of
-  ExtraSampleUnspecified -> 0
-  ExtraSampleAssociatedAlpha -> 1
-  ExtraSampleUnassociatedAlpha -> 2
-
-unPackCompression :: Word32 -> Get TiffCompression
-unPackCompression v = case v of
-  0 -> pure CompressionNone
-  1 -> pure CompressionNone
-  2 -> pure CompressionModifiedRLE
-  5 -> pure CompressionLZW
-  6 -> pure CompressionJPEG
-  32773 -> pure CompressionPackBit
-  vv -> fail $ "Unknown compression scheme " ++ show vv
-
-packCompression :: TiffCompression -> Word16
-packCompression v = case v of
-  CompressionNone        -> 1
-  CompressionModifiedRLE -> 2
-  CompressionLZW         -> 5
-  CompressionJPEG        -> 6
-  CompressionPackBit     -> 32773
-
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE FlexibleContexts #-}
+module Codec.Picture.Tiff.Internal.Types
+    ( BinaryParam( .. )
+    , Endianness( .. )
+    , TiffHeader( .. )
+    , TiffPlanarConfiguration( .. )
+    , TiffCompression( .. )
+    , IfdType( .. )
+    , TiffColorspace( .. )
+    , TiffSampleFormat( .. )
+    , ImageFileDirectory( .. )
+    , ExtraSample( .. )
+    , Predictor( .. )
+
+    , planarConfgOfConstant
+    , constantToPlaneConfiguration
+    , unpackSampleFormat
+    , packSampleFormat
+    , word16OfTag
+    , unpackPhotometricInterpretation
+    , packPhotometricInterpretation
+    , codeOfExtraSample
+    , unPackCompression
+    , packCompression 
+    , predictorOfConstant
+    ) where
+
+#if !MIN_VERSION_base(4,8,0)
+import Control.Applicative( (<$>), (<*>), pure )
+#endif
+
+import Control.DeepSeq( NFData(..) )
+import Control.Monad( forM_, when, replicateM, )
+import Data.Bits( (.&.), unsafeShiftR )
+import Data.Binary( Binary( .. ) )
+import Data.Binary.Get( Get
+                      , getWord16le, getWord16be
+                      , getWord32le, getWord32be
+                      , bytesRead
+                      , skip
+                      , getByteString
+                      )
+import Data.Binary.Put( Put
+                      , putWord16le, putWord16be
+                      , putWord32le, putWord32be
+                      , putByteString
+                      )
+import Data.Function( on )
+import Data.List( sortBy, mapAccumL )
+import qualified Data.Vector as V
+import qualified Data.ByteString as B
+import Data.Int( Int32 )
+import Data.Word( Word8, Word16, Word32 )
+import GHC.Generics( Generic )
+
+import Codec.Picture.Metadata.Exif
+{-import Debug.Trace-}
+
+data Endianness
+  = EndianLittle
+  | EndianBig
+  deriving (Eq, Show)
+
+instance Binary Endianness where
+  put EndianLittle = putWord16le 0x4949
+  put EndianBig = putWord16le 0x4D4D
+
+  get = do
+    tag <- getWord16le
+    case tag of
+      0x4949 -> return EndianLittle
+      0x4D4D -> return EndianBig
+      _ -> fail "Invalid endian tag value"
+
+-- | Because having a polymorphic get with endianness is to nice
+-- to pass on, introducing this helper type class, which is just
+-- a superset of Binary, but formalising a parameter passing
+-- into it.
+class BinaryParam a b where
+  getP :: a -> Get b
+  putP :: a -> b -> Put
+
+data TiffHeader = TiffHeader
+  { hdrEndianness :: !Endianness
+  , hdrOffset     :: {-# UNPACK #-} !Word32
+  }
+  deriving (Eq, Show)
+
+instance BinaryParam Endianness Word16 where
+  putP EndianLittle = putWord16le
+  putP EndianBig = putWord16be
+
+  getP EndianLittle = getWord16le
+  getP EndianBig = getWord16be
+
+instance BinaryParam Endianness Int32 where
+  putP en v = putP en $ (fromIntegral v :: Word32)
+  getP en = fromIntegral <$> (getP en :: Get Word32) 
+
+instance BinaryParam Endianness Word32 where
+  putP EndianLittle = putWord32le
+  putP EndianBig = putWord32be
+
+  getP EndianLittle = getWord32le
+  getP EndianBig = getWord32be
+
+instance Binary TiffHeader where
+  put hdr = do
+    let endian = hdrEndianness hdr
+    put endian
+    putP endian (42 :: Word16)
+    putP endian $ hdrOffset hdr
+
+  get = do
+    endian <- get
+    magic <- getP endian
+    let magicValue = 42 :: Word16
+    when (magic /= magicValue)
+         (fail "Invalid TIFF magic number")
+    TiffHeader endian <$> getP endian
+
+data TiffPlanarConfiguration
+  = PlanarConfigContig    -- = 1
+  | PlanarConfigSeparate  -- = 2
+
+planarConfgOfConstant :: Word32 -> Get TiffPlanarConfiguration
+planarConfgOfConstant 0 = pure PlanarConfigContig
+planarConfgOfConstant 1 = pure PlanarConfigContig
+planarConfgOfConstant 2 = pure PlanarConfigSeparate
+planarConfgOfConstant v = fail $ "Unknown planar constant (" ++ show v ++ ")"
+
+constantToPlaneConfiguration :: TiffPlanarConfiguration -> Word16
+constantToPlaneConfiguration PlanarConfigContig = 1
+constantToPlaneConfiguration PlanarConfigSeparate = 2
+
+data TiffCompression
+  = CompressionNone           -- 1
+  | CompressionModifiedRLE    -- 2
+  | CompressionLZW            -- 5
+  | CompressionJPEG           -- 6
+  | CompressionPackBit        -- 32273
+
+data IfdType
+  = TypeByte
+  | TypeAscii
+  | TypeShort
+  | TypeLong
+  | TypeRational
+  | TypeSByte
+  | TypeUndefined
+  | TypeSignedShort
+  | TypeSignedLong
+  | TypeSignedRational
+  | TypeFloat
+  | TypeDouble
+  deriving (Eq, Show, Generic)
+instance NFData IfdType
+
+instance BinaryParam Endianness IfdType where
+    getP endianness = getP endianness >>= conv where
+      conv :: Word16 -> Get IfdType
+      conv v = case v of
+        1  -> return TypeByte
+        2  -> return TypeAscii
+        3  -> return TypeShort
+        4  -> return TypeLong
+        5  -> return TypeRational
+        6  -> return TypeSByte
+        7  -> return TypeUndefined
+        8  -> return TypeSignedShort
+        9  -> return TypeSignedLong
+        10 -> return TypeSignedRational
+        11 -> return TypeFloat
+        12 -> return TypeDouble
+        _  -> fail "Invalid TIF directory type"
+
+    putP endianness = putP endianness . conv where
+      conv :: IfdType -> Word16
+      conv v = case v of
+        TypeByte -> 1
+        TypeAscii -> 2
+        TypeShort -> 3
+        TypeLong -> 4
+        TypeRational -> 5
+        TypeSByte -> 6
+        TypeUndefined -> 7
+        TypeSignedShort -> 8
+        TypeSignedLong -> 9
+        TypeSignedRational -> 10
+        TypeFloat -> 11
+        TypeDouble -> 12
+
+instance BinaryParam Endianness ExifTag where
+  getP endianness = tagOfWord16 <$> getP endianness
+  putP endianness = putP endianness . word16OfTag
+
+data Predictor
+  = PredictorNone                   -- 1
+  | PredictorHorizontalDifferencing -- 2
+  deriving Eq
+
+predictorOfConstant :: Word32 -> Get Predictor
+predictorOfConstant 1 = pure PredictorNone
+predictorOfConstant 2 = pure PredictorHorizontalDifferencing
+predictorOfConstant v = fail $ "Unknown predictor (" ++ show v ++ ")"
+
+paddWrite :: B.ByteString -> Put
+paddWrite str = putByteString str >> padding where
+  zero = 0 :: Word8
+  padding = when (odd (B.length str)) $ put zero
+
+instance BinaryParam (Endianness, Int, ImageFileDirectory) ExifData where
+  putP (endianness, _, _) = dump
+    where
+      dump ExifNone = pure ()
+      dump (ExifLong _) = pure ()
+      dump (ExifShort _) = pure ()
+      dump (ExifIFD _) = pure ()
+      dump (ExifString bstr) = paddWrite bstr
+      dump (ExifUndefined bstr) = paddWrite bstr
+      -- wrong if length == 2
+      dump (ExifShorts shorts) = V.mapM_ (putP endianness) shorts
+      dump (ExifLongs longs) = V.mapM_ (putP endianness) longs
+      dump (ExifRational a b) = putP endianness a >> putP endianness b
+      dump (ExifSignedRational a b) = putP endianness a >> putP endianness b
+
+  getP (endianness, maxi, ifd) = fetcher ifd
+    where
+      align ImageFileDirectory { ifdOffset = offset } act = do
+        readed <- bytesRead
+        let delta = fromIntegral offset - readed
+        if offset >= fromIntegral maxi || fromIntegral readed > offset then
+          pure ExifNone
+        else do
+          skip $ fromIntegral delta
+          act
+
+      getE :: (BinaryParam Endianness a) => Get a
+      getE = getP endianness
+
+      getVec count = V.replicateM (fromIntegral count)
+
+      immediateBytes ofs =
+        let bytes = [fromIntegral $ (ofs .&. 0xFF000000) `unsafeShiftR` (3 * 8)
+                    ,fromIntegral $ (ofs .&. 0x00FF0000) `unsafeShiftR` (2 * 8)
+                    ,fromIntegral $ (ofs .&. 0x0000FF00) `unsafeShiftR` (1 * 8)
+                    ,fromIntegral $  ofs .&. 0x000000FF
+                    ]
+        in case endianness of
+             EndianLittle -> reverse bytes
+             EndianBig    -> bytes
+
+      fetcher ImageFileDirectory { ifdIdentifier = TagExifOffset
+                                 , ifdType = TypeLong
+                                 , ifdCount = 1 } = do
+         align ifd $ do
+            let byOffset = sortBy (compare `on` ifdOffset)
+                cleansIfds = fmap (cleanImageFileDirectory endianness)
+            subIfds <- cleansIfds . byOffset <$> getP endianness
+            cleaned <- fetchExtended endianness maxi $ sortBy (compare `on` ifdOffset) subIfds
+            pure $ ExifIFD [(ifdIdentifier fd, ifdExtended fd) | fd <- cleaned]
+         {-  
+      fetcher ImageFileDirectory { ifdIdentifier = TagGPSInfo
+                                 , ifdType = TypeLong
+                                 , ifdCount = 1 } = do
+         align ifd 
+         subIfds <- fmap (cleanImageFileDirectory endianness) <$> getP endianness
+         cleaned <- fetchExtended endianness subIfds
+         pure $ ExifIFD [(ifdIdentifier fd, ifdExtended fd) | fd <- cleaned]
+        -}
+      fetcher ImageFileDirectory { ifdType = TypeUndefined, ifdCount = count } | count > 4 =
+         align ifd $ ExifUndefined <$> getByteString (fromIntegral count)
+      fetcher ImageFileDirectory { ifdType = TypeUndefined, ifdOffset = ofs } =
+          pure . ExifUndefined . B.pack $ take (fromIntegral $ ifdCount ifd)
+              (immediateBytes ofs)
+      fetcher ImageFileDirectory { ifdType = TypeAscii, ifdCount = count } | count > 4 =
+          align ifd $ ExifString <$> getByteString (fromIntegral count)
+      fetcher ImageFileDirectory { ifdType = TypeAscii, ifdOffset = ofs } =
+          pure . ExifString . B.pack $ take (fromIntegral $ ifdCount ifd)
+              (immediateBytes ofs)
+      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = 2, ifdOffset = ofs } =
+          pure . ExifShorts $ V.fromListN 2 valList
+            where high = fromIntegral $ ofs `unsafeShiftR` 16
+                  low = fromIntegral $ ofs .&. 0xFFFF
+                  valList = case endianness of
+                    EndianLittle -> [low, high]
+                    EndianBig -> [high, low]
+      fetcher ImageFileDirectory { ifdType = TypeRational, ifdCount = 1 } = do
+          align ifd $ ExifRational <$> getP EndianLittle <*> getP EndianLittle
+      fetcher ImageFileDirectory { ifdType = TypeSignedRational, ifdCount = 1 } = do
+          align ifd $ ExifSignedRational <$> getP EndianLittle <*> getP EndianLittle
+      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = 1 } =
+          pure . ExifShort . fromIntegral $ ifdOffset ifd
+      fetcher ImageFileDirectory { ifdType = TypeShort, ifdCount = count } | count > 2 =
+          align ifd $ ExifShorts <$> getVec count getE
+      fetcher ImageFileDirectory { ifdType = TypeLong, ifdCount = 1 } =
+          pure . ExifLong . fromIntegral $ ifdOffset ifd
+      fetcher ImageFileDirectory { ifdType = TypeLong, ifdCount = count } | count > 1 =
+          align ifd $ ExifLongs <$> getVec count getE
+      fetcher _ = pure ExifNone
+
+cleanImageFileDirectory :: Endianness -> ImageFileDirectory -> ImageFileDirectory
+cleanImageFileDirectory EndianBig ifd@(ImageFileDirectory { ifdCount = 1 }) = aux $ ifdType ifd
+  where
+    aux TypeShort = ifd { ifdOffset = ifdOffset ifd `unsafeShiftR` 16 }
+    aux _ = ifd
+cleanImageFileDirectory _ ifd = ifd
+
+fetchExtended :: Endianness -> Int -> [ImageFileDirectory] -> Get [ImageFileDirectory]
+fetchExtended endian maxi = mapM $ \ifd -> do
+  v <- getP (endian, maxi, ifd)
+  pure $ ifd { ifdExtended = v }
+
+-- | All the IFD must be written in order according to the tag
+-- value of the IFD. To avoid getting to much restriction in the
+-- serialization code, just sort it.
+orderIfdByTag :: [ImageFileDirectory] -> [ImageFileDirectory]
+orderIfdByTag = sortBy comparer where
+  comparer a b = compare t1 t2 where
+    t1 = word16OfTag $ ifdIdentifier a
+    t2 = word16OfTag $ ifdIdentifier b
+
+-- | Given an official offset and a list of IFD, update the offset information
+-- of the IFD with extended data.
+setupIfdOffsets :: Word32 -> [ImageFileDirectory] -> (Word32, [ImageFileDirectory])
+setupIfdOffsets initialOffset lst = mapAccumL updater startExtended lst
+  where ifdElementCount = fromIntegral $ length lst
+        ifdSize = 12
+        ifdCountSize = 2
+        nextOffsetSize = 4
+        startExtended = initialOffset
+                     + ifdElementCount * ifdSize
+                     + ifdCountSize + nextOffsetSize
+
+        paddedSize blob = fromIntegral $ blobLength + padding where
+          blobLength = B.length blob
+          padding = if odd blobLength then 1 else 0
+
+        updater ix ifd@(ImageFileDirectory { ifdIdentifier = TagExifOffset }) =
+            (ix, ifd { ifdOffset = ix } )
+        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifUndefined b }) =
+            (ix + paddedSize b, ifd { ifdOffset = ix } )
+        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifString b }) =
+            (ix + paddedSize b, ifd { ifdOffset = ix } )
+        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifLongs v })
+            | V.length v > 1 = ( ix + fromIntegral (V.length v * 4)
+                               , ifd { ifdOffset = ix } )
+        updater ix ifd@(ImageFileDirectory { ifdExtended = ExifShorts v })
+            | V.length v > 2 = ( ix + fromIntegral (V.length v * 2)
+                             , ifd { ifdOffset = ix })
+        updater ix ifd = (ix, ifd)
+
+instance BinaryParam B.ByteString (TiffHeader, [[ImageFileDirectory]]) where
+  putP rawData (hdr, ifds) = do
+    put hdr
+    putByteString rawData
+    let endianness = hdrEndianness hdr
+        (_, offsetted) = mapAccumL
+            (\ix ifd -> setupIfdOffsets ix $ orderIfdByTag ifd)
+            (hdrOffset hdr)
+            ifds
+    forM_ offsetted $ \list -> do
+        putP endianness list
+        mapM_ (\field -> putP (endianness, (0::Int), field) $ ifdExtended field) list
+
+  getP raw = do
+    hdr <- get
+    readed <- bytesRead
+    skip . fromIntegral $ fromIntegral (hdrOffset hdr) - readed
+    let endian = hdrEndianness hdr
+        byOffset = sortBy (compare `on` ifdOffset)
+        cleanIfds = fmap (cleanImageFileDirectory endian)
+
+    ifd <-  cleanIfds . byOffset <$> getP endian
+    cleaned <- fetchExtended endian (B.length raw) ifd
+    return (hdr, [cleaned])
+
+data TiffSampleFormat
+  = TiffSampleUint
+  | TiffSampleInt
+  | TiffSampleFloat
+  | TiffSampleUnknown
+  deriving Eq
+
+unpackSampleFormat :: Word32 -> Get TiffSampleFormat
+unpackSampleFormat v = case v of
+  1 -> pure TiffSampleUint
+  2 -> pure TiffSampleInt
+  3 -> pure TiffSampleFloat
+  4 -> pure TiffSampleUnknown
+  vv -> fail $ "Undefined data format (" ++ show vv ++ ")"
+
+packSampleFormat :: TiffSampleFormat -> Word32
+packSampleFormat TiffSampleUint    = 1
+packSampleFormat TiffSampleInt     = 2
+packSampleFormat TiffSampleFloat   = 3
+packSampleFormat TiffSampleUnknown = 4
+
+data ImageFileDirectory = ImageFileDirectory
+  { ifdIdentifier :: !ExifTag -- Word16
+  , ifdType       :: !IfdType -- Word16
+  , ifdCount      :: !Word32
+  , ifdOffset     :: !Word32
+  , ifdExtended   :: !ExifData
+  }
+  deriving (Eq, Show, Generic)
+instance NFData ImageFileDirectory
+
+instance BinaryParam Endianness ImageFileDirectory where
+  getP endianness =
+    ImageFileDirectory <$> getE <*> getE <*> getE <*> getE
+                       <*> pure ExifNone
+        where getE :: (BinaryParam Endianness a) => Get a
+              getE = getP endianness
+
+  putP endianness ifd = do
+    let putE :: (BinaryParam Endianness a) => a -> Put
+        putE = putP endianness
+    putE $ ifdIdentifier ifd
+    putE $ ifdType ifd
+    putE $ ifdCount ifd
+    putE $ ifdOffset ifd
+
+instance BinaryParam Endianness [ImageFileDirectory] where
+  getP endianness = do
+    count <- getP endianness :: Get Word16
+    rez <- replicateM (fromIntegral count) $ getP endianness
+    _ <- getP endianness :: Get Word32
+    pure rez
+
+
+  putP endianness lst = do
+    let count = fromIntegral $ length lst :: Word16
+    putP endianness count
+    mapM_ (putP endianness) lst
+    putP endianness (0 :: Word32)
+
+data TiffColorspace
+  = TiffMonochromeWhite0 -- ^ 0
+  | TiffMonochrome       -- ^ 1
+  | TiffRGB              -- ^ 2
+  | TiffPaleted          -- ^ 3
+  | TiffTransparencyMask -- ^ 4
+  | TiffCMYK             -- ^ 5
+  | TiffYCbCr            -- ^ 6
+  | TiffCIELab           -- ^ 8
+
+
+packPhotometricInterpretation :: TiffColorspace -> Word16
+packPhotometricInterpretation v = case v of
+  TiffMonochromeWhite0 -> 0
+  TiffMonochrome       -> 1
+  TiffRGB              -> 2
+  TiffPaleted          -> 3
+  TiffTransparencyMask -> 4
+  TiffCMYK             -> 5
+  TiffYCbCr            -> 6
+  TiffCIELab           -> 8
+
+unpackPhotometricInterpretation :: Word32 -> Get TiffColorspace
+unpackPhotometricInterpretation v = case v of
+  0 -> pure TiffMonochromeWhite0
+  1 -> pure TiffMonochrome
+  2 -> pure TiffRGB
+  3 -> pure TiffPaleted
+  4 -> pure TiffTransparencyMask
+  5 -> pure TiffCMYK
+  6 -> pure TiffYCbCr
+  8 -> pure TiffCIELab
+  vv -> fail $ "Unrecognized color space " ++ show vv
+
+data ExtraSample
+  = ExtraSampleUnspecified       -- ^ 0
+  | ExtraSampleAssociatedAlpha   -- ^ 1
+  | ExtraSampleUnassociatedAlpha -- ^ 2
+
+codeOfExtraSample :: ExtraSample -> Word16
+codeOfExtraSample v = case v of
+  ExtraSampleUnspecified -> 0
+  ExtraSampleAssociatedAlpha -> 1
+  ExtraSampleUnassociatedAlpha -> 2
+
+unPackCompression :: Word32 -> Get TiffCompression
+unPackCompression v = case v of
+  0 -> pure CompressionNone
+  1 -> pure CompressionNone
+  2 -> pure CompressionModifiedRLE
+  5 -> pure CompressionLZW
+  6 -> pure CompressionJPEG
+  32773 -> pure CompressionPackBit
+  vv -> fail $ "Unknown compression scheme " ++ show vv
+
+packCompression :: TiffCompression -> Word16
+packCompression v = case v of
+  CompressionNone        -> 1
+  CompressionModifiedRLE -> 2
+  CompressionLZW         -> 5
+  CompressionJPEG        -> 6
+  CompressionPackBit     -> 32773
+
diff --git a/src/Codec/Picture/Types.hs b/src/Codec/Picture/Types.hs
--- a/src/Codec/Picture/Types.hs
+++ b/src/Codec/Picture/Types.hs
@@ -467,7 +467,7 @@
 dynamicMap f (ImageCMYK16 i) = f i
 
 -- | Equivalent of the `pixelMap` function for the dynamic images.
--- You can perform pixel colorspace independant operations with this
+-- You can perform pixel colorspace independent operations with this
 -- function.
 --
 -- For instance, if you want to extract a square crop of any image,
@@ -742,12 +742,12 @@
     -- it is treated like the other color components.
     colorMap :: (PixelBaseComponent a -> PixelBaseComponent a) -> a -> a
 
-    -- | Calculate the index for the begining of the pixel
+    -- | Calculate the index for the beginning of the pixel
     pixelBaseIndex :: Image a -> Int -> Int -> Int
     pixelBaseIndex (Image { imageWidth = w }) x y =
             (x + y * w) * componentCount (undefined :: a)
 
-    -- | Calculate theindex for the begining of the pixel at position x y
+    -- | Calculate theindex for the beginning of the pixel at position x y
     mutablePixelBaseIndex :: MutableImage s a -> Int -> Int -> Int
     mutablePixelBaseIndex (MutableImage { mutableImageWidth = w }) x y =
             (x + y * w) * componentCount (undefined :: a)
@@ -1188,7 +1188,7 @@
     computeLuma (PixelYCbCr8 y _ _) = y
     extractLumaPlane = extractComponent PlaneLuma
 
--- | Free promotion for identic pixel types
+-- | Free promotion for identical pixel types
 instance (Pixel a) => ColorConvertible a a where
     {-# INLINE promotePixel #-}
     promotePixel = id
@@ -2404,7 +2404,7 @@
 -- to pack a pixel value to a simpler "primitive" data
 -- type to allow faster writing to moemory.
 class PackeablePixel a where
-    -- | Primitive type asociated to the current pixel
+    -- | Primitive type associated to the current pixel
     -- It's Word32 for PixelRGBA8 for instance
     type PackedRepresentation a
 
diff --git a/src/Codec/Picture/VectorByteConversion.hs b/src/Codec/Picture/VectorByteConversion.hs
--- a/src/Codec/Picture/VectorByteConversion.hs
+++ b/src/Codec/Picture/VectorByteConversion.hs
@@ -1,52 +1,52 @@
-{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE TypeFamilies #-}
-{-# LANGUAGE CPP #-}
-module Codec.Picture.VectorByteConversion( blitVector
-                                         , toByteString
-                                         , imageFromUnsafePtr ) where
-
-import Data.Word( Word8 )
-import Data.Vector.Storable( Vector, unsafeToForeignPtr, unsafeFromForeignPtr0 )
-import Foreign.Storable( Storable, sizeOf )
-
-#if !MIN_VERSION_base(4,8,0)
-import Foreign.ForeignPtr.Safe( ForeignPtr, castForeignPtr )
-#else
-import Foreign.ForeignPtr( ForeignPtr, castForeignPtr )
-#endif
-
-
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Internal as S
-
-import Codec.Picture.Types
-
-mkBS :: ForeignPtr Word8 -> Int -> Int -> S.ByteString
-#if MIN_VERSION_bytestring(0,11,0)
-mkBS fptr off = S.BS (fptr `S.plusForeignPtr` off)
-#else
-mkBS = S.PS
-#endif
-
-blitVector :: Vector Word8 -> Int -> Int -> B.ByteString
-blitVector vec atIndex = mkBS ptr (offset + atIndex)
-  where (ptr, offset, _length) = unsafeToForeignPtr vec
-
-toByteString :: forall a. (Storable a) => Vector a -> B.ByteString
-toByteString vec = mkBS (castForeignPtr ptr) offset (len * size)
-  where (ptr, offset, len) = unsafeToForeignPtr vec
-        size = sizeOf (undefined :: a)
-
--- | Import a image from an unsafe pointer
--- The pointer must have a size of width * height * componentCount px
-imageFromUnsafePtr :: forall px
-                    . (Pixel px, (PixelBaseComponent px) ~ Word8)
-                   => Int -- ^ Width in pixels
-                   -> Int -- ^ Height in pixels
-                   -> ForeignPtr Word8 -- ^ Pointer to the raw data
-                   -> Image px
-imageFromUnsafePtr width height ptr =
-    Image width height $ unsafeFromForeignPtr0 ptr size
-      where compCount = componentCount (undefined :: px)
-            size = width * height * compCount
-
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE CPP #-}
+module Codec.Picture.VectorByteConversion( blitVector
+                                         , toByteString
+                                         , imageFromUnsafePtr ) where
+
+import Data.Word( Word8 )
+import Data.Vector.Storable( Vector, unsafeToForeignPtr, unsafeFromForeignPtr0 )
+import Foreign.Storable( Storable, sizeOf )
+
+#if !MIN_VERSION_base(4,8,0)
+import Foreign.ForeignPtr.Safe( ForeignPtr, castForeignPtr )
+#else
+import Foreign.ForeignPtr( ForeignPtr, castForeignPtr )
+#endif
+
+
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Internal as S
+
+import Codec.Picture.Types
+
+mkBS :: ForeignPtr Word8 -> Int -> Int -> S.ByteString
+#if MIN_VERSION_bytestring(0,11,0)
+mkBS fptr off = S.BS (fptr `S.plusForeignPtr` off)
+#else
+mkBS = S.PS
+#endif
+
+blitVector :: Vector Word8 -> Int -> Int -> B.ByteString
+blitVector vec atIndex = mkBS ptr (offset + atIndex)
+  where (ptr, offset, _length) = unsafeToForeignPtr vec
+
+toByteString :: forall a. (Storable a) => Vector a -> B.ByteString
+toByteString vec = mkBS (castForeignPtr ptr) offset (len * size)
+  where (ptr, offset, len) = unsafeToForeignPtr vec
+        size = sizeOf (undefined :: a)
+
+-- | Import a image from an unsafe pointer
+-- The pointer must have a size of width * height * componentCount px
+imageFromUnsafePtr :: forall px
+                    . (Pixel px, (PixelBaseComponent px) ~ Word8)
+                   => Int -- ^ Width in pixels
+                   -> Int -- ^ Height in pixels
+                   -> ForeignPtr Word8 -- ^ Pointer to the raw data
+                   -> Image px
+imageFromUnsafePtr width height ptr =
+    Image width height $ unsafeFromForeignPtr0 ptr size
+      where compCount = componentCount (undefined :: px)
+            size = width * height * compCount
+
diff --git a/test-src/BmpRleSafety.hs b/test-src/BmpRleSafety.hs
new file mode 100644
--- /dev/null
+++ b/test-src/BmpRleSafety.hs
@@ -0,0 +1,148 @@
+-- BmpRleSafety.hs: regression tests for the BMP RLE out-of-bounds write fix
+-- (HSEC-2026-00XX / CVE pending).
+--
+-- Covers:
+--  1. Int32 allocation-wrap header (w = 2^27, h = 64 -> product == 2^33)
+--     must be rejected by the dimension gate, not crash.
+--  2. A negative-offset RLE8 delta escape stream (cursor walked above the
+--     buffer) must decode safely with the writes clipped.
+--  2b. height = INT32_MIN must be rejected (Int32 abs wraps to itself).
+--  2c. The same negative-offset escape through the 4bpp (RLE4) path.
+--  3. A benign 4x4 RLE8 image must still decode correctly (no overblocking).
+--  4. A benign 8x1 RLE4 image must still decode correctly (4bpp path).
+--
+-- Palettes are identity grayscale (entry i = RGB i i i) so decoded pixel
+-- values are deterministic.
+module Main where
+
+import qualified Data.ByteString as B
+import qualified Data.Vector.Storable as VS
+import           Data.Bits ((.&.), shiftR)
+import           Data.Int (Int32)
+import           Data.Word
+import           Data.List (isPrefixOf)
+import           System.Exit (exitFailure, exitSuccess)
+import           Codec.Picture
+
+le16 :: Int -> [Word8]
+le16 v = [ fromIntegral (v .&. 0xFF), fromIntegral ((v `shiftR` 8) .&. 0xFF) ]
+
+le32 :: Int -> [Word8]
+le32 v = [ fromIntegral (v .&. 0xFF), fromIntegral ((v `shiftR` 8) .&. 0xFF)
+         , fromIntegral ((v `shiftR` 16) .&. 0xFF)
+         , fromIntegral ((v `shiftR` 24) .&. 0xFF) ]
+
+-- Identity grayscale 8bpp palette: entry i stored as B,G,R,X bytes.
+grayPalette :: B.ByteString
+grayPalette = B.pack $ concat
+  [ [ fromIntegral i, fromIntegral i, fromIntegral i, 0 ]
+  | i <- [0 .. 255 :: Int] ]
+
+-- BITMAPINFOHEADER wrapper, BGR palette order.
+bmp :: Int -> Int -> Int -> Int -> Int -> B.ByteString -> B.ByteString
+       -> B.ByteString
+bmp w h bpp compression clrUsed palette stream = B.pack $
+  concat [ [0x42, 0x4D], le32 totalSize, le16 0, le16 0, le32 pixelOffset
+         , le32 40, le32 w, le32 h, le16 1, le16 bpp, le32 compression
+         , le32 (B.length stream), le32 2835, le32 2835
+         , le32 clrUsed, le32 0 ]
+    ++ B.unpack palette ++ B.unpack stream
+  where
+    totalSize = 14 + 40 + B.length palette + B.length stream
+    pixelOffset = 14 + 40 + B.length palette
+
+-- 1. Allocation-wrap header: 2^27 * 64 == 2^33 -> Int32 wraps to 0, plus a
+--    delta escape (v=255) walking the cursor ~24 GB below the buffer.
+wrapBmp :: B.ByteString
+wrapBmp = bmp 0x08000000 64 8 1 0 grayPalette (B.pack [0x00, 0x02, 0x00, 0xFF, 0x10, 0x41, 0x00, 0x01])
+
+-- 2. F110-style attack stream: 16x16, leading vertical delta escape
+--    (00 02 00 38, y -= 16*56) pushing the cursor far above the buffer,
+--    then 16 marker runs 0xC0..0xCF, then end-of-bitmap.
+attackBmp :: B.ByteString
+attackBmp = bmp 16 16 8 1 0 grayPalette stream
+  where
+    stream = B.pack $ concat
+      [ [0x00, 0x02, 0x00, 0x38]
+      , [0x00, 0x02, 0x00, 0x00]
+      , concat [ [0x01, 0xC0 + fromIntegral i] | i <- [0 .. 15 :: Int] ]
+      , [0x00, 0x01] ]
+
+-- 2b. height = INT32_MIN: `abs` in Int32 wraps back to minBound, so the gate
+--     must widen to Int64 before taking abs to reject it.
+minHeightBmp :: B.ByteString
+minHeightBmp = bmp 1 (fromIntegral (minBound :: Int32)) 8 1 0 grayPalette
+                     (B.pack [0x00, 0x01])
+
+-- 2c. F110-style 4bpp attack: 4x4, delta escape (00 02 00 10) pushes the
+--     cursor 4*16 rows up (negative), then a two-nibble run 0x0A, then EOB.
+--     Exercises both nibble writeByte calls on the clipped path.
+attack4Bmp :: B.ByteString
+attack4Bmp = bmp 4 4 4 2 16 palette stream
+  where
+    palette = B.pack $
+      concat [ replicate 4 (fromIntegral (i * 17)) | i <- [0 .. 15 :: Int] ]
+    stream = B.pack [0x00, 0x02, 0x00, 0x10, 0x02, 0xAA, 0x00, 0x01]
+
+-- 3. Benign 4x4 RLE8: one 4-pixel run per row (with end-of-line codes),
+--    all at index 0x41, then end-of-bitmap.
+benign8Bmp :: B.ByteString
+benign8Bmp = bmp 4 4 8 1 0 grayPalette stream
+  where
+    stream = B.pack $
+      concat (replicate 3 [0x04, 0x41, 0x00, 0x00])
+        ++ [0x04, 0x41, 0x00, 0x01]
+
+-- 4. Benign 8x1 RLE4 (compression=2): 8 pixels at nibble 0x0A, then EOB.
+--    Palette has only 16 entries (B,G,R,X each), scaled 17x for visibility.
+benign4Bmp :: B.ByteString
+benign4Bmp = bmp 8 1 4 2 16 palette stream
+  where
+    palette = B.pack $
+      concat [ replicate 4 (fromIntegral (i * 17)) | i <- [0 .. 15 :: Int] ]
+    stream = B.pack [0x08, 0xAA, 0x00, 0x01]
+
+-- Force the full decoded image; returns (width, height, byte sum of RGBA8).
+forceDecoded :: B.ByteString -> Either String (Int, Int, Int)
+forceDecoded bs = case decodeBitmap bs of
+  Left e -> Left e
+  Right dyn ->
+    let img = convertRGBA8 dyn
+    in Right ( imageWidth img, imageHeight img
+             , VS.foldl' (\a w -> a + fromIntegral w) (0 :: Int) (imageData img) )
+
+main :: IO ()
+main = do
+  results <- sequence
+    [ check "wrap header rejected" $
+        case forceDecoded wrapBmp of
+          Left e -> "Invalid bmp dimensions" `isPrefixOf` e
+          Right _ -> False
+    , check "negative-offset attack stream decodes safely" $
+        case forceDecoded attackBmp of
+          Right (16, 16, s) -> s == 16 * 16 * 255  -- all writes clipped -> zero-filled
+          _ -> False
+    , check "INT32_MIN height rejected (Int32 abs wraps)" $
+        case forceDecoded minHeightBmp of
+          Left e -> "Invalid bmp dimensions" `isPrefixOf` e
+          Right _ -> False
+    , check "4bpp negative-offset stream decodes safely" $
+        case forceDecoded attack4Bmp of
+          Right (4, 4, _) -> True
+          _ -> False
+    , check "benign 4x4 RLE8 decodes to 16 pixels of 0x41" $
+        case forceDecoded benign8Bmp of
+          Right (4, 4, s) -> s == 16 * (0x41 * 3 + 255)
+          _ -> False
+    , check "benign 8x1 RLE4 decodes to 8 pixels of 0x0A" $
+        case forceDecoded benign4Bmp of
+          Right (8, 1, s) -> s == 8 * (0x0A * 17 * 3 + 255)
+          _ -> False
+    ]
+  if and results
+    then putStrLn ("bmp-rle-safety: " ++ show (length results) ++ "/" ++ show (length results) ++ " pass") >> exitSuccess
+    else exitFailure
+  where
+    check name ok = do
+      putStrLn (name ++ ": " ++ (if ok then "PASS" else "FAIL"))
+      return ok
diff --git a/test-src/main.hs b/test-src/main.hs
new file mode 100644
--- /dev/null
+++ b/test-src/main.hs
@@ -0,0 +1,998 @@
+-- test file, don't care about unused, on the contrary...
+{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TypeFamilies #-}
+import Codec.Picture
+import Codec.Picture.Jpg( JpgEncodable 
+                        , decodeJpegWithMetadata
+                        , encodeJpeg
+                        , encodeDirectJpegAtQualityWithMetadata )
+import Codec.Picture.Gif
+import Codec.Picture.Tiff
+import System.Environment
+
+import Data.Either ( isRight )
+import Data.Binary
+import Data.Binary.Get (runGetOrFail)
+import Data.Bits ( unsafeShiftR, xor )
+import Data.Char( toLower )
+import Data.List( isInfixOf, isPrefixOf )
+import Data.Maybe( maybeToList )
+import Data.Monoid
+import Data.Word( Word8 )
+import Control.Monad( forM_, liftM, when )
+import System.FilePath
+import qualified Data.ByteString.Char8 as B
+import qualified Data.ByteString.Lazy as L
+import qualified Codec.Picture.Jpg.Internal.Types as JpgInternal
+import Codec.Picture.Types
+import Codec.Picture.Saving
+import Codec.Picture.HDR
+import Codec.Picture.Bitmap( encodeBitmapWithMetadata )
+import Codec.Picture.Png( encodePalettedPngWithMetadata )
+import qualified Codec.Picture.Metadata as Met
+import qualified Codec.Picture.Metadata.Exif as Met
+import qualified Data.Vector.Storable as V
+
+import Control.Applicative( (<$>) )
+import Criterion.Main
+import Control.DeepSeq
+
+validTests :: [FilePath]
+validTests = 
+   ["PngSuite.png", "basi0g01.png", "basi0g02.png", "basi0g04.png", "basi0g08.png",
+    "basi0g16.png", "basi2c08.png", "basi2c16.png", "basi3p01.png", "basi3p02.png",
+    "basi3p04.png", "basi3p08.png", "basi4a08.png", "basi4a16.png", "basi6a08.png",
+    "basi6a16.png", "basn0g01.png", "basn0g02.png", "basn0g04.png", "basn0g08.png",
+    "basn0g16.png", "basn2c08.png", "basn2c16.png", "basn3p01.png", "basn3p02.png",
+    "basn3p04.png", "basn3p08.png", "basn4a08.png", "basn4a16.png", "basn6a08.png",
+    "basn6a16.png", "bgai4a08.png", "bgai4a16.png", "bgan6a08.png", "bgan6a16.png",
+    "bgbn4a08.png", "bggn4a16.png", "bgwn6a08.png", "bgyn6a16.png", "ccwn2c08.png",
+    "ccwn3p08.png", "cdfn2c08.png", "cdhn2c08.png", "cdsn2c08.png", "cdun2c08.png",
+    "ch1n3p04.png", "ch2n3p08.png", "cm0n0g04.png", "cm7n0g04.png", "cm9n0g04.png",
+    "cs3n2c16.png", "cs3n3p08.png", "cs5n2c08.png", "cs5n3p08.png", "cs8n2c08.png",
+    "cs8n3p08.png", "ct0n0g04.png", "ct1n0g04.png", "cten0g04.png", "ctfn0g04.png",
+    "ctgn0g04.png", "cthn0g04.png", "ctjn0g04.png", "ctzn0g04.png", "f00n0g08.png",
+    "f00n2c08.png", "f01n0g08.png", "f01n2c08.png", "f02n0g08.png", "f02n2c08.png",
+    "f03n0g08.png", "f03n2c08.png", "f04n0g08.png", "f04n2c08.png", "f99n0g04.png",
+    "g03n0g16.png", "g03n2c08.png", "g03n3p04.png", "g04n0g16.png", "g04n2c08.png",
+    "g04n3p04.png", "g05n0g16.png", "g05n2c08.png", "g05n3p04.png", "g07n0g16.png",
+    "g07n2c08.png", "g07n3p04.png", "g10n0g16.png", "g10n2c08.png", "g10n3p04.png",
+    "g25n0g16.png", "g25n2c08.png", "g25n3p04.png", "oi1n0g16.png", "oi1n2c16.png",
+    "oi2n0g16.png", "oi2n2c16.png", "oi4n0g16.png", "oi4n2c16.png", "oi9n0g16.png",
+    "oi9n2c16.png", "pp0n2c16.png", "pp0n6a08.png", "ps1n0g08.png", "ps1n2c16.png",
+    "ps2n0g08.png", "ps2n2c16.png", "s01i3p01.png", "s01n3p01.png", "s02i3p01.png",
+    "s02n3p01.png", "s03i3p01.png", "s03n3p01.png", "s04i3p01.png", "s04n3p01.png",
+    "s05i3p02.png", "s05n3p02.png", "s06i3p02.png", "s06n3p02.png", "s07i3p02.png",
+    "s07n3p02.png", "s08i3p02.png", "s08n3p02.png", "s09i3p02.png", "s09n3p02.png",
+    "s32i3p04.png", "s32n3p04.png", "s33i3p04.png", "s33n3p04.png", "s34i3p04.png",
+    "s34n3p04.png", "s35i3p04.png", "s35n3p04.png", "s36i3p04.png", "s36n3p04.png",
+    "s37i3p04.png", "s37n3p04.png", "s38i3p04.png", "s38n3p04.png", "s39i3p04.png",
+    "s39n3p04.png", "s40i3p04.png", "s40n3p04.png", "tbbn0g04.png", "tbbn2c16.png",
+    "tbbn3p08.png", "tbgn2c16.png", "tbgn3p08.png", "tbrn2c08.png", "tbwn0g16.png",
+    "tbwn3p08.png", "tbyn3p08.png", "tp0n0g08.png", "tp0n2c08.png", "tp0n3p08.png",
+    "tp1n3p08.png", "z00n2c08.png", "z03n2c08.png", "z06n2c08.png", "z09n2c08.png", "megaman.png"]
+
+invalidTests :: [FilePath]
+invalidTests = ["xc1n0g08.png", "xc9n2c08.png", "xcrn0g04.png", "xcsn0g01.png", "xd0n2c08.png",
+                "xd3n2c08.png", "xdtn0g01.png", "xhdn0g08.png", "xlfn0g04.png", "xs1n0g01.png",
+                "xs2n0g01.png", "xs4n0g01.png", "xs7n0g01.png", "xd9n2c08.png"]
+
+{-exportBmpWitness :: IO ()-}
+{-exportBmpWitness = writeBitmap "wintess.bmp" $ img 232 241-}
+    {-where img w h = array ((0,0), (w - 1, h - 1)) $ pixels w h-}
+          {-pixels w h = [((x,y), pixel x y) | y <- [0 .. h-1], x <- [0 .. w-1] ]-}
+          {-pixel x y = PixelRGBA8 128 (fromIntegral x) (fromIntegral y) 255-}
+
+greyScaleWitness :: Int -> Image Pixel8
+greyScaleWitness offset = img 232 241
+    where img w h = Image w h $ V.fromListN (w * h) $ pixels w h
+          pixels w h = [pixel (x + offset) (y + offset)
+                                | y <- [0 .. h-1], x <- [0 .. w-1] ]
+          pixel x y = truncate $ sqrt dist
+                where xf = fromIntegral $ x - 100 :: Int
+                      yf = fromIntegral $ y - 100
+                      dist = (fromIntegral $ xf * xf + yf * yf) :: Double
+
+gifAPITest :: IO ()
+gifAPITest = do
+  testFail noImages1 "No GIF frames" "Empty frames list"
+  testFail noImages2 "No image in list" "Empty images list"
+
+  testFail zeroWidthScreen "Invalid screen bounds" "Screen width of zero"
+  testFail zeroHeightScreen "Invalid screen bounds" "Screen height of zero"
+  testFail tooWideScreen "Invalid screen bounds" "Screen width over 65535"
+  testFail tooTallScreen "Invalid screen bounds" "Screen height over 65535"
+
+  testFail zeroWidthFrame "GIF frames with invalid bounds" "Frame width of zero"
+  testFail zeroHeightFrame "GIF frames with invalid bounds" "Frame height of zero"
+  testFail tooWideFrame "GIF frames with invalid bounds" "Screen width over 65535"
+  testFail tooTallFrame "GIF frames with invalid bounds" "Screen height over 65535"
+
+  testFail outOfBoundsXNeg "GIF frames out of screen bounds" "Frame out of screen bounds -X"
+  testFail outOfBoundsXPos "GIF frames out of screen bounds" "Frame out of screen bounds +X"
+  testFail outOfBoundsYNeg "GIF frames out of screen bounds" "Frame out of screen bounds -Y"
+  testFail outOfBoundsYPos "GIF frames out of screen bounds" "Frame out of screen bounds +Y"
+
+  testFail zeroColorGlobalPalette "Invalid global palette size" "Zero color global palette"
+  testFail tooLargeGlobalPalette "Invalid global palette size" "Over 256 colors global palette"
+  testFail tallGlobalPalette "Invalid global palette size" "Invalid global palette height"
+
+  testFail zeroColorFramePalette "Invalid palette size in GIF frames" "Zero color frame palette"
+  testFail tooLargeFramePalette "Invalid palette size in GIF frames" "Over 256 colors frame palette"
+  testFail tallFramePalette "Invalid palette size in GIF frames" "Invalid frame palette height"
+
+  testFail bgColorMissing "GIF background index absent" "GIF background color not in global palette"
+  testFail trColorMissing "GIF transparent index absent" "GIF transparent color not in frame palette"
+
+  testFail noPalette "GIF image frames with color indexes missing" "Frame with no palette"
+  
+  testFail pxColorMissing1 "GIF image frames with color indexes missing" "Pixel color index not in palette"
+  testFail pxColorMissing2 "GIF image frames with color indexes missing" "Pixel color index not in palette"
+  testFail pxColorMissing3 "GIF image frames with color indexes missing" "Pixel color index not in palette"
+
+  where testFail (Right _)  _        desc = putStrLn $ "GIF API test failed: " ++ desc ++ " should cause error"
+        testFail (Left msg) expected _
+          | expected `isPrefixOf` msg = return ()
+          | otherwise                 = putStrLn $ "Unexpected failure message from GIF API: " ++ msg
+
+        palette2b = generateImage (\x _ -> let c = if x == 0 then 0x00 else 0xff in PixelRGB8 c c c) 2 1
+        pixels1x1 = generateImage (\_ _ -> 0) 1 1
+        okFrames = [GifFrame 0 0 (Just palette2b) Nothing 0 DisposalAny pixels1x1]
+
+        noImages1 = encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever []
+        noImages2 = encodeGifImages LoopingNever []
+
+        zeroWidthScreen = encodeComplexGifImage $ GifEncode 0 1 Nothing Nothing LoopingNever okFrames
+        zeroHeightScreen = encodeComplexGifImage $ GifEncode 1 0 Nothing Nothing LoopingNever okFrames
+        tooWideScreen = encodeComplexGifImage $ GifEncode 0x10000 1 Nothing Nothing LoopingNever okFrames
+        tooTallScreen = encodeComplexGifImage $ GifEncode 1 0x10000 Nothing Nothing LoopingNever okFrames
+
+        zeroWidthFrame = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                         [GifFrame 0 0 Nothing Nothing 0 DisposalAny $ generateImage (\_ _ -> 0) 0 1]
+        zeroHeightFrame = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                          [GifFrame 0 0 Nothing Nothing 0 DisposalAny $ generateImage (\_ _ -> 0) 1 0]
+        tooWideFrame = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                       [GifFrame 0 0 Nothing Nothing 0 DisposalAny $ generateImage (\_ _ -> 0) 0x10000 1]
+        tooTallFrame = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                       [GifFrame 0 0 Nothing Nothing 0 DisposalAny $ generateImage (\_ _ -> 0) 1 0x10000]
+
+        outOfBoundsXNeg = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                          [GifFrame (-1) 0 Nothing Nothing 0 DisposalAny pixels1x1]
+        outOfBoundsXPos = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                          [GifFrame 1 0 Nothing Nothing 0 DisposalAny pixels1x1]
+        outOfBoundsYNeg = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                          [GifFrame 0 (-1) Nothing Nothing 0 DisposalAny pixels1x1]
+        outOfBoundsYPos = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever
+                          [GifFrame 0 1 Nothing Nothing 0 DisposalAny pixels1x1]
+
+        zeroColorGlobalPalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 0 1
+          in encodeComplexGifImage $ GifEncode 1 1 (Just palette) Nothing LoopingNever okFrames
+        tooLargeGlobalPalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 257 1
+          in encodeComplexGifImage $ GifEncode 1 1 (Just palette) Nothing LoopingNever okFrames
+        tallGlobalPalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 1 2
+          in encodeComplexGifImage $ GifEncode 1 1 (Just palette) Nothing LoopingNever okFrames
+
+        zeroColorFramePalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 0 1
+              frames = [GifFrame 0 0 (Just palette) Nothing 0 DisposalAny pixels1x1]
+          in encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever frames
+        tooLargeFramePalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 257 1
+              frames = [GifFrame 0 0 (Just palette) Nothing 0 DisposalAny pixels1x1]
+          in encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever frames
+        tallFramePalette =
+          let palette = generateImage (\_ _ -> PixelRGB8 0 0 0) 1 2
+              frames = [GifFrame 0 0 (Just palette) Nothing 0 DisposalAny pixels1x1]
+          in encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever frames
+
+        bgColorMissing = encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) (Just 3) LoopingNever okFrames
+        trColorMissing = encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever
+                         [GifFrame 0 0 (Just palette2b) (Just 3) 0 DisposalAny pixels1x1]
+
+        noPalette =
+          let frames = [GifFrame 0 0 Nothing Nothing 0 DisposalAny pixels1x1]
+          in encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever frames
+
+        pxColorMissing1 = -- Global palette
+          let pixels = generateImage (\_ _ -> 2) 1 1
+              frames = [GifFrame 0 0 Nothing Nothing 0 DisposalAny pixels]
+          in encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever frames
+        pxColorMissing2 = -- Local palette
+          let pixels = generateImage (\_ _ -> 2) 1 1
+              frames = [GifFrame 0 0 (Just palette2b) Nothing 0 DisposalAny pixels]
+          in encodeComplexGifImage $ GifEncode 1 1 Nothing Nothing LoopingNever frames
+        pxColorMissing3 = -- Both
+          let pixels = generateImage (\_ _ -> 2) 1 1
+              frames = [GifFrame 0 0 (Just palette2b) Nothing 0 DisposalAny pixels]
+          in encodeComplexGifImage $ GifEncode 1 1 (Just palette2b) Nothing LoopingNever frames
+        
+
+gifAnimationTest :: IO ()
+gifAnimationTest =
+    case writeGifImages "Gifanim.gif" LoopingForever img of
+      Left err -> putStrLn err
+      Right w -> w
+  where img = [(greyPalette, 20, greyScaleWitness (i * 10)) | i <- [0 .. 20]]
+
+gifPaletteTest :: IO ()
+gifPaletteTest = do
+  gifGridTest
+  gif1024ColorsTest
+
+gifGridTest :: IO ()
+gifGridTest = do
+  gifBWGrid
+  gifBAGrid
+  gifWAGrid
+
+  where palette = generateImage (\x _ -> let c = if x == 0 then 0x00 else 0xff in PixelRGB8 c c c) 2 1
+        pixels = generateImage (\x y -> if even x `xor` even y then 0 else 1) 20 20
+        writeGif name spec = case writeComplexGifImage ("tests" </> name) spec of
+          Left err -> putStrLn err
+          Right w -> w
+        -- BW global palette, no local palette
+        gifBWGrid = writeGif "black-white-grid.gif" $
+          GifEncode 20 20 (Just palette) Nothing LoopingNever
+          [GifFrame 0 0 Nothing Nothing 0 DisposalAny pixels]
+        -- No global palette, BW local palette with white index as transparency
+        gifBAGrid = writeGif "black-alpha-grid.gif" $
+          GifEncode 20 20 Nothing Nothing LoopingNever
+          [GifFrame 0 0 (Just palette) (Just 1) 0 DisposalAny pixels]
+        -- No global palette, BW local palette with black index as transparency
+        gifWAGrid = writeGif "white-alpha-grid.gif" $
+          GifEncode 20 20 Nothing Nothing LoopingNever
+          [GifFrame 0 0 (Just palette) (Just 0) 0 DisposalAny pixels]
+
+gif1024ColorsTest :: IO ()
+gif1024ColorsTest = case writeComplexGifImage ("tests" </> "1024-colors.gif") spec of
+                      Left err -> putStrLn err
+                      Right w -> w
+  where spec = GifEncode 256 4 Nothing Nothing LoopingNever [reds, greens, blues, greys]
+        -- Most viewers will animate this even with the 0 delays
+        reds   = GifFrame 0 0 (Just redPalette)   Nothing 0 DisposalDoNot pixels
+        greens = GifFrame 0 1 (Just greenPalette) Nothing 0 DisposalDoNot pixels
+        blues  = GifFrame 0 2 (Just bluePalette)  Nothing 0 DisposalDoNot pixels
+        greys  = GifFrame 0 3 (Just greyPalette)  Nothing 0 DisposalDoNot pixels
+        redPalette   = pixelMap (\(PixelRGB8 r _ _) -> PixelRGB8 r 0 0) greyPalette
+        greenPalette = pixelMap (\(PixelRGB8 _ g _) -> PixelRGB8 0 g 0) greyPalette
+        bluePalette  = pixelMap (\(PixelRGB8 _ _ b) -> PixelRGB8 0 0 b) greyPalette
+        pixels = generateImage (\x _ -> fromIntegral x) 256 1
+
+jpegValidTests :: [FilePath]
+jpegValidTests = [ "bad_decode.jpg"
+                 , "broken.jpg"
+                 , "borked_render.jpg"
+                 , "inf_loop01.jpg"
+                 , "inf_loop02.jpg"
+                 , "explore_jpeg.jpg"
+                 , "16x16jpeg.jpg"
+                 , "8x8jpeg.jpg"
+                 , "avatar.jpg"
+                 , "fenek.jpg"
+                 , "Channel_digital_image_CMYK_color.jpg"
+                 , "rgb.jpg"
+                 , "img_cmyk.jpg"
+                 , "JPEG_example_JPG_RIP_001.jpg"
+                 , "JPEG_example_JPG_RIP_010.jpg"
+                 , "JPEG_example_JPG_RIP_025.jpg"
+                 , "JPEG_example_JPG_RIP_050.jpg"
+                 , "JPEG_example_JPG_RIP_100.jpg"
+                 , "sheep.jpg"
+                 , "MCU0.jpg"
+                 , "MCU1.jpg"
+                 , "MCU5.jpg"
+                 , "MCU10.jpg"
+                 , "20100713-0107-interleaved2.jpg"
+                 , "MCU35.jpg"
+                 , "dunno.jpg"
+                 , "mand_prgrsv.jpg"
+                 , "bad.jpg"
+                 , "richys-groceries.jpg"
+                 ]
+
+tgaValidTests :: [FilePath]
+tgaValidTests =
+    [ "CBW8.TGA"
+    , "CTC16.TGA"
+    , "CTC24.TGA"
+    , "CTC32.TGA"
+    , "FLAG_B16.TGA"
+    , "FLAG_B24.TGA"
+    , "FLAG_B32.TGA"
+    , "FLAG_T16.TGA"
+    , "FLAG_T32.TGA"
+    , "MARBLES.TGA"
+
+    , "UTC16.TGA"
+    , "UTC24.TGA"
+    , "UTC32.TGA"
+    , "XING_B16.TGA"
+    , "XING_B24.TGA"
+    , "XING_B32.TGA"
+    , "XING_T16.TGA"
+    , "XING_T24.TGA"
+    , "XING_T32.TGA"
+
+    , "CCM8.TGA"
+    , "UBW8.TGA"
+    , "UCM8.TGA"
+    ]
+
+bmpValidTests :: [FilePath]
+bmpValidTests =
+    ["simple_bitmap_24bits.bmp"
+    ,"simple_bitmap_8bits.bmp"
+    ,"simple_bitmap_32bits.bmp"
+    ,"bitmap_32bits_type0.bmp"
+    ,"eggyra0001.bmp"
+    ,"smiley.bmp"
+    ,"rle_test.bmp"
+    ,"bmpsuite_good/pal1bg.bmp"
+    ,"bmpsuite_good/pal8.bmp"
+    ,"bmpsuite_good/pal8v5.bmp"
+    ,"bmpsuite_good/rgb16.bmp"
+    ,"bmpsuite_good/pal1.bmp"
+    ,"bmpsuite_good/pal8gs.bmp"
+    ,"bmpsuite_good/pal8w124.bmp"
+    ,"bmpsuite_good/rgb24.bmp"
+    ,"bmpsuite_good/pal1wb.bmp"
+    ,"bmpsuite_good/pal8nonsquare.bmp"
+    ,"bmpsuite_good/pal8w125.bmp"
+    ,"bmpsuite_good/rgb24pal.bmp"
+    ,"bmpsuite_good/pal4.bmp"
+    ,"bmpsuite_good/pal8os2.bmp"
+    ,"bmpsuite_good/pal8w126.bmp"
+    ,"bmpsuite_good/rgb32bf.bmp"
+    ,"bmpsuite_good/pal4gs.bmp"
+    ,"bmpsuite_good/pal8rle.bmp"
+    ,"bmpsuite_good/rgb16-565.bmp"
+    ,"bmpsuite_good/rgb32bfdef.bmp"
+    ,"bmpsuite_good/pal4rle.bmp"
+    ,"bmpsuite_good/pal8topdown.bmp"
+    ,"bmpsuite_good/rgb16-565pal.bmp"
+    ,"bmpsuite_good/rgb32.bmp"
+    ,"bmpsuite_good/pal8-0.bmp"
+    ,"bmpsuite_good/pal8v4.bmp"
+    ,"bmpsuite_good/rgb16bfdef.bmp"
+    ]
+
+-- "caspian.tif"
+tiffValidTests :: [FilePath]
+tiffValidTests =
+    ["depth/flower-rgb-planar-02.tif"
+    ,"depth/flower-rgb-planar-04.tif"
+    ,"depth/flower-rgb-planar-08.tif"
+    ,"depth/flower-rgb-planar-16.tif"
+    ,"depth/flower-rgb-contig-02.tif"
+    ,"depth/flower-rgb-contig-04.tif"
+    ,"depth/flower-rgb-contig-08.tif"
+    ,"depth/flower-rgb-contig-16.tif"
+    ,"depth/flower-palette-02.tif"
+    ,"depth/flower-palette-04.tif"
+    ,"depth/flower-palette-08.tif"
+    ,"depth/flower-minisblack-02.tif"
+    ,"depth/flower-minisblack-08.tif"
+    ,"depth/flower-minisblack-04.tif"
+    ,"depth/flower-minisblack-16.tif"
+    ,"depth/flower-separated-contig-08.tif"
+    ,"depth/flower-separated-contig-16.tif"
+    ,"depth/flower-separated-planar-08.tif"
+    ,"depth/flower-separated-planar-16.tif"
+    ,"depth/flower-minisblack-12.tif"
+    ,"quad-lzw.tif"
+    ,"pc260001.tif"
+    ,"cramps.tif"
+    ,"strike.tif"
+    ,"ycbcr-cat.tif"
+    {-,"zackthecat.tif"-}
+    {-"smallliz.tif"-}
+    ,"compression/cs3n2c16.tif"
+    ,"compression/flower-rgb-contig-16-packbits.tif"
+    ,"other/butique-YA8.tif"
+    ,"other/butique-YA16.tif"
+    ,"horizontal-difference-lzw.tiff" -- produced by "Grab" on Mac OS X
+    ,"rad_YF.tif"
+    ,"rad_Y32.tif"
+    ]
+
+validationJpegEncode :: Image PixelYCbCr8 -> L.ByteString
+validationJpegEncode = encodeJpegAtQuality 100
+
+liberalJpegEncode :: (PixelBaseComponent px ~ Word8, JpgEncodable px)
+                  => Image px -> L.ByteString
+liberalJpegEncode =
+    encodeDirectJpegAtQualityWithMetadata 100 mempty
+
+eitherDo :: Either String (IO ()) -> IO ()
+eitherDo (Left str) = putStrLn str
+eitherDo (Right action) = action
+
+gifToImg :: FilePath -> IO ()
+gifToImg path = do
+    rez <- readGifImages path
+    case rez of
+        Left err -> putStrLn $ "Error : " ++ err
+        Right [] -> putStrLn "No image in gif file"
+        Right v@(ImageRGB8 _ : _) ->
+          forM_ (zip [0..] v) $ \(i :: Int, ImageRGB8 img) -> do
+            let ycbcr = convertImage img
+                jpg = validationJpegEncode ycbcr
+                png = encodePng img
+                tga = encodeTga img
+                bmp = encodeBitmap img
+                tiff = encodeTiff img
+            putStrLn $ "PixelRGB8 : " ++ path
+
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGB8.bmp") bmp
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGB8.png") png
+            putStrLn "-> TGA"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGB8.tga") tga
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGB8.jpg") jpg
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGB8.tiff") tiff
+
+        Right v@(ImageRGBA8 _ : _) ->
+          forM_ (zip [0..] v) $ \(i :: Int, ImageRGBA8 img) -> do
+            let ycbcr = convertImage $ dropAlphaLayer img
+                jpg = validationJpegEncode ycbcr
+                png = encodePng img
+                tga = encodeTga img
+                bmp = encodeBitmap img
+                tiff = encodeTiff img
+            putStrLn $ "PixelRGB8 : " ++ path
+
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGBA8.bmp") bmp
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGBA8.png") png
+            putStrLn "-> TGA"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGBA8.tga") tga
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGBA8.jpg") jpg
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "_" ++ show i ++ "._fromRGBA8.tiff") tiff
+
+        Right _ ->
+            putStrLn "Error : unexpected colorspace from GIF file"
+
+
+imgToImg :: FilePath -> IO ()
+imgToImg path = do
+    rez <- readImageWithMetadata path
+    case rez of
+        Right (ImageYCbCr8 img, met) -> do
+            let rgb = convertImage img :: Image PixelRGB8
+                jpg = validationJpegEncode img
+                png = encodePng rgb
+                tga = encodeTga rgb
+                bmp = encodeBitmap rgb
+                tiff = encodeTiff img
+            putStrLn $ "YCbCr : " ++ path
+            print met
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromYCbCr8.jpg") jpg
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "._fromYCbCr8.bmp") bmp
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromYCbCr8.png") png
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromYCbCr8.tiff") tiff
+            putStrLn "-> TGA"
+            L.writeFile (path ++ "._fromYCbCr8.tga") tga
+            putStrLn "-> Gif"
+            eitherDo $ writeColorReducedGifImage (path ++ "._fromYCbCr8.gif") rgb
+
+        Right (ImageYF img, met) -> do
+            let png16  = encodePng $ fromFloatTo16 img
+                tiff32 = encodeTiff $ fromFloatTo32 img
+            putStrLn $ "Float : " ++ path
+            print met
+            putStrLn "-> PNG (16)"
+            L.writeFile (path ++ "._fromYF.png") png16
+            putStrLn "-> Tiff (32)"
+            L.writeFile (path ++ "._fromYF.tiff") tiff32
+
+        Right (ImageY32 img, met) -> do
+            let png16     = encodePng $ from32To16 img
+                tiffFloat = encodeTiff $ from32ToFloat img
+            putStrLn $ "Y32 : " ++ path
+            print met
+            putStrLn "-> PNG (16)"
+            L.writeFile (path ++ "._fromY32.png") png16
+            putStrLn "-> Tiff (Float)"
+            L.writeFile (path ++ "._fromY32.tiff") tiffFloat
+
+        Right (ImageRGBF _, _) -> putStrLn "don't handle HDR image in imgToImg"
+        Right (ImageCMYK16 img, met) -> do
+            let rgbimg :: Image PixelRGB16
+                rgbimg = convertImage img
+                png = encodePng rgbimg
+                tiff = encodeTiff img
+            putStrLn $ "CMYK16 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromCMYK16.png") png
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromCMYK16.tiff") tiff
+
+        Right (ImageCMYK8 img, met) -> do
+            let rgbimg :: Image PixelRGB8
+                rgbimg = convertImage img
+                png = encodePng rgbimg
+                jpg = encodeDirectJpegAtQualityWithMetadata 90 mempty img
+                tiff = encodeTiff img
+            putStrLn $ "CMYK8 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromCMYK8.png") png
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromCMYK8.jpg") jpg
+            putStrLn "-> Gif"
+            eitherDo $ writeColorReducedGifImage (path ++ "._fromCMYK8.gif") rgbimg
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromCMYK8.tiff") tiff
+
+        Right (ImageRGB8 img, met) -> do
+            let jpg = validationJpegEncode (convertImage img)
+                jpgRgb = liberalJpegEncode img
+                png = encodePng img
+                bmp = encodeBitmap img
+                tga = encodeTga img
+                tiff = encodeTiff img
+            putStrLn $ "RGB8 : " ++ path
+            print met
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "._fromRGB8.bmp") bmp
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromRGB8.jpg") jpg
+            putStrLn "-> JPG (RGB)"
+            L.writeFile (path ++ ".RGB._fromRGB8.jpg") jpgRgb
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromRGB8.png") png
+            putStrLn "-> Gif"
+            eitherDo $ writeColorReducedGifImage (path ++ "._fromRGB8.gif") img
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromRGB8.tiff") tiff
+            putStrLn "-> Tga"
+            L.writeFile (path ++ "._fromRGB8.tga") tga
+
+        Right (ImageY16 img, met) -> do
+            let pngFile = encodePng img
+                tiffFile = encodeTiff img
+            putStrLn $ "Y16 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromY16.png") pngFile
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromY16.tiff") tiffFile
+
+        Right (ImageYA16 img, met) -> do
+            let pngFile = imageToPng $ ImageYA16 img
+            putStrLn $ "YA16 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromYA16.png") pngFile
+
+        Right (ImageRGB16 img, met) -> do
+            let pngFile = encodePng img
+                tiffFile = encodeTiff img
+            putStrLn $ "RGB16 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromRGB16.png") pngFile
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromRGB16.tiff") tiffFile
+
+
+        Right (ImageRGBA16 img, met) -> do
+            let pngFile = encodePng img
+                tiffFile = encodeTiff img
+            putStrLn $ "RGBA16 : " ++ path
+            print met
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromRGBA16.png") pngFile
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromRGBA16.tiff") tiffFile
+
+        Right (ImageRGBA8 img, met) -> do
+            let bmp = encodeBitmap img
+                jpg = validationJpegEncode (convertImage $ dropAlphaLayer img)
+                png = encodePng img
+                tiff = encodeTiff img
+                tga = encodeTga img
+            putStrLn $ "RGBA8 : " ++ path
+            print met
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "._fromRGBA8.bmp") bmp
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromRGBA8.jpg") jpg
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromRGBA8.png") png
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromRGBA8.tiff") tiff
+            putStrLn "-> Tga"
+            L.writeFile (path ++ "._fromRGBA8.tga") tga
+
+        Right (ImageY8 img, met) -> do
+            let bmp = encodeBitmap img
+                jpg = liberalJpegEncode img
+                png = encodePng img
+                tiff = encodeTiff img
+                tga = encodeTiff img
+                gif = encodeGifImage img
+            putStrLn $ "Y8 : " ++ path
+            print met
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "._fromY8.bmp") bmp
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromY8.jpg") jpg
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromY8.png") png
+            putStrLn "-> Tiff"
+            L.writeFile (path ++ "._fromY8.tiff") tiff
+            putStrLn "-> Tga"
+            L.writeFile (path ++ "._fromY8.tga") tga
+            putStrLn "-> Gif"
+            L.writeFile (path ++ "._fromY8.gif") gif
+
+        Right (ImageYA8 img, met) -> do
+            let bmp = encodeBitmap $ (promoteImage img :: Image PixelRGB8)
+                png = encodePng $ (promoteImage img :: Image PixelRGBA8)
+                gif = encodeGifImage $ (dropAlphaLayer img)
+                jpg = validationJpegEncode $ convertImage
+                                (promoteImage $ dropAlphaLayer img :: Image PixelRGB8)
+            putStrLn $ "YA8 : " ++ path
+            print met
+            putStrLn "-> BMP"
+            L.writeFile (path ++ "._fromYA8.bmp") bmp
+            putStrLn "-> JPG"
+            L.writeFile (path ++ "._fromYA8.jpg") jpg
+            putStrLn "-> PNG"
+            L.writeFile (path ++ "._fromYA8.png") png
+            putStrLn "-> Gif"
+            L.writeFile (path ++ "._fromYA8.gif") gif
+
+        Left err ->
+            putStrLn $ "Error loading " ++ path ++ " " ++ err
+
+toStandardDef :: Image PixelRGBF -> Image PixelRGB8
+toStandardDef img = pixelMap pixelConverter img
+  where fix = truncate . (254 *) . max 0.0 . min 1.0
+        pixelConverter (PixelRGBF rf gf bf) = PixelRGB8 r g b
+          where r = fix rf
+                g = fix gf
+                b = fix bf
+
+fromFloatTo32 :: Image PixelF -> Image Pixel32
+fromFloatTo32 = pixelMap (\f -> floor (f * (fromIntegral (maxBound :: Word32))))
+
+fromFloatTo16 :: Image PixelF -> Image Pixel16
+fromFloatTo16 = pixelMap (\f -> floor (f * (fromIntegral (maxBound :: Word16))))
+
+from32ToFloat :: Image Pixel32 -> Image PixelF
+from32ToFloat = pixelMap (\w -> fromIntegral w / 4294967296.0)
+
+from32To16 :: Image Pixel32 -> Image Pixel16
+from32To16 = pixelMap (fromIntegral . (`unsafeShiftR` 16))
+
+radianceToBitmap :: FilePath -> IO ()
+radianceToBitmap path = do
+    rez <- readImage path
+    case rez of
+      Left err -> putStrLn $ "Error loading " ++ path ++ " " ++ err
+      Right (ImageRGBF img) -> do
+          L.writeFile (path ++ ".bmp") . imageToBitmap $ ImageRGBF img
+          writeHDR (path ++ ".hdr") img
+          writeRLENewStyleHDR (path ++ ".rle.hdr") img
+
+      Right img -> do
+          L.writeFile (path ++ ".bmp") $ imageToBitmap img
+
+toJpg :: String -> Image PixelRGB8 -> IO ()
+toJpg name img = do
+    let jpg = validationJpegEncode (convertImage img)
+    putStrLn "-> JPG"
+    L.writeFile (name ++ "._fromRGB8.jpg") jpg
+
+planeSeparationRGB8Test :: IO ()
+planeSeparationRGB8Test = do
+    rez <- readImage ("tests" </> "planeseparation.png")
+    case rez of
+       Left _ -> putStrLn "can't load separation file"
+       Right (ImageRGB8 img) -> do
+           L.writeFile ("tests" </> "rgb8_red.png") . encodePng $ extractComponent PlaneRed img
+           L.writeFile ("tests" </> "rgb8_green.png") . encodePng $ extractComponent PlaneGreen img
+           L.writeFile ("tests" </> "rgb8_blue.png") . encodePng $ extractComponent PlaneBlue img
+
+       Right _ -> putStrLn "Wrong image file format"
+
+planeSeparationRGBA8Test :: IO ()
+planeSeparationRGBA8Test = do
+    rez <- readImage ("tests" </> "planeseparationrgba.png")
+    case rez of
+       Left _ -> putStrLn "can't load separation file"
+       Right (ImageRGBA8 img) -> do
+           L.writeFile ("tests" </> "rgba8_red.png") . encodePng $ extractComponent PlaneRed img
+           L.writeFile ("tests" </> "rgba8_green.png") . encodePng $ extractComponent PlaneGreen img
+           L.writeFile ("tests" </> "rgba8_blue.png") . encodePng $ extractComponent PlaneBlue img
+           L.writeFile ("tests" </> "rgba8_alpha.png") . encodePng $ extractComponent PlaneAlpha img
+
+       Right _ -> putStrLn "Wrong image file format"
+
+planeSeparationYA8Test :: IO ()
+planeSeparationYA8Test = do
+    let img = generateImage generator 256 256
+        generator x y = PixelYA8 (fromIntegral $ x `mod` 256) (fromIntegral $ ((y `div` 4) `mod` 2) * 255)
+    L.writeFile ("tests" </> "ya8_gray.png") . encodePng $ extractComponent PlaneLuma img
+    L.writeFile ("tests" </> "ya8_alpha.png") . encodePng $ extractComponent PlaneAlpha img
+    L.writeFile ("tests" </> "ya8_combined.png") $ encodePng img
+
+gifTest :: [FilePath]
+gifTest = ["Gif_pixel_cube.gif"
+          ,"fgs.gif"
+          ,"animated.gif"
+          ,"interleaved.gif"
+          ,"delta.gif"
+          ,"delta2.gif"
+          ,"rId98.gif"
+          ,"magceit.gif"
+          ,"2k.gif"
+          ,"pikachu.gif"
+          ,"huge.gif"
+          ]
+
+radianceTest :: [FilePath]
+radianceTest = [ "sunrise.hdr", "free_009.hdr"]
+
+metadataWriteTest :: IO ()
+metadataWriteTest = do
+  let dumbImage = generateImage (\_ _ -> PixelRGB8 255 255 255) 16 16
+      mi = Met.insert
+      metas = mi Met.Author "It's a me"
+            $ mi Met.Software "JuicyPixels test suite"
+            $ mi Met.Title "A metadata test"
+            $ mi Met.Copyright "meh"
+            $ mi Met.Description "let's see the results"
+            $ mi Met.Comment "Test of comment"
+            $ Met.mkDpiMetadata 93
+  L.writeFile "tests/metadata.png" $
+      encodePngWithMetadata metas dumbImage
+  L.writeFile "tests/metadata.jpg" $
+      encodeDirectJpegAtQualityWithMetadata 50 metas $ (convertImage dumbImage :: Image PixelYCbCr8)
+  L.writeFile "tests/metadata.bmp" $
+      encodeBitmapWithMetadata metas dumbImage
+
+metadataReadTest :: IO ()
+metadataReadTest = do
+  image <- B.readFile "tests/jpeg/10x8-samsung-s8.jpg"
+  case decodeJpegWithMetadata image of
+      Left err -> putStrLn err
+      Right (ImageYCbCr8 img, meta) -> do
+        putStrLn "===== Storing Jpeg metadata"
+        print meta
+        let encoded = encodeDirectJpegAtQualityWithMetadata 90 meta img
+        L.writeFile "tests/metadata_extif.jpg" encoded
+        let Right (_, remeta) = decodeJpegWithMetadata image
+        putStrLn "========= Reparsed metas"
+        print remeta
+          
+      Right (_, meta) -> checkMeta meta
+  where
+    -- The insert order is important as there is no Eq instance (yet)
+    metas = Met.insert Met.DpiY 72 $
+            Met.insert Met.DpiX 72 $
+            Met.insert (Met.Exif Met.TagModel) (Met.ExifString $ B.pack "SM-G955F\NUL") $
+            Met.insert Met.Height 3024 $
+            Met.insert (Met.Exif Met.TagOrientation) (Met.ExifShort 6) $
+            Met.insert Met.Width 4032 $
+            Met.insert (Met.Exif Met.TagLightSource) (Met.ExifLong 0) $
+            Met.insert (Met.Exif Met.TagFlash) (Met.ExifShort 0) $
+            Met.insert Met.Software "G955FXXU1AQJ1\NUL" $
+            Met.insert Met.Format Met.SourceTiff $
+            Met.empty
+
+    checkMeta meta = do
+      let sm = show meta
+          sms = show metas
+      when (sm /= sms) $
+        putStrLn $ "Erroneous metadata parsed from file" ++ sm ++ " vs " ++ sms
+
+palettedPngCreation :: IO ()
+palettedPngCreation = L.writeFile "tests/paleted_alpha.png" encoded
+  where
+    Right encoded = encodePalettedPngWithMetadata mempty palette img
+    img = generateImage (\x _y -> fromIntegral x) 256 128
+    palette :: Image PixelRGBA8
+    palette = generateImage (\x _y -> PixelRGBA8 255 128 128 (255 - fromIntegral x)) 256 1
+
+-- The given `path` must be a valid JPEG; this function checks it.
+-- This is to guard against not noticing that everything fails parsing.
+jpgParseECS_equivalence_success :: FilePath -> IO ()
+jpgParseECS_equivalence_success path = do
+    bsl <- L.fromStrict <$> B.readFile path
+    let ecs_res =
+            runGetOrFail (JpgInternal.skipUntilFrames *> parseFramesWithParseECSFunction JpgInternal.parseECS) bsl
+    let ecs_simple_res =
+            runGetOrFail (JpgInternal.skipUntilFrames *> parseFramesWithParseECSFunction JpgInternal.parseECS_simple) bsl
+    case (ecs_res, ecs_simple_res) of
+        (Right{}, Right{})
+            | ecs_res == ecs_simple_res -> return ()
+            | otherwise -> error "Test failure: parseECS /= parseECS_simple"
+        _ -> error $ "Test failure: parseECS / parseECS_simple failed unexpectedly with results: " ++ show (isRight ecs_res, isRight ecs_simple_res) -- only show Left/Right
+  where
+    parseFramesWithParseECSFunction :: Get L.ByteString -> Get [JpgInternal.JpgFrame]
+    parseFramesWithParseECSFunction parseECSFunction = do
+        kind <- get
+        case kind of
+            JpgInternal.JpgEndOfImage -> return []
+            _ -> do
+                mbFrame <- case kind of
+                    JpgInternal.JpgStartOfScan -> do
+                        scanHeader <- get
+                        ecs <- parseECSFunction
+                        return $! Just $! JpgInternal.JpgScanBlob scanHeader ecs
+                    _ -> JpgInternal.parseFrameOfKind kind
+                JpgInternal.skipFrameMarker
+                remainingFrames <- JpgInternal.parseFrames
+                return $ maybeToList mbFrame ++ remainingFrames
+
+-- The given `path` must be a valid JPEG; this function checks it.
+-- This is to guard against not noticing that everything fails parsing.
+getJpgImage_equivalence_success :: FilePath -> IO ()
+getJpgImage_equivalence_success path = do
+    bsl <- L.fromStrict <$> B.readFile path
+    let res = runGetOrFail (JpgInternal.getJpgImage) bsl
+    let legacy_res = runGetOrFail (get :: Get JpgInternal.JpgImage) bsl
+    case (res, legacy_res) of
+        (Right{}, Right{})
+            | res == legacy_res -> return ()
+            | otherwise -> error "Test failure: getJpgImage /= (get :: Get JpgImage)"
+        _ -> error $ "Test failure: getJpgImage / (get :: Get JpgImage) failed unexpectedly with results: " ++ show (isRight res, isRight legacy_res) -- only show Left/Right
+
+testSuite :: IO ()
+testSuite = do
+    putStrLn ">>>> Metadata test"
+    metadataWriteTest
+    metadataReadTest
+    putStrLn ">>>> Gif animation test"
+    gifAnimationTest
+    putStrLn ">>>> Gif API test"
+    gifAPITest
+    putStrLn ">>>> Gif palette test"
+    gifPaletteTest
+    putStrLn ">>>> Jpg parseECS equivalence test"
+    mapM_ (jpgParseECS_equivalence_success . (("tests" </> "jpeg") </>)) ("huge.jpg" : "10x8-samsung-s8.jpg" : jpegValidTests)
+    putStrLn ">>>> Jpg getJpgImage equivalence test"
+    mapM_ (getJpgImage_equivalence_success . (("tests" </> "jpeg") </>)) ("huge.jpg" : "10x8-samsung-s8.jpg" : jpegValidTests)
+    putStrLn ">>>> Valid instances"
+    toJpg "white" $ generateImage (\_ _ -> PixelRGB8 255 255 255) 16 16
+    toJpg "black" $ generateImage (\_ _ -> PixelRGB8 0 0 0) 16 16
+    toJpg "test" $ generateImage (\x y -> PixelRGB8 (fromIntegral x) (fromIntegral y) 255)
+                                        128 128
+    palettedPngCreation
+    planeSeparationRGB8Test 
+    planeSeparationRGBA8Test 
+    planeSeparationYA8Test 
+
+    mapM_ (imgToImg . (("tests" </> "bmp") </>)) bmpValidTests
+    mapM_ (imgToImg . (("tests" </> "pngsuite") </>)) ("huge.png" : validTests)
+    mapM_ (imgToImg . (("tests" </> "jpeg") </>)) ("huge.jpg" : jpegValidTests)
+    mapM_ (imgToImg . (("tests" </> "jpeg") </>)) ("huge.jpg" : jpegValidTests)
+    mapM_ (radianceToBitmap . (("tests" </> "radiance") </>)) radianceTest
+    mapM_ (gifToImg . (("tests" </> "gif") </>)) gifTest
+    mapM_ (imgToImg . (("tests" </> "tiff") </>)) tiffValidTests
+    mapM_ (imgToImg . (("tests" </> "tga") </>)) tgaValidTests
+
+jpegToPng :: IO ()
+jpegToPng = do
+ {-Right rez <- readImage "tests/jpeg/sheep.jpg"-}
+ {-savePngImage "control.png" rez-}
+ img <- readImage  "tests/jpeg/mand_prgrsv.jpg" -- "tests/jpeg/huge.jpg"
+ case img of
+   Left err -> do
+       putStrLn err
+       {-error "Can't decompress img"-}
+   Right i -> savePngImage "huge.png" i
+
+pngToJpeg :: IO ()
+pngToJpeg = do
+  img <- readImage "tests/pngsuite/huge.png"
+  case img of
+    Left err -> do
+        putStrLn err
+        {-error "Can't decompress img"-}
+    Right i -> saveJpgImage 95 "huge.jpg" i
+
+pngToBmp :: IO ()
+pngToBmp = do
+  img <- readImage "tests/pngsuite/huge.png"
+  case img of
+    Right (ImageRGB8 i) -> writeBitmap "huge.bmp" i
+    Left err -> do
+        putStrLn err
+        {-error "Can't decompress img"-}
+    _ -> return ()
+
+gifToPng :: IO ()
+gifToPng = do
+  img <- readImage "tests/gif/2k.gif"
+  case img of
+    Right (ImageRGB8 i) -> writeBitmap "huge.png" i
+    Left err -> do
+        putStrLn err
+        {-error "Can't decompress img"-}
+    _ -> return ()
+
+benchMark :: IO ()
+benchMark = do
+    putStrLn "Benchmarking"
+
+    hugeJpeg <- B.readFile "tests/jpeg/huge.jpg"
+    hugePng <- B.readFile "tests/pngsuite/huge.png"
+    hugeGif <- B.readFile "tests/gif/huge.gif"
+
+    let Right decodedImage = decodeImage hugePng
+
+    jpegToPng >> pngToJpeg
+
+    defaultMainWith defaultConfig [
+        bgroup "trad"
+            [ bench "JPG -> PNG" $ whnfIO jpegToPng
+            , bench "PNG -> JPG" $ whnfIO pngToJpeg
+            , bench "GIF -> PNG" $ whnfIO gifToPng
+            , bench "PNG -> BMP" $ whnfIO pngToBmp
+            ],
+
+        bgroup "reading"
+            [ bench "Huge jpeg" $ nf decodeImage hugeJpeg
+            , bench "Huge png" $ nf decodeImage hugePng
+            , bench "Huge gif" $ nf decodeImage hugeGif
+            ],
+
+        bgroup "writing"
+            [ bench "Huge jpeg" $ whnfIO $ saveJpgImage 50 "s.jpg" decodedImage
+            , bench "Huge png" $ whnfIO $ savePngImage "p.png" decodedImage
+            ]
+        ]
+    putStrLn "END"
+
+debug :: IO ()
+debug = do
+ args <- getArgs
+ case args of
+   [] -> putStrLn "no filename"
+   [_] -> putStrLn "no filename"
+   (_:filename:_) -> do
+      img <- readImage filename
+      case img of
+        Left err -> putStrLn err
+        Right i ->
+            savePngImage (filename ++ ".png") i
+
+myMain :: IO ()
+myMain = do
+    prog <- liftM (map toLower) getProgName
+    args <- getArgs
+    case args of
+        ("test":_) -> testSuite
+        ("debug":_) -> debug
+        ("jpegtopng":_) -> jpegToPng
+        ("pngtojpeg":_) -> pngToJpeg
+        ("pngtobmp":_) -> pngToBmp
+        [] | "imagetest"      `isInfixOf` prog -> testSuite
+           | "imagebenchmark" `isInfixOf` prog -> benchMark
+        _ -> do
+            putStrLn ("Unknown command " ++ show args ++ "Launching benchMark")
+            benchMark
+
+main :: IO ()
+main = myMain
+
diff --git a/test-src/toPng.hs b/test-src/toPng.hs
new file mode 100644
--- /dev/null
+++ b/test-src/toPng.hs
@@ -0,0 +1,16 @@
+
+import Prelude hiding( writeFile )
+import Data.ByteString.Lazy( writeFile )
+import Codec.Picture( readImage )
+import Codec.Picture.Saving( imageToPng )
+import System.Environment( getArgs )
+
+main :: IO ()
+main = do
+  filename:_ <- getArgs
+  img <- readImage filename
+  case img of
+    Left err -> putStrLn err
+    Right final ->
+      writeFile (filename ++ ".png") $ imageToPng final
+
diff --git a/tests/apng/APNG-Icos4D.png b/tests/apng/APNG-Icos4D.png
new file mode 100644
Binary files /dev/null and b/tests/apng/APNG-Icos4D.png differ
diff --git a/tests/apng/APNG-clock.png b/tests/apng/APNG-clock.png
new file mode 100644
Binary files /dev/null and b/tests/apng/APNG-clock.png differ
diff --git a/tests/apng/APNG-cube.png b/tests/apng/APNG-cube.png
new file mode 100644
Binary files /dev/null and b/tests/apng/APNG-cube.png differ
diff --git a/tests/apng/APNG-pyani.png b/tests/apng/APNG-pyani.png
new file mode 100644
Binary files /dev/null and b/tests/apng/APNG-pyani.png differ
diff --git a/tests/apng/APNG-spinfox.png b/tests/apng/APNG-spinfox.png
new file mode 100644
Binary files /dev/null and b/tests/apng/APNG-spinfox.png differ
diff --git a/tests/bmp/bitmap_32bits_type0.bmp b/tests/bmp/bitmap_32bits_type0.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bitmap_32bits_type0.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal1.bmp b/tests/bmp/bmpsuite_good/pal1.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal1.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal1bg.bmp b/tests/bmp/bmpsuite_good/pal1bg.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal1bg.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal1wb.bmp b/tests/bmp/bmpsuite_good/pal1wb.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal1wb.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal4.bmp b/tests/bmp/bmpsuite_good/pal4.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal4.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal4gs.bmp b/tests/bmp/bmpsuite_good/pal4gs.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal4gs.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal4rle.bmp b/tests/bmp/bmpsuite_good/pal4rle.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal4rle.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8-0.bmp b/tests/bmp/bmpsuite_good/pal8-0.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8-0.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8.bmp b/tests/bmp/bmpsuite_good/pal8.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8gs.bmp b/tests/bmp/bmpsuite_good/pal8gs.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8gs.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8nonsquare.bmp b/tests/bmp/bmpsuite_good/pal8nonsquare.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8nonsquare.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8os2.bmp b/tests/bmp/bmpsuite_good/pal8os2.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8os2.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8rle.bmp b/tests/bmp/bmpsuite_good/pal8rle.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8rle.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8topdown.bmp b/tests/bmp/bmpsuite_good/pal8topdown.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8topdown.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8v4.bmp b/tests/bmp/bmpsuite_good/pal8v4.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8v4.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8v5.bmp b/tests/bmp/bmpsuite_good/pal8v5.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8v5.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8w124.bmp b/tests/bmp/bmpsuite_good/pal8w124.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8w124.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8w125.bmp b/tests/bmp/bmpsuite_good/pal8w125.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8w125.bmp differ
diff --git a/tests/bmp/bmpsuite_good/pal8w126.bmp b/tests/bmp/bmpsuite_good/pal8w126.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/pal8w126.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb16-565.bmp b/tests/bmp/bmpsuite_good/rgb16-565.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb16-565.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb16-565pal.bmp b/tests/bmp/bmpsuite_good/rgb16-565pal.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb16-565pal.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb16.bmp b/tests/bmp/bmpsuite_good/rgb16.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb16.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb16bfdef.bmp b/tests/bmp/bmpsuite_good/rgb16bfdef.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb16bfdef.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb24.bmp b/tests/bmp/bmpsuite_good/rgb24.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb24.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb24pal.bmp b/tests/bmp/bmpsuite_good/rgb24pal.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb24pal.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb32.bmp b/tests/bmp/bmpsuite_good/rgb32.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb32.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb32bf.bmp b/tests/bmp/bmpsuite_good/rgb32bf.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb32bf.bmp differ
diff --git a/tests/bmp/bmpsuite_good/rgb32bfdef.bmp b/tests/bmp/bmpsuite_good/rgb32bfdef.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/bmpsuite_good/rgb32bfdef.bmp differ
diff --git a/tests/bmp/eggyra0001.bmp b/tests/bmp/eggyra0001.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/eggyra0001.bmp differ
diff --git a/tests/bmp/rle_test.bmp b/tests/bmp/rle_test.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/rle_test.bmp differ
diff --git a/tests/bmp/simple_bitmap_24bits.bmp b/tests/bmp/simple_bitmap_24bits.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/simple_bitmap_24bits.bmp differ
diff --git a/tests/bmp/simple_bitmap_32bits.bmp b/tests/bmp/simple_bitmap_32bits.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/simple_bitmap_32bits.bmp differ
diff --git a/tests/bmp/simple_bitmap_8bits.bmp b/tests/bmp/simple_bitmap_8bits.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/simple_bitmap_8bits.bmp differ
diff --git a/tests/bmp/smiley.bmp b/tests/bmp/smiley.bmp
new file mode 100644
Binary files /dev/null and b/tests/bmp/smiley.bmp differ
diff --git a/tests/gif/1bitgiffail.gif b/tests/gif/1bitgiffail.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/1bitgiffail.gif differ
diff --git a/tests/gif/2k.gif b/tests/gif/2k.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/2k.gif differ
diff --git a/tests/gif/Gif_pixel_cube.gif b/tests/gif/Gif_pixel_cube.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/Gif_pixel_cube.gif differ
diff --git a/tests/gif/animated.gif b/tests/gif/animated.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/animated.gif differ
diff --git a/tests/gif/delta.gif b/tests/gif/delta.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/delta.gif differ
diff --git a/tests/gif/delta2.gif b/tests/gif/delta2.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/delta2.gif differ
diff --git a/tests/gif/fgs.gif b/tests/gif/fgs.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/fgs.gif differ
diff --git a/tests/gif/huge.gif b/tests/gif/huge.gif
new file mode 100644
# file too large to diff: tests/gif/huge.gif
diff --git a/tests/gif/interleaved.gif b/tests/gif/interleaved.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/interleaved.gif differ
diff --git a/tests/gif/magceit.gif b/tests/gif/magceit.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/magceit.gif differ
diff --git a/tests/gif/pikachu.gif b/tests/gif/pikachu.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/pikachu.gif differ
diff --git a/tests/gif/rId98.gif b/tests/gif/rId98.gif
new file mode 100644
Binary files /dev/null and b/tests/gif/rId98.gif differ
diff --git a/tests/jpeg/.gitignore b/tests/jpeg/.gitignore
new file mode 100644
--- /dev/null
+++ b/tests/jpeg/.gitignore
@@ -0,0 +1,2 @@
+*.bmp
+*.png
diff --git a/tests/jpeg/10x8-samsung-s8.jpg b/tests/jpeg/10x8-samsung-s8.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/10x8-samsung-s8.jpg differ
diff --git a/tests/jpeg/16x16jpeg.jpg b/tests/jpeg/16x16jpeg.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/16x16jpeg.jpg differ
diff --git a/tests/jpeg/20100713-0107-interleaved2.jpg b/tests/jpeg/20100713-0107-interleaved2.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/20100713-0107-interleaved2.jpg differ
diff --git a/tests/jpeg/8x8jpeg.jpg b/tests/jpeg/8x8jpeg.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/8x8jpeg.jpg differ
diff --git a/tests/jpeg/Channel_digital_image_CMYK_color.jpg b/tests/jpeg/Channel_digital_image_CMYK_color.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/Channel_digital_image_CMYK_color.jpg differ
diff --git a/tests/jpeg/JPEG_example_JPG_RIP_001.jpg b/tests/jpeg/JPEG_example_JPG_RIP_001.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/JPEG_example_JPG_RIP_001.jpg differ
diff --git a/tests/jpeg/JPEG_example_JPG_RIP_010.jpg b/tests/jpeg/JPEG_example_JPG_RIP_010.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/JPEG_example_JPG_RIP_010.jpg differ
diff --git a/tests/jpeg/JPEG_example_JPG_RIP_025.jpg b/tests/jpeg/JPEG_example_JPG_RIP_025.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/JPEG_example_JPG_RIP_025.jpg differ
diff --git a/tests/jpeg/JPEG_example_JPG_RIP_050.jpg b/tests/jpeg/JPEG_example_JPG_RIP_050.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/JPEG_example_JPG_RIP_050.jpg differ
diff --git a/tests/jpeg/JPEG_example_JPG_RIP_100.jpg b/tests/jpeg/JPEG_example_JPG_RIP_100.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/JPEG_example_JPG_RIP_100.jpg differ
diff --git a/tests/jpeg/MCU0.jpg b/tests/jpeg/MCU0.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/MCU0.jpg differ
diff --git a/tests/jpeg/MCU1.jpg b/tests/jpeg/MCU1.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/MCU1.jpg differ
diff --git a/tests/jpeg/MCU10.jpg b/tests/jpeg/MCU10.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/MCU10.jpg differ
diff --git a/tests/jpeg/MCU35.jpg b/tests/jpeg/MCU35.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/MCU35.jpg differ
diff --git a/tests/jpeg/MCU5.jpg b/tests/jpeg/MCU5.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/MCU5.jpg differ
diff --git a/tests/jpeg/avatar.jpg b/tests/jpeg/avatar.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/avatar.jpg differ
diff --git a/tests/jpeg/bad.jpg b/tests/jpeg/bad.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/bad.jpg differ
diff --git a/tests/jpeg/bad_decode.jpg b/tests/jpeg/bad_decode.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/bad_decode.jpg differ
diff --git a/tests/jpeg/borked_render.jpg b/tests/jpeg/borked_render.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/borked_render.jpg differ
diff --git a/tests/jpeg/broken.jpg b/tests/jpeg/broken.jpg
new file mode 100644
# file too large to diff: tests/jpeg/broken.jpg
diff --git a/tests/jpeg/dunno.jpg b/tests/jpeg/dunno.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/dunno.jpg differ
diff --git a/tests/jpeg/explore_jpeg.jpg b/tests/jpeg/explore_jpeg.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/explore_jpeg.jpg differ
diff --git a/tests/jpeg/fenek.jpg b/tests/jpeg/fenek.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/fenek.jpg differ
diff --git a/tests/jpeg/huge.jpg b/tests/jpeg/huge.jpg
new file mode 100644
# file too large to diff: tests/jpeg/huge.jpg
diff --git a/tests/jpeg/img_cmyk.jpg b/tests/jpeg/img_cmyk.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/img_cmyk.jpg differ
diff --git a/tests/jpeg/inf_loop01.jpg b/tests/jpeg/inf_loop01.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/inf_loop01.jpg differ
diff --git a/tests/jpeg/inf_loop02.jpg b/tests/jpeg/inf_loop02.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/inf_loop02.jpg differ
diff --git a/tests/jpeg/mand_prgrsv.jpg b/tests/jpeg/mand_prgrsv.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/mand_prgrsv.jpg differ
diff --git a/tests/jpeg/rgb.jpg b/tests/jpeg/rgb.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/rgb.jpg differ
diff --git a/tests/jpeg/richys-groceries.jpg b/tests/jpeg/richys-groceries.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/richys-groceries.jpg differ
diff --git a/tests/jpeg/sheep.jpg b/tests/jpeg/sheep.jpg
new file mode 100644
Binary files /dev/null and b/tests/jpeg/sheep.jpg differ
diff --git a/tests/palette/barb.png b/tests/palette/barb.png
new file mode 100644
Binary files /dev/null and b/tests/palette/barb.png differ
diff --git a/tests/palette/frog.png b/tests/palette/frog.png
new file mode 100644
Binary files /dev/null and b/tests/palette/frog.png differ
diff --git a/tests/palette/lena.png b/tests/palette/lena.png
new file mode 100644
Binary files /dev/null and b/tests/palette/lena.png differ
diff --git a/tests/palette/mandrill.png b/tests/palette/mandrill.png
new file mode 100644
Binary files /dev/null and b/tests/palette/mandrill.png differ
diff --git a/tests/palette/seniors.png b/tests/palette/seniors.png
new file mode 100644
Binary files /dev/null and b/tests/palette/seniors.png differ
diff --git a/tests/planeseparation.png b/tests/planeseparation.png
new file mode 100644
Binary files /dev/null and b/tests/planeseparation.png differ
diff --git a/tests/planeseparationrgba.png b/tests/planeseparationrgba.png
new file mode 100644
Binary files /dev/null and b/tests/planeseparationrgba.png differ
diff --git a/tests/pngsuite/PngSuite.LICENSE b/tests/pngsuite/PngSuite.LICENSE
new file mode 100644
--- /dev/null
+++ b/tests/pngsuite/PngSuite.LICENSE
@@ -0,0 +1,9 @@
+PngSuite
+--------
+
+Permission to use, copy, modify and distribute these images for any
+purpose and without fee is hereby granted.
+
+
+(c) Willem van Schaik, 1996, 2011
+
diff --git a/tests/pngsuite/PngSuite.README b/tests/pngsuite/PngSuite.README
new file mode 100644
--- /dev/null
+++ b/tests/pngsuite/PngSuite.README
@@ -0,0 +1,25 @@
+        PNGSUITE
+----------------
+
+        testset for PNG-(de)coders
+        created by Willem van Schaik
+------------------------------------
+
+This is a collection of graphics images created to test the png applications
+like viewers, converters and editors. All (as far as that is possible)
+formats supported by the PNG standard are represented.
+
+The suite consists of the following files:
+
+-	PngSuite.README		- this file
+-	PngSuite.LICENSE	- the PngSuite is freeware
+-	PngSuite.png		- image with PngSuite logo
+-	PngSuite.tgz		- archive of all PNG testfiles
+-	PngSuite.zip		- same in .zip format for PCs
+
+
+--------
+    (c) Willem van Schaik
+	willem@schaik.com
+        Calgary, April 2011
+
diff --git a/tests/pngsuite/PngSuite.png b/tests/pngsuite/PngSuite.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/PngSuite.png differ
diff --git a/tests/pngsuite/basi0g01.png b/tests/pngsuite/basi0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi0g01.png differ
diff --git a/tests/pngsuite/basi0g02.png b/tests/pngsuite/basi0g02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi0g02.png differ
diff --git a/tests/pngsuite/basi0g04.png b/tests/pngsuite/basi0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi0g04.png differ
diff --git a/tests/pngsuite/basi0g08.png b/tests/pngsuite/basi0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi0g08.png differ
diff --git a/tests/pngsuite/basi0g16.png b/tests/pngsuite/basi0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi0g16.png differ
diff --git a/tests/pngsuite/basi2c08.png b/tests/pngsuite/basi2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi2c08.png differ
diff --git a/tests/pngsuite/basi2c16.png b/tests/pngsuite/basi2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi2c16.png differ
diff --git a/tests/pngsuite/basi3p01.png b/tests/pngsuite/basi3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi3p01.png differ
diff --git a/tests/pngsuite/basi3p02.png b/tests/pngsuite/basi3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi3p02.png differ
diff --git a/tests/pngsuite/basi3p04.png b/tests/pngsuite/basi3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi3p04.png differ
diff --git a/tests/pngsuite/basi3p08.png b/tests/pngsuite/basi3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi3p08.png differ
diff --git a/tests/pngsuite/basi4a08.png b/tests/pngsuite/basi4a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi4a08.png differ
diff --git a/tests/pngsuite/basi4a16.png b/tests/pngsuite/basi4a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi4a16.png differ
diff --git a/tests/pngsuite/basi6a08.png b/tests/pngsuite/basi6a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi6a08.png differ
diff --git a/tests/pngsuite/basi6a16.png b/tests/pngsuite/basi6a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basi6a16.png differ
diff --git a/tests/pngsuite/basn0g01.png b/tests/pngsuite/basn0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn0g01.png differ
diff --git a/tests/pngsuite/basn0g02.png b/tests/pngsuite/basn0g02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn0g02.png differ
diff --git a/tests/pngsuite/basn0g04.png b/tests/pngsuite/basn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn0g04.png differ
diff --git a/tests/pngsuite/basn0g08.png b/tests/pngsuite/basn0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn0g08.png differ
diff --git a/tests/pngsuite/basn0g16.png b/tests/pngsuite/basn0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn0g16.png differ
diff --git a/tests/pngsuite/basn2c08.png b/tests/pngsuite/basn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn2c08.png differ
diff --git a/tests/pngsuite/basn2c16.png b/tests/pngsuite/basn2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn2c16.png differ
diff --git a/tests/pngsuite/basn3p01.png b/tests/pngsuite/basn3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn3p01.png differ
diff --git a/tests/pngsuite/basn3p02.png b/tests/pngsuite/basn3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn3p02.png differ
diff --git a/tests/pngsuite/basn3p04.png b/tests/pngsuite/basn3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn3p04.png differ
diff --git a/tests/pngsuite/basn3p08.png b/tests/pngsuite/basn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn3p08.png differ
diff --git a/tests/pngsuite/basn4a08.png b/tests/pngsuite/basn4a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn4a08.png differ
diff --git a/tests/pngsuite/basn4a16.png b/tests/pngsuite/basn4a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn4a16.png differ
diff --git a/tests/pngsuite/basn6a08.png b/tests/pngsuite/basn6a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn6a08.png differ
diff --git a/tests/pngsuite/basn6a16.png b/tests/pngsuite/basn6a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/basn6a16.png differ
diff --git a/tests/pngsuite/bgai4a08.png b/tests/pngsuite/bgai4a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgai4a08.png differ
diff --git a/tests/pngsuite/bgai4a16.png b/tests/pngsuite/bgai4a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgai4a16.png differ
diff --git a/tests/pngsuite/bgan6a08.png b/tests/pngsuite/bgan6a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgan6a08.png differ
diff --git a/tests/pngsuite/bgan6a16.png b/tests/pngsuite/bgan6a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgan6a16.png differ
diff --git a/tests/pngsuite/bgbn4a08.png b/tests/pngsuite/bgbn4a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgbn4a08.png differ
diff --git a/tests/pngsuite/bggn4a16.png b/tests/pngsuite/bggn4a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bggn4a16.png differ
diff --git a/tests/pngsuite/bgwn6a08.png b/tests/pngsuite/bgwn6a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgwn6a08.png differ
diff --git a/tests/pngsuite/bgyn6a16.png b/tests/pngsuite/bgyn6a16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/bgyn6a16.png differ
diff --git a/tests/pngsuite/ccwn2c08.png b/tests/pngsuite/ccwn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ccwn2c08.png differ
diff --git a/tests/pngsuite/ccwn3p08.png b/tests/pngsuite/ccwn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ccwn3p08.png differ
diff --git a/tests/pngsuite/cdfn2c08.png b/tests/pngsuite/cdfn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cdfn2c08.png differ
diff --git a/tests/pngsuite/cdhn2c08.png b/tests/pngsuite/cdhn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cdhn2c08.png differ
diff --git a/tests/pngsuite/cdsn2c08.png b/tests/pngsuite/cdsn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cdsn2c08.png differ
diff --git a/tests/pngsuite/cdun2c08.png b/tests/pngsuite/cdun2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cdun2c08.png differ
diff --git a/tests/pngsuite/ch1n3p04.png b/tests/pngsuite/ch1n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ch1n3p04.png differ
diff --git a/tests/pngsuite/ch2n3p08.png b/tests/pngsuite/ch2n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ch2n3p08.png differ
diff --git a/tests/pngsuite/cm0n0g04.png b/tests/pngsuite/cm0n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cm0n0g04.png differ
diff --git a/tests/pngsuite/cm7n0g04.png b/tests/pngsuite/cm7n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cm7n0g04.png differ
diff --git a/tests/pngsuite/cm9n0g04.png b/tests/pngsuite/cm9n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cm9n0g04.png differ
diff --git a/tests/pngsuite/cs3n2c16.png b/tests/pngsuite/cs3n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs3n2c16.png differ
diff --git a/tests/pngsuite/cs3n3p08.png b/tests/pngsuite/cs3n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs3n3p08.png differ
diff --git a/tests/pngsuite/cs5n2c08.png b/tests/pngsuite/cs5n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs5n2c08.png differ
diff --git a/tests/pngsuite/cs5n3p08.png b/tests/pngsuite/cs5n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs5n3p08.png differ
diff --git a/tests/pngsuite/cs8n2c08.png b/tests/pngsuite/cs8n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs8n2c08.png differ
diff --git a/tests/pngsuite/cs8n3p08.png b/tests/pngsuite/cs8n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cs8n3p08.png differ
diff --git a/tests/pngsuite/ct0n0g04.png b/tests/pngsuite/ct0n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ct0n0g04.png differ
diff --git a/tests/pngsuite/ct1n0g04.png b/tests/pngsuite/ct1n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ct1n0g04.png differ
diff --git a/tests/pngsuite/cten0g04.png b/tests/pngsuite/cten0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cten0g04.png differ
diff --git a/tests/pngsuite/ctfn0g04.png b/tests/pngsuite/ctfn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ctfn0g04.png differ
diff --git a/tests/pngsuite/ctgn0g04.png b/tests/pngsuite/ctgn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ctgn0g04.png differ
diff --git a/tests/pngsuite/cthn0g04.png b/tests/pngsuite/cthn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/cthn0g04.png differ
diff --git a/tests/pngsuite/ctjn0g04.png b/tests/pngsuite/ctjn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ctjn0g04.png differ
diff --git a/tests/pngsuite/ctzn0g04.png b/tests/pngsuite/ctzn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ctzn0g04.png differ
diff --git a/tests/pngsuite/f00n0g08.png b/tests/pngsuite/f00n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f00n0g08.png differ
diff --git a/tests/pngsuite/f00n2c08.png b/tests/pngsuite/f00n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f00n2c08.png differ
diff --git a/tests/pngsuite/f01n0g08.png b/tests/pngsuite/f01n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f01n0g08.png differ
diff --git a/tests/pngsuite/f01n2c08.png b/tests/pngsuite/f01n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f01n2c08.png differ
diff --git a/tests/pngsuite/f02n0g08.png b/tests/pngsuite/f02n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f02n0g08.png differ
diff --git a/tests/pngsuite/f02n2c08.png b/tests/pngsuite/f02n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f02n2c08.png differ
diff --git a/tests/pngsuite/f03n0g08.png b/tests/pngsuite/f03n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f03n0g08.png differ
diff --git a/tests/pngsuite/f03n2c08.png b/tests/pngsuite/f03n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f03n2c08.png differ
diff --git a/tests/pngsuite/f04n0g08.png b/tests/pngsuite/f04n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f04n0g08.png differ
diff --git a/tests/pngsuite/f04n2c08.png b/tests/pngsuite/f04n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f04n2c08.png differ
diff --git a/tests/pngsuite/f99n0g04.png b/tests/pngsuite/f99n0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/f99n0g04.png differ
diff --git a/tests/pngsuite/g03n0g16.png b/tests/pngsuite/g03n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g03n0g16.png differ
diff --git a/tests/pngsuite/g03n2c08.png b/tests/pngsuite/g03n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g03n2c08.png differ
diff --git a/tests/pngsuite/g03n3p04.png b/tests/pngsuite/g03n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g03n3p04.png differ
diff --git a/tests/pngsuite/g04n0g16.png b/tests/pngsuite/g04n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g04n0g16.png differ
diff --git a/tests/pngsuite/g04n2c08.png b/tests/pngsuite/g04n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g04n2c08.png differ
diff --git a/tests/pngsuite/g04n3p04.png b/tests/pngsuite/g04n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g04n3p04.png differ
diff --git a/tests/pngsuite/g05n0g16.png b/tests/pngsuite/g05n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g05n0g16.png differ
diff --git a/tests/pngsuite/g05n2c08.png b/tests/pngsuite/g05n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g05n2c08.png differ
diff --git a/tests/pngsuite/g05n3p04.png b/tests/pngsuite/g05n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g05n3p04.png differ
diff --git a/tests/pngsuite/g07n0g16.png b/tests/pngsuite/g07n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g07n0g16.png differ
diff --git a/tests/pngsuite/g07n2c08.png b/tests/pngsuite/g07n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g07n2c08.png differ
diff --git a/tests/pngsuite/g07n3p04.png b/tests/pngsuite/g07n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g07n3p04.png differ
diff --git a/tests/pngsuite/g10n0g16.png b/tests/pngsuite/g10n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g10n0g16.png differ
diff --git a/tests/pngsuite/g10n2c08.png b/tests/pngsuite/g10n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g10n2c08.png differ
diff --git a/tests/pngsuite/g10n3p04.png b/tests/pngsuite/g10n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g10n3p04.png differ
diff --git a/tests/pngsuite/g25n0g16.png b/tests/pngsuite/g25n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g25n0g16.png differ
diff --git a/tests/pngsuite/g25n2c08.png b/tests/pngsuite/g25n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g25n2c08.png differ
diff --git a/tests/pngsuite/g25n3p04.png b/tests/pngsuite/g25n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/g25n3p04.png differ
diff --git a/tests/pngsuite/huge.png b/tests/pngsuite/huge.png
new file mode 100644
# file too large to diff: tests/pngsuite/huge.png
diff --git a/tests/pngsuite/megaman.png b/tests/pngsuite/megaman.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/megaman.png differ
diff --git a/tests/pngsuite/oi1n0g16.png b/tests/pngsuite/oi1n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi1n0g16.png differ
diff --git a/tests/pngsuite/oi1n2c16.png b/tests/pngsuite/oi1n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi1n2c16.png differ
diff --git a/tests/pngsuite/oi2n0g16.png b/tests/pngsuite/oi2n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi2n0g16.png differ
diff --git a/tests/pngsuite/oi2n2c16.png b/tests/pngsuite/oi2n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi2n2c16.png differ
diff --git a/tests/pngsuite/oi4n0g16.png b/tests/pngsuite/oi4n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi4n0g16.png differ
diff --git a/tests/pngsuite/oi4n2c16.png b/tests/pngsuite/oi4n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi4n2c16.png differ
diff --git a/tests/pngsuite/oi9n0g16.png b/tests/pngsuite/oi9n0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi9n0g16.png differ
diff --git a/tests/pngsuite/oi9n2c16.png b/tests/pngsuite/oi9n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/oi9n2c16.png differ
diff --git a/tests/pngsuite/pp0n2c16.png b/tests/pngsuite/pp0n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/pp0n2c16.png differ
diff --git a/tests/pngsuite/pp0n6a08.png b/tests/pngsuite/pp0n6a08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/pp0n6a08.png differ
diff --git a/tests/pngsuite/ps1n0g08.png b/tests/pngsuite/ps1n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ps1n0g08.png differ
diff --git a/tests/pngsuite/ps1n2c16.png b/tests/pngsuite/ps1n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ps1n2c16.png differ
diff --git a/tests/pngsuite/ps2n0g08.png b/tests/pngsuite/ps2n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ps2n0g08.png differ
diff --git a/tests/pngsuite/ps2n2c16.png b/tests/pngsuite/ps2n2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/ps2n2c16.png differ
diff --git a/tests/pngsuite/s01i3p01.png b/tests/pngsuite/s01i3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s01i3p01.png differ
diff --git a/tests/pngsuite/s01n3p01.png b/tests/pngsuite/s01n3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s01n3p01.png differ
diff --git a/tests/pngsuite/s02i3p01.png b/tests/pngsuite/s02i3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s02i3p01.png differ
diff --git a/tests/pngsuite/s02n3p01.png b/tests/pngsuite/s02n3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s02n3p01.png differ
diff --git a/tests/pngsuite/s03i3p01.png b/tests/pngsuite/s03i3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s03i3p01.png differ
diff --git a/tests/pngsuite/s03n3p01.png b/tests/pngsuite/s03n3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s03n3p01.png differ
diff --git a/tests/pngsuite/s04i3p01.png b/tests/pngsuite/s04i3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s04i3p01.png differ
diff --git a/tests/pngsuite/s04n3p01.png b/tests/pngsuite/s04n3p01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s04n3p01.png differ
diff --git a/tests/pngsuite/s05i3p02.png b/tests/pngsuite/s05i3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s05i3p02.png differ
diff --git a/tests/pngsuite/s05n3p02.png b/tests/pngsuite/s05n3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s05n3p02.png differ
diff --git a/tests/pngsuite/s06i3p02.png b/tests/pngsuite/s06i3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s06i3p02.png differ
diff --git a/tests/pngsuite/s06n3p02.png b/tests/pngsuite/s06n3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s06n3p02.png differ
diff --git a/tests/pngsuite/s07i3p02.png b/tests/pngsuite/s07i3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s07i3p02.png differ
diff --git a/tests/pngsuite/s07n3p02.png b/tests/pngsuite/s07n3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s07n3p02.png differ
diff --git a/tests/pngsuite/s08i3p02.png b/tests/pngsuite/s08i3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s08i3p02.png differ
diff --git a/tests/pngsuite/s08n3p02.png b/tests/pngsuite/s08n3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s08n3p02.png differ
diff --git a/tests/pngsuite/s09i3p02.png b/tests/pngsuite/s09i3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s09i3p02.png differ
diff --git a/tests/pngsuite/s09n3p02.png b/tests/pngsuite/s09n3p02.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s09n3p02.png differ
diff --git a/tests/pngsuite/s32i3p04.png b/tests/pngsuite/s32i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s32i3p04.png differ
diff --git a/tests/pngsuite/s32n3p04.png b/tests/pngsuite/s32n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s32n3p04.png differ
diff --git a/tests/pngsuite/s33i3p04.png b/tests/pngsuite/s33i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s33i3p04.png differ
diff --git a/tests/pngsuite/s33n3p04.png b/tests/pngsuite/s33n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s33n3p04.png differ
diff --git a/tests/pngsuite/s34i3p04.png b/tests/pngsuite/s34i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s34i3p04.png differ
diff --git a/tests/pngsuite/s34n3p04.png b/tests/pngsuite/s34n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s34n3p04.png differ
diff --git a/tests/pngsuite/s35i3p04.png b/tests/pngsuite/s35i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s35i3p04.png differ
diff --git a/tests/pngsuite/s35n3p04.png b/tests/pngsuite/s35n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s35n3p04.png differ
diff --git a/tests/pngsuite/s36i3p04.png b/tests/pngsuite/s36i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s36i3p04.png differ
diff --git a/tests/pngsuite/s36n3p04.png b/tests/pngsuite/s36n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s36n3p04.png differ
diff --git a/tests/pngsuite/s37i3p04.png b/tests/pngsuite/s37i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s37i3p04.png differ
diff --git a/tests/pngsuite/s37n3p04.png b/tests/pngsuite/s37n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s37n3p04.png differ
diff --git a/tests/pngsuite/s38i3p04.png b/tests/pngsuite/s38i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s38i3p04.png differ
diff --git a/tests/pngsuite/s38n3p04.png b/tests/pngsuite/s38n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s38n3p04.png differ
diff --git a/tests/pngsuite/s39i3p04.png b/tests/pngsuite/s39i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s39i3p04.png differ
diff --git a/tests/pngsuite/s39n3p04.png b/tests/pngsuite/s39n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s39n3p04.png differ
diff --git a/tests/pngsuite/s40i3p04.png b/tests/pngsuite/s40i3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s40i3p04.png differ
diff --git a/tests/pngsuite/s40n3p04.png b/tests/pngsuite/s40n3p04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/s40n3p04.png differ
diff --git a/tests/pngsuite/tbbn0g04.png b/tests/pngsuite/tbbn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbbn0g04.png differ
diff --git a/tests/pngsuite/tbbn2c16.png b/tests/pngsuite/tbbn2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbbn2c16.png differ
diff --git a/tests/pngsuite/tbbn3p08.png b/tests/pngsuite/tbbn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbbn3p08.png differ
diff --git a/tests/pngsuite/tbgn2c16.png b/tests/pngsuite/tbgn2c16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbgn2c16.png differ
diff --git a/tests/pngsuite/tbgn3p08.png b/tests/pngsuite/tbgn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbgn3p08.png differ
diff --git a/tests/pngsuite/tbrn2c08.png b/tests/pngsuite/tbrn2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbrn2c08.png differ
diff --git a/tests/pngsuite/tbwn0g16.png b/tests/pngsuite/tbwn0g16.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbwn0g16.png differ
diff --git a/tests/pngsuite/tbwn3p08.png b/tests/pngsuite/tbwn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbwn3p08.png differ
diff --git a/tests/pngsuite/tbyn3p08.png b/tests/pngsuite/tbyn3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tbyn3p08.png differ
diff --git a/tests/pngsuite/tp0n0g08.png b/tests/pngsuite/tp0n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tp0n0g08.png differ
diff --git a/tests/pngsuite/tp0n2c08.png b/tests/pngsuite/tp0n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tp0n2c08.png differ
diff --git a/tests/pngsuite/tp0n3p08.png b/tests/pngsuite/tp0n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tp0n3p08.png differ
diff --git a/tests/pngsuite/tp1n3p08.png b/tests/pngsuite/tp1n3p08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/tp1n3p08.png differ
diff --git a/tests/pngsuite/xc1n0g08.png b/tests/pngsuite/xc1n0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xc1n0g08.png differ
diff --git a/tests/pngsuite/xc9n2c08.png b/tests/pngsuite/xc9n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xc9n2c08.png differ
diff --git a/tests/pngsuite/xcrn0g04.png b/tests/pngsuite/xcrn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xcrn0g04.png differ
diff --git a/tests/pngsuite/xcsn0g01.png b/tests/pngsuite/xcsn0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xcsn0g01.png differ
diff --git a/tests/pngsuite/xd0n2c08.png b/tests/pngsuite/xd0n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xd0n2c08.png differ
diff --git a/tests/pngsuite/xd3n2c08.png b/tests/pngsuite/xd3n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xd3n2c08.png differ
diff --git a/tests/pngsuite/xd9n2c08.png b/tests/pngsuite/xd9n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xd9n2c08.png differ
diff --git a/tests/pngsuite/xdtn0g01.png b/tests/pngsuite/xdtn0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xdtn0g01.png differ
diff --git a/tests/pngsuite/xhdn0g08.png b/tests/pngsuite/xhdn0g08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xhdn0g08.png differ
diff --git a/tests/pngsuite/xlfn0g04.png b/tests/pngsuite/xlfn0g04.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xlfn0g04.png differ
diff --git a/tests/pngsuite/xs1n0g01.png b/tests/pngsuite/xs1n0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xs1n0g01.png differ
diff --git a/tests/pngsuite/xs2n0g01.png b/tests/pngsuite/xs2n0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xs2n0g01.png differ
diff --git a/tests/pngsuite/xs4n0g01.png b/tests/pngsuite/xs4n0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xs4n0g01.png differ
diff --git a/tests/pngsuite/xs7n0g01.png b/tests/pngsuite/xs7n0g01.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/xs7n0g01.png differ
diff --git a/tests/pngsuite/z00n2c08.png b/tests/pngsuite/z00n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/z00n2c08.png differ
diff --git a/tests/pngsuite/z03n2c08.png b/tests/pngsuite/z03n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/z03n2c08.png differ
diff --git a/tests/pngsuite/z06n2c08.png b/tests/pngsuite/z06n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/z06n2c08.png differ
diff --git a/tests/pngsuite/z09n2c08.png b/tests/pngsuite/z09n2c08.png
new file mode 100644
Binary files /dev/null and b/tests/pngsuite/z09n2c08.png differ
diff --git a/tests/radiance/free_009.hdr b/tests/radiance/free_009.hdr
new file mode 100644
Binary files /dev/null and b/tests/radiance/free_009.hdr differ
diff --git a/tests/radiance/sunrise.hdr b/tests/radiance/sunrise.hdr
new file mode 100644
Binary files /dev/null and b/tests/radiance/sunrise.hdr differ
diff --git a/tests/tga/CBW8.TGA b/tests/tga/CBW8.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/CBW8.TGA differ
diff --git a/tests/tga/CCM8.TGA b/tests/tga/CCM8.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/CCM8.TGA differ
diff --git a/tests/tga/CTC16.TGA b/tests/tga/CTC16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/CTC16.TGA differ
diff --git a/tests/tga/CTC24.TGA b/tests/tga/CTC24.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/CTC24.TGA differ
diff --git a/tests/tga/CTC32.TGA b/tests/tga/CTC32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/CTC32.TGA differ
diff --git a/tests/tga/FLAG_B16.TGA b/tests/tga/FLAG_B16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/FLAG_B16.TGA differ
diff --git a/tests/tga/FLAG_B24.TGA b/tests/tga/FLAG_B24.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/FLAG_B24.TGA differ
diff --git a/tests/tga/FLAG_B32.TGA b/tests/tga/FLAG_B32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/FLAG_B32.TGA differ
diff --git a/tests/tga/FLAG_T16.TGA b/tests/tga/FLAG_T16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/FLAG_T16.TGA differ
diff --git a/tests/tga/FLAG_T32.TGA b/tests/tga/FLAG_T32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/FLAG_T32.TGA differ
diff --git a/tests/tga/MARBLES.TGA b/tests/tga/MARBLES.TGA
new file mode 100644
# file too large to diff: tests/tga/MARBLES.TGA
diff --git a/tests/tga/UBW8.TGA b/tests/tga/UBW8.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/UBW8.TGA differ
diff --git a/tests/tga/UCM8.TGA b/tests/tga/UCM8.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/UCM8.TGA differ
diff --git a/tests/tga/UTC16.TGA b/tests/tga/UTC16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/UTC16.TGA differ
diff --git a/tests/tga/UTC24.TGA b/tests/tga/UTC24.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/UTC24.TGA differ
diff --git a/tests/tga/UTC32.TGA b/tests/tga/UTC32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/UTC32.TGA differ
diff --git a/tests/tga/XING_B16.TGA b/tests/tga/XING_B16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_B16.TGA differ
diff --git a/tests/tga/XING_B24.TGA b/tests/tga/XING_B24.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_B24.TGA differ
diff --git a/tests/tga/XING_B32.TGA b/tests/tga/XING_B32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_B32.TGA differ
diff --git a/tests/tga/XING_T16.TGA b/tests/tga/XING_T16.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_T16.TGA differ
diff --git a/tests/tga/XING_T24.TGA b/tests/tga/XING_T24.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_T24.TGA differ
diff --git a/tests/tga/XING_T32.TGA b/tests/tga/XING_T32.TGA
new file mode 100644
Binary files /dev/null and b/tests/tga/XING_T32.TGA differ
diff --git a/tests/tga/tgatest.c b/tests/tga/tgatest.c
new file mode 100644
--- /dev/null
+++ b/tests/tga/tgatest.c
@@ -0,0 +1,196 @@
+#include "stdio.h"
+#include "stdlib.h"
+#include "math.h"
+
+/*
+   The following is rather crude demonstration code to read 
+   uncompressed and compressed TGA files of 16, 24, or 32 bit 
+   TGA. 
+   Hope it is helpful.
+*/
+
+typedef struct {
+   char  idlength;
+   char  colourmaptype;
+   char  datatypecode;
+   short int colourmaporigin;
+   short int colourmaplength;
+   char  colourmapdepth;
+   short int x_origin;
+   short int y_origin;
+   short width;
+   short height;
+   char  bitsperpixel;
+   char  imagedescriptor;
+} HEADER;
+
+typedef struct {
+   unsigned char r,g,b,a;
+} PIXEL;
+
+void MergeBytes(PIXEL *,unsigned char *,int);
+
+int main(int argc,char **argv)
+{
+   int n=0,i,j;
+   int bytes2read,skipover = 0;
+   unsigned char p[5];
+   FILE *fptr;
+   HEADER header;
+   PIXEL *pixels;
+
+   if (argc < 2) {
+      fprintf(stderr,"Usage: %s tgafile\n",argv[0]);
+      exit(-1);
+   }
+
+   /* Open the file */
+   if ((fptr = fopen(argv[1],"r")) == NULL) {
+      fprintf(stderr,"File open failed\n");
+      exit(-1);
+   }
+
+   /* Display the header fields */
+   header.idlength = fgetc(fptr);
+   fprintf(stderr,"ID length:         %d\n",header.idlength);
+   header.colourmaptype = fgetc(fptr);
+   fprintf(stderr,"Colourmap type:    %d\n",header.colourmaptype);
+   header.datatypecode = fgetc(fptr);
+   fprintf(stderr,"Image type:        %d\n",header.datatypecode);
+   fread(&header.colourmaporigin,2,1,fptr);
+   fprintf(stderr,"Colour map offset: %d\n",header.colourmaporigin);
+   fread(&header.colourmaplength,2,1,fptr);
+   fprintf(stderr,"Colour map length: %d\n",header.colourmaplength); 
+   header.colourmapdepth = fgetc(fptr);
+   fprintf(stderr,"Colour map depth:  %d\n",header.colourmapdepth);
+   fread(&header.x_origin,2,1,fptr);
+   fprintf(stderr,"X origin:          %d\n",header.x_origin);
+   fread(&header.y_origin,2,1,fptr);
+   fprintf(stderr,"Y origin:          %d\n",header.y_origin);
+   fread(&header.width,2,1,fptr);
+   fprintf(stderr,"Width:             %d\n",header.width);
+   fread(&header.height,2,1,fptr);
+   fprintf(stderr,"Height:            %d\n",header.height);
+   header.bitsperpixel = fgetc(fptr);
+   fprintf(stderr,"Bits per pixel:    %d\n",header.bitsperpixel);
+   header.imagedescriptor = fgetc(fptr);
+   fprintf(stderr,"Descriptor:        %d\n",header.imagedescriptor);
+
+   /* Allocate space for the image */
+   if ((pixels = malloc(header.width*header.height*sizeof(PIXEL))) == NULL) {
+      fprintf(stderr,"malloc of image failed\n");
+      exit(-1);
+   }
+   for (i=0;i<header.width*header.height;i++) {
+      pixels[i].r = 0;
+      pixels[i].g = 0;
+      pixels[i].b = 0;
+      pixels[i].a = 0;
+   }
+
+   /* What can we handle */
+   if (header.datatypecode != 2 && header.datatypecode != 10) {
+      printf(stderr,"Can only handle image type 2 and 10\n");
+      exit(-1);
+   }
+   if (header.bitsperpixel != 16 && 
+       header.bitsperpixel != 24 && header.bitsperpixel != 32) {
+      fprintf(stderr,"Can only handle pixel depths of 16, 24, and 32\n");
+      exit(-1);
+   }
+   if (header.colourmaptype != 0 && header.colourmaptype != 1) {
+      fprintf(stderr,"Can only handle colour map types of 0 and 1\n");
+      exit(-1);
+   }
+
+   /* Skip over unnecessary stuff */
+   skipover += header.idlength;
+   skipover += header.colourmaptype * header.colourmaplength;
+   fprintf(stderr,"Skip over %d bytes\n",skipover);
+   fseek(fptr,skipover,SEEK_CUR);
+
+   /* Read the image */
+   bytes2read = header.bitsperpixel / 8;
+   while (n < header.width * header.height) {
+      if (header.datatypecode == 2) {                     /* Uncompressed */
+         if (fread(p,1,bytes2read,fptr) != bytes2read) {
+            fprintf(stderr,"Unexpected end of file at pixel %d\n",i);
+            exit(-1);
+         }
+         MergeBytes(&(pixels[n]),p,bytes2read);
+         n++;
+      } else if (header.datatypecode == 10) {             /* Compressed */
+         if (fread(p,1,bytes2read+1,fptr) != bytes2read+1) {
+            fprintf(stderr,"Unexpected end of file at pixel %d\n",i);
+            exit(-1);
+         }
+         j = p[0] & 0x7f;
+         MergeBytes(&(pixels[n]),&(p[1]),bytes2read);
+         n++;
+         if (p[0] & 0x80) {         /* RLE chunk */
+            for (i=0;i<j;i++) {
+               MergeBytes(&(pixels[n]),&(p[1]),bytes2read);
+               n++;
+            }
+         } else {                   /* Normal chunk */
+            for (i=0;i<j;i++) {
+               if (fread(p,1,bytes2read,fptr) != bytes2read) {
+                  fprintf(stderr,"Unexpected end of file at pixel %d\n",i);
+                  exit(-1);
+               }
+               MergeBytes(&(pixels[n]),p,bytes2read);
+               n++;
+            }
+         }
+      }
+   }
+   fclose(fptr);
+
+   /* Write the result as a uncompressed TGA */
+   if ((fptr = fopen("tgatest.tga","w")) == NULL) {
+      fprintf(stderr,"Failed to open outputfile\n");
+      exit(-1);
+   }
+   putc(0,fptr);
+   putc(0,fptr);
+   putc(2,fptr);                         /* uncompressed RGB */
+   putc(0,fptr); putc(0,fptr);
+   putc(0,fptr); putc(0,fptr);
+   putc(0,fptr);
+   putc(0,fptr); putc(0,fptr);           /* X origin */
+   putc(0,fptr); putc(0,fptr);           /* y origin */
+   putc((header.width & 0x00FF),fptr);
+   putc((header.width & 0xFF00) / 256,fptr);
+   putc((header.height & 0x00FF),fptr);
+   putc((header.height & 0xFF00) / 256,fptr);
+   putc(32,fptr);                        /* 24 bit bitmap */
+   putc(0,fptr);
+   for (i=0;i<header.height*header.width;i++) {
+      putc(pixels[i].b,fptr);
+      putc(pixels[i].g,fptr);
+      putc(pixels[i].r,fptr);
+      putc(pixels[i].a,fptr);
+   }
+   fclose(fptr);
+}
+
+void MergeBytes(PIXEL *pixel,unsigned char *p,int bytes)
+{
+   if (bytes == 4) {
+      pixel->r = p[2];
+      pixel->g = p[1];
+      pixel->b = p[0];
+      pixel->a = p[3];
+   } else if (bytes == 3) {
+      pixel->r = p[2];
+      pixel->g = p[1];
+      pixel->b = p[0];
+      pixel->a = 0;
+   } else if (bytes == 2) {
+      pixel->r = (p[1] & 0x7c) << 1;
+      pixel->g = ((p[1] & 0x03) << 6) | ((p[0] & 0xe0) >> 2);
+      pixel->b = (p[0] & 0x1f) << 3;
+      pixel->a = (p[1] & 0x80);
+   }
+}
+
diff --git a/tests/tiff/README b/tests/tiff/README
new file mode 100644
--- /dev/null
+++ b/tests/tiff/README
@@ -0,0 +1,101 @@
+The following image files are included for testing.  Note that a wide
+variety of images can be generated using the tools provided with the
+library (e.g. tiffcp, tiff2bw, tiffmedian, etc.); see below for some
+hints on this.
+
+PlanarConfiguration = 1 (packed data)
+-------------------------------------
+caspian.tif	279x220 64-bit floating point (deflate) Caspian Sea from space
+cramps.tif	800x607 8-bit b&w (packbits) "cramps poster"
+cramps-tile.tif	256x256 tiled version of cramps.tif (no compression)
+dscf0013.tif	640x480 YCbCr digital camera image which lacks Reference
+		Black/White values. Contains EXIF SubIFD. No compression.
+fax2d.tif	1728x1082 1-bit b&w (G3/2D) facsimile
+g3test.g3	raw Group 3 encoded fax file
+g3test.tif	TIFF equivalent of g3test.g3 created by fax2tiff
+jello.tif	256x192 8-bit RGB (lzw palette) Paul Heckbert "jello"
+ladoga.tif	158x118 16-bit unsigned, single band, deflate
+off_l16.tif	333x225 8-bit CIE LogL (SGILog) office from Greg Larson
+off_luv24.tif	333x225 8-bit CIE LogLuv (SGILog24) office from " "
+off_luv32.tif	333x225	8-bit CIE LogLuv (SGILog) office from " "
+pc260001.tif	640x480 8-bit RGB digital camera image. Contains EXIF SubIFD.
+		No compression.
+quad-jpeg.tif	512x384 8-bit YCbCr (jpeg) version of quad-lzw.tif
+quad-lzw.tif	512x384 8-bit RGB (lzw) "quadric surfaces"
+quad-tile.tif	512x384 tiled version of quad-lzw.tif (lzw)
+strike.tif	256x200 8-bit RGBA (lzw) "bowling pins" from Pixar
+text.tif	1512x359 4-bit b&w (thunderscan) am-express credit card
+ycbcr-cat.tif	250x325 8-bit YCbCr (lzw) "kitty" created by rgb2ycbcr
+
+smallliz.tif	160x160 8-bit YCbCr (OLD jpeg) lizard from HP**
+zackthecat.tif	234x213 8-bit YCbCr (OLD jpeg) tiled "ZackTheCat" from NeXT**
+
+** These images are in a deprecated format and are included only for testing
+   backwards compatibility.  JPEG-encoded TIFF images use a different scheme
+   described in TIFF Technical Note #2 and implemented by libtiff.
+
+PlanarConfiguration = 2 (separated samples)
+-------------------------------------------
+oxford.tif	601x81 8-bit RGB (lzw) screendump off oxford
+
+The other images are from Hewlett Packard and exemplify the use of the
+HalftoneHints tag (in their words):
+
+The images are all the same subject, and should all appear the same
+after rendering.  Each of the images is slightly different as outlined
+by the following table:
+
+   FileName	   ToneRange  HalftoneHints
+jim___cg.tif      	A	    Y
+jim___dg.tif      	B	    N
+jim___gg.tif      	B	    Y
+
+The images with tone range A are 0-100% linear reflectance images,
+in other words, fixed full gamut tone range.  The images with tone
+range B are what we call "normalized", meaning that the image has
+been tone adjusted such the Highlight and Shadow are at gray levels
+1 & 2**BitsPerSample-2.
+
+Each of the three grayscale images should be rendered to look like
+the halftone in pics/jim___ah.tif when printed on a Canon SX engine.
+
+Generated Images
+----------------
+The file g3test.tif was created from g3test.g3 with the command:
+
+    fax2tiff -o t.tif -1 -p -M -R 98 g3test.g3
+
+Tiled images can be created with tiffcp; e.g.
+
+    tiffcp -t -c none cramps.tif cramps-tile.tif
+
+(but the tiled images included here were actually generated by the
+Silicon Graphics Image Library).
+
+The file quad-jpeg.tif was created from quad-lzw.tif with the command:
+
+    tiffcp -c jpeg quad-lzw.tif quad-jpeg.tif
+
+To generate a tiled image with separated samples the following might
+be used:
+
+    tiffcp -t -p separate quad-lzw.tif t.tif
+
+[ Beware that tiffcp does not handle every format TIFF image.  In particular,
+  when conversion between tiled and strip'd images is reliable only when
+  BitsPerSample is 8. ]
+
+To generate a G4-encoded image with a single strip the following would work:
+
+    tiffcp -c g4 -r 1082 fax2d.tif t.tif
+
+Contributing New Images
+-----------------------
+If you have images that are significantly different from those included
+in this package and that do NOT HAVE A COPYRIGHT; feel free to send them
+to me at sam@engr.sgi.com.  I prefer to receive a URL to a location from
+which I can retrieve the image by public FTP.  However if that is not
+possible you can send it to me in a mail message uuencode'd.  Please do
+not send large images by mail.  Also, please do not send me an image
+unless it is notably unique; e.g. not easily generated using the tools
+I provide.
diff --git a/tests/tiff/caspian.tif b/tests/tiff/caspian.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/caspian.tif differ
diff --git a/tests/tiff/compression/cs3n2c16.tif b/tests/tiff/compression/cs3n2c16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/compression/cs3n2c16.tif differ
diff --git a/tests/tiff/compression/flower-rgb-contig-16-packbits.tif b/tests/tiff/compression/flower-rgb-contig-16-packbits.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/compression/flower-rgb-contig-16-packbits.tif differ
diff --git a/tests/tiff/cramps-tile.tif b/tests/tiff/cramps-tile.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/cramps-tile.tif differ
diff --git a/tests/tiff/cramps.tif b/tests/tiff/cramps.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/cramps.tif differ
diff --git a/tests/tiff/depth/README.txt b/tests/tiff/depth/README.txt
new file mode 100644
--- /dev/null
+++ b/tests/tiff/depth/README.txt
@@ -0,0 +1,9 @@
+These sample TIFF image files are prepared by Bob Friesenhahn
+<bfriesen@simple.dallas.tx.us> using a development version of
+GraphicsMagick 1.2.
+
+See the file summary.txt for a description of the images.
+
+These files are hereby placed in the public domain.
+
+
diff --git a/tests/tiff/depth/flower-minisblack-02.tif b/tests/tiff/depth/flower-minisblack-02.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-02.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-04.tif b/tests/tiff/depth/flower-minisblack-04.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-04.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-06.tif b/tests/tiff/depth/flower-minisblack-06.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-06.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-08.tif b/tests/tiff/depth/flower-minisblack-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-08.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-10.tif b/tests/tiff/depth/flower-minisblack-10.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-10.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-12.tif b/tests/tiff/depth/flower-minisblack-12.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-12.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-14.tif b/tests/tiff/depth/flower-minisblack-14.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-14.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-16.tif b/tests/tiff/depth/flower-minisblack-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-16.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-24.tif b/tests/tiff/depth/flower-minisblack-24.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-24.tif differ
diff --git a/tests/tiff/depth/flower-minisblack-32.tif b/tests/tiff/depth/flower-minisblack-32.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-minisblack-32.tif differ
diff --git a/tests/tiff/depth/flower-palette-02.tif b/tests/tiff/depth/flower-palette-02.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-palette-02.tif differ
diff --git a/tests/tiff/depth/flower-palette-04.tif b/tests/tiff/depth/flower-palette-04.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-palette-04.tif differ
diff --git a/tests/tiff/depth/flower-palette-08.tif b/tests/tiff/depth/flower-palette-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-palette-08.tif differ
diff --git a/tests/tiff/depth/flower-palette-16.tif b/tests/tiff/depth/flower-palette-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-palette-16.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-02.tif b/tests/tiff/depth/flower-rgb-contig-02.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-02.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-04.tif b/tests/tiff/depth/flower-rgb-contig-04.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-04.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-08.tif b/tests/tiff/depth/flower-rgb-contig-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-08.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-10.tif b/tests/tiff/depth/flower-rgb-contig-10.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-10.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-12.tif b/tests/tiff/depth/flower-rgb-contig-12.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-12.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-14.tif b/tests/tiff/depth/flower-rgb-contig-14.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-14.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-16.tif b/tests/tiff/depth/flower-rgb-contig-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-16.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-24.tif b/tests/tiff/depth/flower-rgb-contig-24.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-24.tif differ
diff --git a/tests/tiff/depth/flower-rgb-contig-32.tif b/tests/tiff/depth/flower-rgb-contig-32.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-contig-32.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-02.tif b/tests/tiff/depth/flower-rgb-planar-02.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-02.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-04.tif b/tests/tiff/depth/flower-rgb-planar-04.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-04.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-08.tif b/tests/tiff/depth/flower-rgb-planar-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-08.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-10.tif b/tests/tiff/depth/flower-rgb-planar-10.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-10.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-12.tif b/tests/tiff/depth/flower-rgb-planar-12.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-12.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-14.tif b/tests/tiff/depth/flower-rgb-planar-14.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-14.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-16.tif b/tests/tiff/depth/flower-rgb-planar-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-16.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-24.tif b/tests/tiff/depth/flower-rgb-planar-24.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-24.tif differ
diff --git a/tests/tiff/depth/flower-rgb-planar-32.tif b/tests/tiff/depth/flower-rgb-planar-32.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-rgb-planar-32.tif differ
diff --git a/tests/tiff/depth/flower-separated-contig-08.tif b/tests/tiff/depth/flower-separated-contig-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-separated-contig-08.tif differ
diff --git a/tests/tiff/depth/flower-separated-contig-16.tif b/tests/tiff/depth/flower-separated-contig-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-separated-contig-16.tif differ
diff --git a/tests/tiff/depth/flower-separated-planar-08.tif b/tests/tiff/depth/flower-separated-planar-08.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-separated-planar-08.tif differ
diff --git a/tests/tiff/depth/flower-separated-planar-16.tif b/tests/tiff/depth/flower-separated-planar-16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/depth/flower-separated-planar-16.tif differ
diff --git a/tests/tiff/depth/summary.txt b/tests/tiff/depth/summary.txt
new file mode 100644
--- /dev/null
+++ b/tests/tiff/depth/summary.txt
@@ -0,0 +1,37 @@
+
+flower-minisblack-02.tif	73x43 2-bit minisblack gray image
+flower-minisblack-04.tif	73x43 4-bit minisblack gray image
+flower-minisblack-06.tif	73x43 6-bit minisblack gray image
+flower-minisblack-08.tif	73x43 8-bit minisblack gray image
+flower-minisblack-10.tif	73x43 10-bit minisblack gray image
+flower-minisblack-12.tif	73x43 12-bit minisblack gray image
+flower-minisblack-14.tif	73x43 14-bit minisblack gray image
+flower-minisblack-16.tif	73x43 16-bit minisblack gray image
+flower-minisblack-24.tif	73x43 24-bit minisblack gray image
+flower-minisblack-32.tif	73x43 32-bit minisblack gray image
+flower-palette-02.tif	73x43 4-entry colormapped image
+flower-palette-04.tif	73x43 16-entry colormapped image
+flower-palette-08.tif	73x43 256-entry colormapped image
+flower-palette-16.tif	73x43 65536-entry colormapped image
+flower-rgb-contig-02.tif	73x43 2-bit contiguous RGB image
+flower-rgb-contig-04.tif	73x43 4-bit contiguous RGB image
+flower-rgb-contig-08.tif	73x43 8-bit contiguous RGB image
+flower-rgb-contig-10.tif	73x43 10-bit contiguous RGB image
+flower-rgb-contig-12.tif	73x43 12-bit contiguous RGB image
+flower-rgb-contig-14.tif	73x43 14-bit contiguous RGB image
+flower-rgb-contig-16.tif	73x43 16-bit contiguous RGB image
+flower-rgb-contig-24.tif	73x43 24-bit contiguous RGB image
+flower-rgb-contig-32.tif	73x43 32-bit contiguous RGB image
+flower-rgb-planar-02.tif	73x43 2-bit seperated RGB image
+flower-rgb-planar-04.tif	73x43 4-bit seperated RGB image
+flower-rgb-planar-08.tif	73x43 8-bit seperated RGB image
+flower-rgb-planar-10.tif	73x43 10-bit seperated RGB image
+flower-rgb-planar-12.tif	73x43 12-bit seperated RGB image
+flower-rgb-planar-14.tif	73x43 14-bit seperated RGB image
+flower-rgb-planar-16.tif	73x43 16-bit seperated RGB image
+flower-rgb-planar-24.tif	73x43 24-bit seperated RGB image
+flower-rgb-planar-32.tif	73x43 32-bit seperated RGB image
+flower-separated-contig-08.tif	73x43 8-bit contiguous CMYK image
+flower-separated-contig-16.tif	73x43 16-bit contiguous CMYK image
+flower-separated-planar-08.tif	73x43 8-bit separated CMYK image
+flower-separated-planar-16.tif	73x43 16-bit separated CMYK image
diff --git a/tests/tiff/dscf0013.tif b/tests/tiff/dscf0013.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/dscf0013.tif differ
diff --git a/tests/tiff/fax2d.tif b/tests/tiff/fax2d.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/fax2d.tif differ
diff --git a/tests/tiff/g3test.g3 b/tests/tiff/g3test.g3
new file mode 100644
Binary files /dev/null and b/tests/tiff/g3test.g3 differ
diff --git a/tests/tiff/g3test.tif b/tests/tiff/g3test.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/g3test.tif differ
diff --git a/tests/tiff/horizontal-difference-lzw.tiff b/tests/tiff/horizontal-difference-lzw.tiff
new file mode 100644
Binary files /dev/null and b/tests/tiff/horizontal-difference-lzw.tiff differ
diff --git a/tests/tiff/jello.tif b/tests/tiff/jello.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/jello.tif differ
diff --git a/tests/tiff/jim___ah.tif b/tests/tiff/jim___ah.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/jim___ah.tif differ
diff --git a/tests/tiff/jim___cg.tif b/tests/tiff/jim___cg.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/jim___cg.tif differ
diff --git a/tests/tiff/jim___dg.tif b/tests/tiff/jim___dg.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/jim___dg.tif differ
diff --git a/tests/tiff/jim___gg.tif b/tests/tiff/jim___gg.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/jim___gg.tif differ
diff --git a/tests/tiff/ladoga.tif b/tests/tiff/ladoga.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/ladoga.tif differ
diff --git a/tests/tiff/off_l16.tif b/tests/tiff/off_l16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/off_l16.tif differ
diff --git a/tests/tiff/off_luv24.tif b/tests/tiff/off_luv24.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/off_luv24.tif differ
diff --git a/tests/tiff/off_luv32.tif b/tests/tiff/off_luv32.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/off_luv32.tif differ
diff --git a/tests/tiff/other/butique-YA16.tif b/tests/tiff/other/butique-YA16.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/other/butique-YA16.tif differ
diff --git a/tests/tiff/other/butique-YA8.tif b/tests/tiff/other/butique-YA8.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/other/butique-YA8.tif differ
diff --git a/tests/tiff/oxford.tif b/tests/tiff/oxford.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/oxford.tif differ
diff --git a/tests/tiff/pc260001.tif b/tests/tiff/pc260001.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/pc260001.tif differ
diff --git a/tests/tiff/quad-jpeg.tif b/tests/tiff/quad-jpeg.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/quad-jpeg.tif differ
diff --git a/tests/tiff/quad-lzw.tif b/tests/tiff/quad-lzw.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/quad-lzw.tif differ
diff --git a/tests/tiff/quad-tile.tif b/tests/tiff/quad-tile.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/quad-tile.tif differ
diff --git a/tests/tiff/rad_Y32.tif b/tests/tiff/rad_Y32.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/rad_Y32.tif differ
diff --git a/tests/tiff/rad_YF.tif b/tests/tiff/rad_YF.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/rad_YF.tif differ
diff --git a/tests/tiff/smallliz.tif b/tests/tiff/smallliz.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/smallliz.tif differ
diff --git a/tests/tiff/strike.tif b/tests/tiff/strike.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/strike.tif differ
diff --git a/tests/tiff/text.tif b/tests/tiff/text.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/text.tif differ
diff --git a/tests/tiff/ycbcr-cat.tif b/tests/tiff/ycbcr-cat.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/ycbcr-cat.tif differ
diff --git a/tests/tiff/zackthecat.tif b/tests/tiff/zackthecat.tif
new file mode 100644
Binary files /dev/null and b/tests/tiff/zackthecat.tif differ
