diff --git a/.ghci b/.ghci
new file mode 100644
--- /dev/null
+++ b/.ghci
@@ -0,0 +1,1 @@
+:set -XCPP -optP -DCABAL19
diff --git a/Debian/Apt/Dependencies.hs b/Debian/Apt/Dependencies.hs
--- a/Debian/Apt/Dependencies.hs
+++ b/Debian/Apt/Dependencies.hs
@@ -12,6 +12,7 @@
 
 -- test gutsyPackages "libc6" (\csp -> bt csp)
 
+import Control.Arrow (second)
 import qualified Data.ByteString.Char8 as BS
 import qualified Data.ByteString.Char8 as C
 import Data.List((++), foldr, concat, filter, map, any, elem, null, reverse, take, zipWith, find, union)
@@ -20,7 +21,7 @@
 import Debian.Apt.Package(PackageNameMap, packageNameMap, lookupPackageByRel)
 import Debian.Control.ByteString(ControlFunctions(stripWS, lookupP, parseControlFromFile), Field'(Field), Control'(Control), Paragraph, Control)
 import Debian.Relation.ByteString(ParseRelations(..), Relation(..), OrRelation, AndRelation, Relations, checkVersionReq)
-import Debian.Version(DebianVersion, parseDebianVersion)
+import Debian.Version(DebianVersion, parseDebianVersion, prettyDebianVersion)
 
 -- * Basic CSP Types and Functions
 
@@ -28,7 +29,7 @@
     = Remaining AndRelation
     | MissingDep Relation
     | Complete
-      deriving (Show, Eq)
+      deriving (Eq)
 
 type State a = (Status, [a])
 
@@ -94,7 +95,7 @@
 gutsyPackages = "/var/lib/apt/lists/mirror.anl.gov_pub_ubuntu_dists_gutsy_main_binary-i386_Packages"
 
 test controlFP rel labeler =
-    testCSP controlFP depF rel (mapM_ (\ (_,p) -> mapM_ (print . packageVersionParagraph) p ) . take 1 . search labeler)
+    testCSP controlFP depF rel (mapM_ (\ (_,p) -> mapM_ (print . second prettyDebianVersion . packageVersionParagraph) p ) . take 1 . search labeler)
 
 -- TODO: add better errors
 packageVersionParagraph :: Paragraph -> (String, DebianVersion)
diff --git a/Debian/Apt/Index.hs b/Debian/Apt/Index.hs
--- a/Debian/Apt/Index.hs
+++ b/Debian/Apt/Index.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE DeriveDataTypeable #-}
+{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-orphans #-}
 module Debian.Apt.Index
     ( update
     , Fetcher
@@ -93,7 +94,6 @@
     do let localPath' = localPath ++ ".bz2"
        --lm <- getLastModified localPath'
        res <- fetcher (uri { uriPath = (uriPath uri) ++ ".bz2" }) localPath' Nothing
-       return Nothing
        if res
           then return $ Just (localPath', BZ2)
           else do let localPath' = localPath ++ ".gz"
diff --git a/Debian/Apt/Methods.hs b/Debian/Apt/Methods.hs
--- a/Debian/Apt/Methods.hs
+++ b/Debian/Apt/Methods.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-name-shadowing #-}
 -- |an interface for using the methods in /var/lib/apt/methods
 module Debian.Apt.Methods
     ( withMethodPath
@@ -24,7 +25,6 @@
 
 import Control.Exception
 import Control.Monad.Error
-import Data.List
 import Data.Maybe
 import Data.Time
 import System.Directory
@@ -476,7 +476,7 @@
 {-
 groupOn :: (Ord b) => (a -> b) -> [a] -> [[a]]
 groupOn f = groupBy ((==) `on` f) . sortBy (compare `on` f)
--}
 
 on :: (a -> a -> b) -> (c -> a) -> c -> c -> b
 on f g x y = f (g x) (g y)
+-}
diff --git a/Debian/Changes.hs b/Debian/Changes.hs
--- a/Debian/Changes.hs
+++ b/Debian/Changes.hs
@@ -12,9 +12,7 @@
     , prettyEntry
     ) where
 
-import Data.Char (chr)
 import Data.List (intercalate)
-import Data.Maybe
 import qualified Debian.Control.String as S
 import Debian.Release
 import Debian.URI()
@@ -34,7 +32,7 @@
             , changeInfo :: S.Paragraph		-- ^ The contents of the .changes file
             , changeEntry :: ChangeLogEntry	-- ^ The value of the Changes field of the .changes file
             , changeFiles :: [ChangedFileSpec]	-- ^ The parsed value of the Files attribute
-            } deriving (Eq, Show)
+            } deriving (Eq)
 
 -- |An entry in the list of files generated by the build.
 data ChangedFileSpec =
@@ -58,7 +56,7 @@
           , logDate :: String
           }
   | WhiteSpace String
-  deriving (Eq, Show)
+  deriving (Eq)
 
 {-
 instance Show ChangesFile where
@@ -67,7 +65,7 @@
 
 changesFileName :: ChangesFile -> String
 changesFileName changes =
-    changePackage changes ++ "_" ++ show (changeVersion changes) ++ "_" ++ archName (changeArch changes) ++ ".changes"
+    changePackage changes ++ "_" ++ show (prettyDebianVersion (changeVersion changes)) ++ "_" ++ archName (changeArch changes) ++ ".changes"
 
 prettyChangesFile :: ChangesFile -> Doc
 prettyChangesFile = text . changesFileName
@@ -81,13 +79,13 @@
           changedFileName file)
 
 prettyEntry (Entry package version dists urgency details who date) =
-    text (package ++ " (" ++ show version ++ ") " ++ intercalate " " (map releaseName' dists) ++ "; urgency=" ++ urgency ++ "\n\n" ++
+    text (package ++ " (" ++ show (prettyDebianVersion version) ++ ") " ++ intercalate " " (map releaseName' dists) ++ "; urgency=" ++ urgency ++ "\n\n" ++
           details ++ " -- " ++ who ++ "  " ++ date ++ "\n\n")
 
 -- |Show just the top line of a changelog entry (for debugging output.)
 showHeader :: ChangeLogEntry -> Doc
 showHeader (Entry package version dists urgency _ _ _) =
-    text (package ++ " (" ++ show version ++ ") " ++ intercalate " " (map releaseName' dists) ++ "; urgency=" ++ urgency ++ "...")
+    text (package ++ " (" ++ show (prettyDebianVersion version) ++ ") " ++ intercalate " " (map releaseName' dists) ++ "; urgency=" ++ urgency ++ "...")
 
 {-
 format is a series of entries like this:
diff --git a/Debian/Control.hs b/Debian/Control.hs
--- a/Debian/Control.hs
+++ b/Debian/Control.hs
@@ -39,10 +39,17 @@
 
 packParagraph :: S.Paragraph -> B.Paragraph
 packParagraph (S.Paragraph s) = B.Paragraph (map packField s)
+
+packField :: Field' String -> Field' B.ByteString
 packField (S.Field (name, value)) = B.Field (B.pack name, B.pack value)
 packField (S.Comment s) = B.Comment (B.pack s)
 
+formatControl :: Control' B.ByteString -> [B.ByteString]
 formatControl (B.Control paragraphs) = intersperse (B.pack "\n") . map formatParagraph $ paragraphs
+
+formatParagraph :: Paragraph' B.ByteString -> B.ByteString
 formatParagraph (B.Paragraph fields) = B.concat . map formatField $ fields
+
+formatField :: Field' B.ByteString -> B.ByteString
 formatField (B.Field (name, value)) = B.concat [name, B.pack ":", value, B.pack "\n"]
 formatField (B.Comment s) = s
diff --git a/Debian/Control/ByteString.hs b/Debian/Control/ByteString.hs
--- a/Debian/Control/ByteString.hs
+++ b/Debian/Control/ByteString.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE ScopedTypeVariables #-}
+{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-orphans #-}
 module Debian.Control.ByteString
     ( Control'(..)
     , Paragraph'(..)
@@ -25,18 +26,13 @@
 
 import Data.Char(chr,ord,toLower)
 import Data.List
-import Data.Maybe
 import Data.Word
 
---import Foreign.C.String         (CString, CStringLen)
---import Foreign.C.Types          (CSize)
 import Foreign.ForeignPtr
---import Foreign.Marshal.Array
 import Foreign.Ptr
 import Foreign.Storable         (Storable(..))
 
 import System.IO.Unsafe
---import System.Environment
 
 import Text.ParserCombinators.Parsec.Error
 import Text.ParserCombinators.Parsec.Pos
@@ -85,7 +81,7 @@
 pField :: ControlParser Field
 pField =
     do k <- pKey
-       pChar ':'
+       _ <- pChar ':'
        v <- pValue
 --       pChar '\n'
        (pChar '\n' >> return ()) <|> pEOF
diff --git a/Debian/Control/PrettyPrint.hs b/Debian/Control/PrettyPrint.hs
--- a/Debian/Control/PrettyPrint.hs
+++ b/Debian/Control/PrettyPrint.hs
@@ -1,4 +1,4 @@
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
 module Debian.Control.PrettyPrint where
 
 import qualified Data.ByteString.Char8 as C
diff --git a/Debian/Control/String.hs b/Debian/Control/String.hs
--- a/Debian/Control/String.hs
+++ b/Debian/Control/String.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE FlexibleInstances, ScopedTypeVariables, TypeSynonymInstances #-}
+{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-name-shadowing #-}
 module Debian.Control.String
     ( -- * Types
       Control'(..)
diff --git a/Debian/Deb.hs b/Debian/Deb.hs
--- a/Debian/Deb.hs
+++ b/Debian/Deb.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
 module Debian.Deb where
 
 import Control.Monad
diff --git a/Debian/Extra/Files.hs b/Debian/Extra/Files.hs
--- a/Debian/Extra/Files.hs
+++ b/Debian/Extra/Files.hs
@@ -12,12 +12,12 @@
                   -> String		-- ^ The text that the file should contain
                   -> m a		-- ^ The function's return value
 withTemporaryFile f text =
-    do path <- liftIO $ writeTemporaryFile text
+    do path <- liftIO writeTemporaryFile
        result <- f path
        liftIO $ removeFile path
        return result
     where
-      writeTemporaryFile text =
+      writeTemporaryFile =
           do dir <- getTemporaryDirectory
              (path, h) <- openBinaryTempFile dir "wtf.tmp"
              hPutStr h text
diff --git a/Debian/Relation.hs b/Debian/Relation.hs
--- a/Debian/Relation.hs
+++ b/Debian/Relation.hs
@@ -6,6 +6,7 @@
     , OrRelation
     , Relations
     , Relation(..)
+    , prettyRelation
     , ArchitectureReq(..)
     , VersionReq(..)
     -- * Helper Functions
@@ -15,4 +16,5 @@
     , ParseRelations(..)
     ) where 
 
+import Debian.Relation.Common (prettyRelation)
 import Debian.Relation.String
diff --git a/Debian/Relation/Common.hs b/Debian/Relation/Common.hs
--- a/Debian/Relation/Common.hs
+++ b/Debian/Relation/Common.hs
@@ -5,6 +5,7 @@
 import Data.List
 import Text.ParserCombinators.Parsec
 import Data.Function
+import Text.PrettyPrint (Doc, text)
 
 -- Local Modules
 
@@ -29,9 +30,9 @@
     parseRelations :: a -> Either ParseError Relations
 
 
-instance Show Relation where
-    show (Rel name ver arch) =
-        name ++ maybe "" show ver ++ maybe "" show arch
+prettyRelation :: Relation -> Doc
+prettyRelation (Rel name ver arch) =
+    text (name ++ maybe "" (show . prettyVersionReq) ver ++ maybe "" (show . prettyArchitectureReq) arch)
 
 instance Ord Relation where
     compare (Rel pkgName1 mVerReq1 _mArch1) (Rel pkgName2 mVerReq2 _mArch2) =
@@ -45,9 +46,9 @@
     | ArchExcept [String]
       deriving Eq
 
-instance Show ArchitectureReq where
-    show (ArchOnly arch) = " [" ++ intercalate " " arch ++ "]"
-    show (ArchExcept arch) = " [!" ++ intercalate " !" arch ++ "]"
+prettyArchitectureReq :: ArchitectureReq -> Doc
+prettyArchitectureReq (ArchOnly arch) = text $ " [" ++ intercalate " " arch ++ "]"
+prettyArchitectureReq (ArchExcept arch) = text $ " [!" ++ intercalate " !" arch ++ "]"
 
 data VersionReq
     = SLT DebianVersion
@@ -57,12 +58,12 @@
     | SGR DebianVersion
       deriving Eq
 
-instance Show VersionReq where
-    show (SLT v) = " (<< " ++ show v ++ ")"
-    show (LTE v) = " (<= " ++ show v ++ ")"
-    show (EEQ v) = " (= " ++ show v ++ ")"
-    show (GRE v) = " (>= " ++ show v ++ ")"
-    show (SGR v) = " (>> " ++ show v ++ ")"
+prettyVersionReq :: VersionReq -> Doc
+prettyVersionReq (SLT v) = text $ " (<< " ++ show (prettyDebianVersion v) ++ ")"
+prettyVersionReq (LTE v) = text $ " (<= " ++ show (prettyDebianVersion v) ++ ")"
+prettyVersionReq (EEQ v) = text $ " (= " ++ show (prettyDebianVersion v) ++ ")"
+prettyVersionReq (GRE v) = text $ " (>= " ++ show (prettyDebianVersion v) ++ ")"
+prettyVersionReq (SGR v) = text $ " (>> " ++ show (prettyDebianVersion v) ++ ")"
 
 -- |The sort order is based on version number first, then on the kind of
 -- relation, sorting in the order <<, <= , ==, >= , >>
diff --git a/Debian/Relation/String.hs b/Debian/Relation/String.hs
--- a/Debian/Relation/String.hs
+++ b/Debian/Relation/String.hs
@@ -1,4 +1,4 @@
-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
 -- |A module for working with debian relationships <http://www.debian.org/doc/debian-policy/ch-relationships.html>
 module Debian.Relation.String
     ( -- * Types
diff --git a/Debian/Release.hs b/Debian/Release.hs
--- a/Debian/Release.hs
+++ b/Debian/Release.hs
@@ -55,11 +55,13 @@
 
 -- |Parse the value that appears in the @Section@ field of a .changes file.
 -- (Does this need to be unesacped?)
-parseSection section =
-    case span (/= '/') section of
+parseSection :: String -> SubSection
+parseSection s =
+    case span (/= '/') s of
       (x, "") -> SubSection (Section "main") x
       ("main", y) -> SubSection (Section "main") y
       (x, y) -> SubSection (Section x) (tail y)
 
+parseSection' :: String -> Section
 parseSection' name =
     Section (unEscapeString name)
diff --git a/Debian/Report.hs b/Debian/Report.hs
--- a/Debian/Report.hs
+++ b/Debian/Report.hs
@@ -82,6 +82,6 @@
       mkTrumpedPackage (package, (oldVersion, newVersion)) =
           mkElem "trumpedPackage"
                      [ mkElem "package" [ cdata (B.unpack package) ]
-                     , mkElem "oldVersion" [ cdata (show oldVersion) ]
-                     , mkElem "newVersion" [ cdata (show newVersion) ]
+                     , mkElem "oldVersion" [ cdata (show (prettyDebianVersion oldVersion)) ]
+                     , mkElem "newVersion" [ cdata (show (prettyDebianVersion newVersion)) ]
                      ]
diff --git a/Debian/Sources.hs b/Debian/Sources.hs
--- a/Debian/Sources.hs
+++ b/Debian/Sources.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
 module Debian.Sources where
 
 import Data.List (intercalate)
diff --git a/Debian/URI.hs b/Debian/URI.hs
--- a/Debian/URI.hs
+++ b/Debian/URI.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS -fno-warn-orphans #-}
 module Debian.URI
     ( module Network.URI
     , URIString
@@ -7,18 +8,14 @@
     , dirFromURI
     ) where
 
-import Control.Exception (SomeException, {-ErrorCall(ErrorCall),-} try)
---import Control.Monad.Trans (MonadIO)
+import Control.Exception (SomeException, try)
 import qualified Data.ByteString.Lazy.Char8 as L
 import qualified Data.ByteString as B
 import Data.Maybe (catMaybes)
 import Network.URI
 import System.Directory (getDirectoryContents)
---import System.Exit
---import System.Unix.Process (lazyCommand, collectOutput)
 import System.Unix.Process (collectStdout)
-import System.Unix.Progress (lazyCommandSF, quieter)
---import System.Unix.ProcessExtra (cmdOutput, cmdOutputStrict)
+import System.Unix.Progress (lazyCommandF)
 import Text.Regex (mkRegex, matchRegex)
 
 uriToString' :: URI -> String
@@ -35,9 +32,9 @@
     case (uriScheme uri, uriAuthority uri) of
       ("file:", Nothing) -> try (L.readFile (uriPath uri))
       -- ("ssh:", Just auth) -> cmdOutput ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri))
-      ("ssh:", Just auth) -> try (lazyCommandSF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri)) L.empty >>=
+      ("ssh:", Just auth) -> try (lazyCommandF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri)) L.empty >>=
                                   return . fst . collectStdout)
-      _ -> try (lazyCommandSF ("curl -s -g '" ++ uriToString' uri ++ "'") L.empty >>=
+      _ -> try (lazyCommandF ("curl -s -g '" ++ uriToString' uri ++ "'") L.empty >>=
                 return . fst . collectStdout)
 
 fileFromURIStrict :: URI -> IO (Either SomeException B.ByteString)
@@ -45,9 +42,9 @@
     case (uriScheme uri, uriAuthority uri) of
       ("file:", Nothing) -> try (B.readFile (uriPath uri))
       -- ("ssh:", Just auth) -> cmdOutputStrict ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri))
-      ("ssh:", Just auth) -> try (lazyCommandSF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri)) L.empty >>=
+      ("ssh:", Just auth) -> try (lazyCommandF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " cat " ++ show (uriPath uri)) L.empty >>=
                                   return . B.concat . L.toChunks . fst . collectStdout)
-      _ -> try (lazyCommandSF ("curl -s -g '" ++ uriToString' uri ++ "'") L.empty >>=
+      _ -> try (lazyCommandF ("curl -s -g '" ++ uriToString' uri ++ "'") L.empty >>=
                 return . B.concat . L.toChunks . fst . collectStdout)
       -- _ -> cmdOutputStrict ("curl -s -g '" ++ uriToString' uri ++ "'")
 
@@ -69,7 +66,7 @@
     case (uriScheme uri, uriAuthority uri) of
       ("file:", Nothing) -> try (getDirectoryContents (uriPath uri))
       -- ("ssh:", Just auth) -> cmdOutput ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " ls -1 " ++ uriPath uri) >>=
-      ("ssh:", Just auth) -> try (lazyCommandSF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " ls -1 " ++ uriPath uri) L.empty >>=
+      ("ssh:", Just auth) -> try (lazyCommandF ("ssh " ++ uriUserInfo auth ++ uriRegName auth ++ uriPort auth ++ " ls -1 " ++ uriPath uri) L.empty >>=
                                   return . lines . L.unpack . fst . collectStdout)
       -- _ -> cmdOutput ("curl -s -g '" ++ uriToString' uri ++ "/'") >>= return . either Left (Right . webServerDirectoryContents)
-      _ -> try (lazyCommandSF ("curl -s -g '" ++ uriToString' uri ++ "/'") L.empty >>= return . webServerDirectoryContents . fst . collectStdout)
+      _ -> try (lazyCommandF ("curl -s -g '" ++ uriToString' uri ++ "/'") L.empty >>= return . webServerDirectoryContents . fst . collectStdout)
diff --git a/Debian/Version.hs b/Debian/Version.hs
--- a/Debian/Version.hs
+++ b/Debian/Version.hs
@@ -2,6 +2,7 @@
 -- numbers. <http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version>
 module Debian.Version 
     (DebianVersion -- |Exported abstract because the internal representation is likely to change 
+    , prettyDebianVersion
     , parseDebianVersion
     , epoch
     , version
diff --git a/Debian/Version/ByteString.hs b/Debian/Version/ByteString.hs
--- a/Debian/Version/ByteString.hs
+++ b/Debian/Version/ByteString.hs
@@ -1,3 +1,4 @@
+{-# OPTIONS -fno-warn-orphans #-}
 module Debian.Version.ByteString
     ( ParseDebianVersion(..)
     ) where
diff --git a/Debian/Version/Common.hs b/Debian/Version/Common.hs
--- a/Debian/Version/Common.hs
+++ b/Debian/Version/Common.hs
@@ -1,7 +1,9 @@
 -- |A module for parsing, comparing, and (eventually) modifying debian version
 -- numbers. <http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version>
+{-# OPTIONS -fno-warn-orphans -fno-warn-unused-do-bind #-}
 module Debian.Version.Common
     (DebianVersion -- |Exported abstract because the internal representation is likely to change 
+    , prettyDebianVersion
     , ParseDebianVersion(..)
     , evr		-- DebianVersion -> (Maybe Int, String, Maybe String)
     , epoch
@@ -15,9 +17,10 @@
 import Text.ParserCombinators.Parsec
 import Text.Regex
 import Debian.Version.Internal
+import Text.PrettyPrint (Doc, text)
 
-instance Show DebianVersion where
-    show (DebianVersion s _) = s
+prettyDebianVersion :: DebianVersion -> Doc
+prettyDebianVersion (DebianVersion s _) = text s
 
 instance Eq DebianVersion where
     (DebianVersion _ v1) == (DebianVersion _ v2) = v1 == v2
@@ -156,15 +159,16 @@
       -- I really don't think this can happen.
       _ -> error ("Invalid Debian Version String: " ++ s)
 
+epoch :: DebianVersion -> Maybe Int
 epoch v = case evr v of (x, _, _) -> x
+version :: DebianVersion -> String
 version v = case evr v of (_, x, _) -> x
+revision :: DebianVersion -> Maybe String
 revision v = case evr v of (_, _, x) -> x
 
 -- Build a Debian version number from epoch, version, revision
 buildDebianVersion :: Maybe Int -> String -> Maybe String -> DebianVersion
-buildDebianVersion epoch version revision =
+buildDebianVersion e v r =
     either (error . show) (DebianVersion str) $ parse parseDV str str
     where
-      str = (maybe "" (\ n -> show n ++ ":") epoch ++
-                   version ++
-                   maybe "" (\ s -> "-" ++ s) revision)
+      str = (maybe "" (\ n -> show n ++ ":") e ++ v ++ maybe "" (\ s -> "-" ++ s) r)
diff --git a/Debian/Version/String.hs b/Debian/Version/String.hs
--- a/Debian/Version/String.hs
+++ b/Debian/Version/String.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
+{-# OPTIONS -fno-warn-orphans #-}
 module Debian.Version.String
     ( ParseDebianVersion(..)
     ) where
diff --git a/Distribution/Package/Debian.hs b/Distribution/Package/Debian.hs
deleted file mode 100644
--- a/Distribution/Package/Debian.hs
+++ /dev/null
@@ -1,914 +0,0 @@
-{-# LANGUAGE CPP, ScopedTypeVariables, TypeSynonymInstances #-}
-
--- |
--- Module      :  Distribution.Package.Debian
--- Copyright   :  David Fox 2008
---
--- Maintainer  :  David Fox <dsf@seereason.com>
--- Stability   :  alpha
--- Portability :  portable
---
--- Explanation: Support for generating Debianization from Cabal data.
-
--- This software may be used and distributed according to the terms of
--- the GNU General Public License, incorporated herein by reference.
-
-module Distribution.Package.Debian
-    ( debian
-    ) where
-
-import Codec.Binary.UTF8.String (decodeString)
-import Control.Arrow (second)
-import Control.Exception (SomeException, try, bracket)
-import Control.Monad (when,mplus)
-import qualified Data.ByteString.Lazy.Char8 as L
-import Data.Char (toLower, isSpace)
-import Data.List
-import qualified Data.Map as Map
-import Data.Maybe
-import Data.Set (Set, member)
-import qualified Data.Set (fromList)
-import Data.Version (showVersion)
-import Debian.Control
-import qualified Debian.Relation as D
-import Debian.Release (parseReleaseName)
-import Debian.Changes (ChangeLogEntry(..), prettyEntry)
-import Debian.Time (getCurrentLocalRFC822Time)
-import Debian.Version
-import Debian.Version.String
-import Debian.Version.Internal (DebianVersion (DebianVersion))
-import System.Cmd (system)
-import System.Directory
-import System.FilePath ((</>))
-import
-  System.IO
- (IOMode (ReadMode), hGetContents, hPutStrLn, hSetBinaryMode, openFile, stderr)
-import System.IO.Unsafe (unsafePerformIO)
-import System.Posix.Files (setFileCreationMask)
-import System.Process (readProcessWithExitCode)
-import System.Unix.Process
-import System.Environment
---import Text.ParserCombinators.ReadP
-
-import Distribution.Text (display)
-import Distribution.Simple.Compiler (CompilerFlavor(..), compilerFlavor, Compiler(..))
---import Distribution.Simple.Configure (localBuildInfoFile)
-import Distribution.System (Platform(..), buildOS, buildArch)
-import Distribution.License (License(..))
-import Distribution.Package (Package(..), PackageIdentifier(..), PackageName(..), Dependency(..))
-import Distribution.Simple.Program (defaultProgramConfiguration)
-import Distribution.Simple.Configure (configCompiler, maybeGetPersistBuildConfig)
-import Distribution.Simple.InstallDirs (InstallDirs(..), InstallDirTemplates, toPathTemplate)
---import Distribution.Simple.Register (writeInstalledConfig)
---import Distribution.Simple.Setup (defaultRegisterFlags)
-import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..))
-import Distribution.Simple.PackageIndex (PackageIndex,fromList)
-import Distribution.Simple.Utils (die, setupMessage)
-import Distribution.PackageDescription (GenericPackageDescription(..),
-                                        PackageDescription(..),
-                                        allBuildInfo, buildTools, pkgconfigDepends,
-                                        exeName, extraLibs)
-import Distribution.PackageDescription.Configuration (finalizePackageDescription)
-import Distribution.ParseUtils (parseQuoted)
-import Distribution.Verbosity (Verbosity)
-import Distribution.Version (Version(..),VersionRange(..))
-import Distribution.Simple.Setup (defaultDistPref)
-import Distribution.Package.Debian.Setup (Flags(..), DebAction(..), DebType(..))
-import Distribution.Package.Debian.Bundled
-import qualified Distribution.Compat.ReadP as ReadP
-import Distribution.Text ( Text(parse) )
-import Text.PrettyPrint.HughesPJ
-
-parsePackageId' :: ReadP.ReadP PackageIdentifier PackageIdentifier
-parsePackageId' = parseQuoted parse ReadP.<++ parse
-
-type DebMap = Map.Map String (Maybe DebianVersion)
-
-buildDebVersionMap :: IO DebMap
-buildDebVersionMap =
-    readFile "/var/lib/dpkg/status" >>=
-    return . either (const []) unControl . parseControl "/var/lib/dpkg/status" >>=
-    mapM (\ p -> case (lookupP "Package" p, lookupP "Version" p) of
-                   (Just (Field (_, name)), Just (Field (_, version))) ->
-                       return (Just (stripWS name, Just (parseDebianVersion (stripWS version))))
-                   _ -> return Nothing) >>=
-    return . Map.fromList . catMaybes
-
-m ! k =
-    maybe (error ("No version number for " ++ show k ++ " in " ++ show m)) id (Map.findWithDefault Nothing k m)
-
-{-
-trim s =
-    case matchRegex re s of 
-      Just [x, _, _] -> x
-      _ -> error $ "Internal error: trim " ++ show s
-    where
-      re = mkRegex ("^[ \t\n]*(" ++ trimmed ++ ")[ \t\n]*")
-      trimmed = "([^ \t\n](.*[^ \t\n])?)?"
--}
-
-trim = dropWhile isSpace
-
---installedPackages :: Package pkg => IO [PackageIndex]
-{-
-installedPackages =
-    do (out, err, code) <- lazyCommand cmd L.empty >>=  return . collectOutputUnpacked
-       case code of
-         [ExitSuccess] -> return . fromList $ map (last . map fst . ReadP.readP_to_S parsePackageId') (words out)
-         result -> error $ "Failure: " ++ cmd ++ " -> " ++ show result ++ " (" ++ err ++ ")"
-    where
-      cmd = "ghc-pkg list --simple-output"
--}
-
-simplePackageDescription :: GenericPackageDescription -> Flags
-                         -> IO (Compiler, PackageDescription)
-simplePackageDescription genPkgDesc flags = do
-    (compiler, _) <- configCompiler (Just (rpmCompiler flags)) Nothing Nothing
-                     defaultProgramConfiguration
-                     (rpmVerbosity flags)
-    --installed <- installedPackages
-    case finalizePackageDescription (rpmConfigurationsFlags flags)
-          (const True) (Platform buildArch buildOS) (compilerId compiler)
-          {- (Nothing :: Maybe PackageIndex) -}
-          [] genPkgDesc of
-      Left e -> die $ "finalize failed: " ++ show e
-      Right (pd, _) -> return (compiler, pd)
-    
-debian :: GenericPackageDescription	-- ^ info from the .cabal file
-       -> Flags				-- ^ command line flags
-       -> IO ()
-
-debian genPkgDesc flags =
-    case rpmCompiler flags of
-      GHC ->
-          do (compiler, pkgDesc) <- simplePackageDescription genPkgDesc flags
-             let verbose = rpmVerbosity flags
-             createDirectoryIfMissing True (debOutputDir flags)
-             --lbi <- localBuildInfo pkgDesc flags
-             debVersions <- buildDebVersionMap
-             cabalPackages <- libPaths compiler debVersions >>= return . Map.fromList . map (\ p -> (cabalName p, p))
-             bracket (setFileCreationMask 0o022) setFileCreationMask $ \ _ -> do
-               autoreconf verbose pkgDesc
-               case debAction flags of
-                 SubstVar name ->
-                     do control <- readFile "debian/control" >>= either (error . show) return . parseControl "debian/control"
-                        substvars pkgDesc compiler debVersions control cabalPackages name
-                 Debianize ->
-                     debianize True pkgDesc flags compiler (debOutputDir flags)
-                 UpdateDebianization ->
-                     updateDebianization True pkgDesc flags compiler (debOutputDir flags)
-      c -> die ("the " ++ show c ++ " compiler is not yet supported")
-
-autoreconf :: Verbosity -> PackageDescription -> IO ()
-
-autoreconf verbose pkgDesc = do
-    ac <- doesFileExist "configure.ac"
-    when ac $ do
-        c <- doesFileExist "configure"
-        when (not c) $ do
-            setupMessage verbose "Running autoreconf" (packageId pkgDesc)
-            ret <- system "autoreconf"
-            case ret of
-              ExitSuccess -> return ()
-              ExitFailure n -> die ("autoreconf failed with status " ++ show n)
-
-{-
-localBuildInfo :: PackageDescription -> Flags -> IO LocalBuildInfo
-localBuildInfo pkgDesc flags =
-  maybeGetPersistBuildConfig defaultDistPref >>=
-  maybe setup return >>=
-  writeInstalledConfig'
-    where
-      -- Warning - passing the --ghc flag explicitly here probably
-      -- disables support for other compilers.
-      setup = system ("runhaskell Setup configure --ghc --prefix " ++ rpmPrefix flags) >> 
-              maybeGetPersistBuildConfig defaultDistPref >>= 
-              return . maybe (error ("Failed to create " ++ defaultDistPref)) id
-      writeInstalledConfig' lbi =
-          if isNothing (library pkgDesc)
-          then error "cabal-debian - Unsupported: package without a library section"
-          else writeInstalledConfig defaultDistPref pkgDesc lbi False Nothing >> return lbi
--}
-
-data PackageInfo = PackageInfo { libDir :: FilePath
-                               , cabalName :: String
-                               , cabalVersion :: String
-                               , devDeb :: Maybe (String, DebianVersion)
-                               , profDeb :: Maybe (String, DebianVersion)
-                               , docDeb :: Maybe (String, DebianVersion) }  
-
--- |Each cabal package corresponds to a directory <name>-<version>,
--- either in /usr/lib or in /usr/lib/haskell-packages/ghc/lib.
--- In that directory is a compiler subdirectory such as ghc-6.8.2.
--- In the ghc subdirectory is one or two library files of the form
--- libHS<name>-<version>.a and libHS<name>-<version>_p.a.  We can
--- determine the debian package names by running dpkg -S on these
--- names, or examining the /var/lib/dpkg/info/\*.list files.  From
--- these we can determine the source package name, and from that
--- the documentation package name.
-substvars :: PackageDescription		-- ^info from the .cabal file
-          -> Compiler   		-- ^compiler details
-          -> DebMap
-          -> Control			-- ^The debian/control file
-          -> Map.Map String PackageInfo	-- ^The list of installed cabal packages
-          -> DebType			-- ^The type of deb we want to write substvars for
-          -> IO ()
-substvars pkgDesc _compiler _debVersions control cabalPackages debType =
-    case (missingBuildDeps, path) of
-      -- There should already be a .substvars file produced by dh_haskell_prep,
-      -- keep the relations listed there.  They will contain something like this:
-      -- libghc-cabal-debian-prof.substvars:
-      --    haskell:Depends=ghc-prof (<< 6.8.2-999), ghc-prof (>= 6.8.2), libghc-cabal-debian-dev (= 0.4)
-      -- libghc-cabal-debian-dev.substvars:
-      --    haskell:Depends=ghc (<< 6.8.2-999), ghc (>= 6.8.2)
-      -- haskell-cabal-debian-doc.substvars:
-      --    haskell:Depends=ghc-doc, haddock (>= 2.1.0), haddock (<< 2.1.0-999)
-      ([], Just path') ->
-          do old <- try (readFile path') >>= return . either (\ (_ :: SomeException) -> "") id
-             let new = addDeps old
-             hPutStrLn stderr (if new /= old
-                               then ("cabal-debian - Updated " ++ show path' ++ ":\n " ++ old ++ "\n   ->\n " ++ new)
-                               else ("cabal-debian - No updates found for " ++ show path'))
-             maybe (return ()) (\ _x -> replaceFile path' new) name
-      ([], Nothing) -> return ()
-      (missing, _) -> 
-          die ("These debian packages need to be added to the build dependency list so the required cabal packages are available:\n  " ++ intercalate "\n  " (map fst missing) ++
-               "\nIf this is an obsolete package you may need to withdraw the old versions from the\n" ++
-               "upstream repository, and uninstall and purge it from your local system.")
-    where
-      addDeps old =
-          case partition (isPrefixOf "haskell:Depends=") (lines old) of
-            ([], other) -> unlines (("haskell:Depends=" ++ showDeps deps) : other)
-            (hdeps, more) ->
-                case deps of
-                  [] -> unlines (hdeps ++ more)
-                  _ -> unlines (map (++ (", " ++ showDeps deps)) hdeps ++ more)
-      path = maybe Nothing (\ x -> Just ("debian/" ++ x ++ ".substvars")) name
-      name = case debType of Dev -> devDebName; Prof -> profDebName; Doc -> docDebName
-      deps = case debType of Dev -> devDeps; Prof -> profDeps; Doc -> docDeps
-      -- We must have build dependencies on the profiling and documentation packages
-      -- of all the cabal packages.
-      missingBuildDeps =
-          let requiredDebs =
-                  concat (map (\ (Dependency (PackageName name) _) ->
-                               case Map.lookup name cabalPackages :: Maybe PackageInfo of
-                                 Just info ->
-                                     let prof = maybe (devDeb info) Just (profDeb info) in
-                                     let doc = docDeb info in
-                                     catMaybes [prof, doc]
-                                 Nothing -> []) cabalDeps) in
-          filter (not . (`elem` buildDepNames) . fst) requiredDebs
-      -- Make a list of the debian devel packages corresponding to cabal packages
-      -- which are build dependencies
-      devDeps :: D.Relations
-      devDeps =
-          catMaybes (map (\ (Dependency (PackageName name) _) ->
-                          case Map.lookup name cabalPackages :: Maybe PackageInfo of
-                            Just package -> maybe Nothing (\ (s, v) -> Just [D.Rel s (Just (D.GRE v)) Nothing]) (devDeb package)
-                            Nothing -> Nothing) cabalDeps)
-      profDeps :: D.Relations
-      profDeps =
-          maybe [] (\ name -> [[D.Rel name Nothing Nothing]]) devDebName ++
-          catMaybes (map (\ (Dependency (PackageName name) _) ->
-                          case Map.lookup name cabalPackages :: Maybe PackageInfo of
-                            Just package -> maybe Nothing (\ (s, v) -> Just [D.Rel s (Just (D.GRE v)) Nothing]) (profDeb package)
-                            Nothing -> Nothing) cabalDeps)
-      docDeps :: D.Relations
-      docDeps =
-          catMaybes (map (\ (Dependency (PackageName name) _) ->
-                              case Map.lookup name cabalPackages :: Maybe PackageInfo of
-                                Just package -> maybe Nothing (\ (s, v) -> Just [D.Rel s (Just (D.GRE v)) Nothing]) (docDeb package)
-                                Nothing -> Nothing) cabalDeps)
-      cabalDeps :: [Dependency]
-      cabalDeps = map unboxDependency $ allBuildDepends pkgDesc
-      buildDepNames :: [String]
-      buildDepNames = concat (map (map (\ (D.Rel s _ _) -> s)) buildDeps)
-      buildDeps :: D.Relations
-      buildDeps = (either (error . show) id . D.parseRelations $ bd) ++ (either (error . show) id . D.parseRelations $ bdi)
-      --sourceName = maybe (error "Invalid control file") (\ (Field (_, s)) -> stripWS s) (lookupP "Source" (head (unControl control)))
-      devDebName = listToMaybe (filter (isSuffixOf "-dev") debNames)
-      profDebName = listToMaybe (filter (isSuffixOf "-prof") debNames)
-      docDebName = listToMaybe (filter (isSuffixOf "-doc") debNames)
-      debNames = map (\ (Field (_, s)) -> stripWS s) (catMaybes (map (lookupP "Package") (tail (unControl control))))
-      bd = maybe "" (\ (Field (_a, b)) -> stripWS b) . lookupP "Build-Depends" . head . unControl $ control
-      bdi = maybe "" (\ (Field (_a, b)) -> stripWS b) . lookupP "Build-Depends-Indep" . head . unControl $ control
-
--- |Write a file which we might still be reading from in
--- order to compute the text argument.
-replaceFile :: FilePath -> String -> IO ()
-replaceFile path text =
-    try (removeFile back >>		-- This may not exist
-         renameFile path back >>	-- This may not exist
-         writeFile path text) >>=	-- This must succeed
-    either (\ (e :: SomeException) -> error ("writeFile " ++ show path ++ ": " ++ show e)) return
-    where
-      back = path ++ "~"
-
-libPaths :: Compiler -> DebMap -> IO [PackageInfo]
-libPaths compiler debVersions
-    | compilerFlavor compiler == GHC =
-        do a <- getDirPaths "/usr/lib"
-           b <- getDirPaths "/usr/lib/haskell-packages/ghc/lib"
-           -- Build a map from names of installed debs to version numbers
-           mapM (packageInfo compiler debVersions) (a ++ b) >>= return . catMaybes
-    | True = error $ "Can't handle compiler flavor: " ++ show (compilerFlavor compiler)
-    where
-      getDirPaths path = try (getDirectoryContents path) >>= return . map (\ x -> (path, x)) . either (\ (_ :: SomeException) -> []) id
-
-packageInfo :: Compiler ->  DebMap -> (FilePath, String) -> IO (Maybe PackageInfo)
-packageInfo compiler debVersions (d, f) =
-    case parseNameVersion f of
-      Nothing -> return Nothing
-      Just (p, v) -> doesDirectoryExist (d </> f </> cdir) >>= cond (return Nothing) (info (d, p, v))
-    where
-      cdir = display (compilerId compiler)
-      info (d, p, v) = 
-          do dev <- debOfFile ("^" ++ d </> p ++ "-" ++ v </> cdir </> "libHS" ++ p ++ "-" ++ v ++ ".a$")
-             prof <- debOfFile ("^" ++ d </> p ++ "-" ++ v </> cdir </> "libHS" ++ p ++ "-" ++ v ++ "_p.a$")
-             doc <- debOfFile ("/" ++ p ++ ".haddock$")
-             return (Just (PackageInfo { libDir = d
-                                       , cabalName = p
-                                       , cabalVersion = v
-                                       , devDeb = maybe Nothing (\ x -> Just (x, debVersions ! x)) dev
-                                       , profDeb = maybe Nothing (\ x -> Just (x, debVersions ! x)) prof
-                                       , docDeb = maybe Nothing (\ x -> Just (x, debVersions ! x)) doc }))
-      parseNameVersion s =
-          case (break (== '-') (reverse s)) of
-            (_a, "") -> Nothing
-            (a, b) -> Just (reverse (tail b), reverse a) 
-
--- |Given a path, return the name of the package that owns it.
-debOfFile :: FilePath -> IO (Maybe String)
-debOfFile s =
-    do (out, _err, code) <- lazyCommand cmd L.empty >>= return . collectOutputUnpacked
-       case code of
-         ExitSuccess -> return (takePackageName out)
-         _ -> return Nothing
-    where
-      cmd = "cd /var/lib/dpkg/info && grep '" ++ s ++ "' *.list"
-      -- We already know here that suff actually is a suffix of s
-      --dropSuffix suff s = take (length s - length suff) s
-
-takePackageName :: String -> Maybe String
-takePackageName s =
-    f "" s
-    where
-      f name ('.':'l':'i':'s':'t':':':_) = Just (reverse name)
-      f name (x : xs) = f (x : name) xs
-      f _ [] = Nothing
-
--- Determine the documentation package name.  Look for <cabalname>.haddock
-{-
-devToDoc :: Compiler -> String -> IO (Maybe String)
-devToDoc compiler name
-    | compilerFlavor compiler == GHC =
-        case maybe Nothing (dropSuffix "-dev") (dropPrefix "libghc-" name) of
-          Just base -> 
-              do let name1 = "libghc-" ++ base ++ "-doc"
-                 let name2 = "libghc-" ++ base ++ "-doc"
-                 exists1 <- doesFileExist ("/var/lib/dpkg/info/" ++ name1 ++ ".list")
-                 case exists1 of
-                   True -> return (Just name1)
-                   False ->
-                       do exists2 <- doesFileExist ("/var/lib/dpkg/info/" ++ name2 ++ ".list")
-                          case exists2 of
-                            True -> return (Just name2)
-                            False -> return Nothing
-    where
-      dropSuffix :: String -> String -> Maybe String
-      dropSuffix suff s = case isSuffixOf suff s of
-                            True -> Just (take (length s - length suff) s)
-                            False -> Nothing
-      dropPrefix :: String -> String -> Maybe String
-      dropPrefix pref s = case isPrefixOf pref s of
-                            True -> Just (drop (length pref) s)
-                            False -> Nothing
--}
-
-cond ifF _ifT False = ifF
-cond _ifF ifT True = ifT
-
-debianize force pkgDesc flags compiler tgtPfx =
-    mapM_ removeIfExists ["debian/control", "debian/changelog"] >>
-    updateDebianization force pkgDesc flags compiler tgtPfx
-
-removeFileIfExists x = doesFileExist x >>= (`when` (removeFile x))
-removeDirectoryIfExists x = doesDirectoryExist x >>= (`when` (removeDirectory x))
-removeIfExists x = removeFileIfExists x >> removeDirectoryIfExists x
-
-updateDebianization :: Bool                -- ^whether to forcibly create file
-                    -> PackageDescription  -- ^info from the .cabal file
-                    -> Flags		 -- ^command line yflags
-                    -> Compiler            -- ^compiler details
-                    -> FilePath            -- ^directory in which to create files
-                    -> IO ()
-updateDebianization _force pkgDesc flags compiler tgtPfx =
-    do createDirectoryIfMissing True "debian"
-       date <- getCurrentLocalRFC822Time
-       copyright <- try (readFile' (licenseFile pkgDesc)) >>=
-                    return . either (\ (_ :: SomeException) -> showLicense . license $ pkgDesc) id
-       debianMaintainer <- getDebianMaintainer flags >>= maybe (error "Missing value for --maintainer") return
-       controlUpdate (tgtPfx </> "control") flags compiler debianMaintainer pkgDesc
-       changelogUpdate (tgtPfx </> "changelog") debianMaintainer pkgDesc date
-       writeFile (tgtPfx </> "rules") (cdbsRules pkgDesc)
-       getPermissions "debian/rules" >>= setPermissions "debian/rules" . (\ p -> p {executable = True})
-       writeFile (tgtPfx </> "compat") "7" -- should this be hardcoded, or automatically read from /var/lib/dpkg/status?
-       writeFile (tgtPfx </> "copyright") copyright
-       -- The dev postinst and prerm files are generated by haskell-devscripts via cdbs.
-       return ()
-
-readFile' :: FilePath -> IO String
-readFile' path
-  = do
-    file <- openFile path ReadMode
-    hSetBinaryMode file True
-    hGetContents file
-
-{-
-Create a debian maintainer field from the environment variables:
-
-  DEBFULLNAME (preferred) or NAME
-  DEBEMAIL (preferred) or EMAIL
-
-More work could be done to match dch, but this is sufficient for
-now. Here is what the man page for dch has to say:
-
- If the environment variable DEBFULLNAME is set, this will be used for
- the maintainer full name; if not, then NAME will be checked.  If the
- environment variable DEBEMAIL is set, this will be used for the email
- address.  If this variable has the form "name <email>", then the
- maintainer name will also be taken from here if neither DEBFULLNAME
- nor NAME is set.  If this variable is not set, the same test is
- performed on the environment variable EMAIL.  Next, if the full name
- has still not been determined, then use getpwuid(3) to determine the
- name from the pass‐word file.  If this fails, use the previous
- changelog entry.  For the email address, if it has not been set from
- DEBEMAIL or EMAIL, then look in /etc/mailname, then attempt to build
- it from the username and FQDN, otherwise use the email address in the
- previous changelog entry.  In other words, it’s a good idea to set
- DEBEMAIL and DEBFULLNAME when using this script.
-
--}
-getDebianMaintainer :: Flags -> IO (Maybe String)
-getDebianMaintainer flags =
-    case debMaintainer flags of
-      Nothing -> envMaintainer
-      maint -> return maint
-    where
-      envMaintainer :: IO (Maybe String)
-      envMaintainer =
-          do env <- map (second decodeString) `fmap` getEnvironment
-             return $ do fullname <- lookup "DEBFULLNAME" env `mplus` lookup "NAME" env
-                         email    <- lookup "DEBEMAIL" env `mplus` lookup "EMAIL" env
-                         return (fullname ++ " <" ++ email ++ ">")
-
-cdbsRules :: PackageDescription -> String
-cdbsRules pkgDesc =
-    unlines (intercalate [""] ([header] ++ [comments] {- ++ devrules ++ profrules -} ))
-    where
-      header =
-          ["#!/usr/bin/make -f",
-           "include /usr/share/cdbs/1/rules/debhelper.mk",
-           "include /usr/share/cdbs/1/class/hlibrary.mk"]
-      comments =
-          ["# How to install an extra file into the documentation package",
-           "#binary-fixup/libghc-" ++ libName ++ "-doc::",
-           "#\techo \"Some informative text\" > debian/libghc-" ++ libName ++ "-doc/usr/share/doc/libghc-" ++ libName ++ "-doc/AnExtraDocFile"]
-{-
-      devrules =
-          case (library pkgDesc, executables pkgDesc) of
-            (_, []) -> []
-            (_, execs) ->
-                [["binary-fixup/" ++ (debianDevelPackageName libName) ++ "::"] ++
-                 concat (map (\ exec -> ["\tmkdir -p debian/" ++ exeName exec ++ "/usr/bin",
-		                         "\tmv debian/" ++ (debianDevelPackageName libName) ++
-                                         "/usr/lib/haskell-packages/ghc/bin/" ++ exeName exec ++
-                                         " debian/" ++ exeName exec ++ "/usr/bin"]) (executables pkgDesc))]
-      profrules =
-          case (library pkgDesc, executables pkgDesc) of
-            (_, []) -> []
-            (_, execs) ->
-                [["binary-fixup/" ++ (debianProfilingPackageName libName) ++ "::"] ++
-		 map (\ exec -> "\trm debian/" ++ (debianProfilingPackageName libName) ++
-                                "/usr/lib/haskell-packages/ghc/bin/" ++ exeName exec) (executables pkgDesc)]
--}
-      libName = unPackageName . pkgName . package $ pkgDesc
-
-list :: b -> ([a] -> b) -> [a] -> b
-list d f l = case l of [] -> d; _ -> f l
-
-controlUpdate :: FilePath -> Flags -> Compiler -> String -> PackageDescription -> IO ()
-controlUpdate path flags compiler debianMaintainer pkgDesc =
-    builtIns compiler >>= \bundled ->
-    try (readFile path) >>=
-    either (\ (_ :: SomeException) -> writeFile path (show (newCtl bundled))) (\ s -> writeFile (path ++ ".new") $! show (merge (newCtl bundled) (oldCtl s)))
-    where
-      newCtl bundled = control flags bundled compiler debianMaintainer pkgDesc
-      oldCtl s = either (const (Control [])) id (parseControl "debian/control" s)
-      merge (Control new) (Control old) =
-          case (new, old) of
-            (_newSource : _new', []) -> Control new
-            (newSource : new', oldSource : old') ->
-                Control (mergeParagraphs newSource oldSource : mergeOther new' old')
-      -- Merge a list of binary package paragraphs
-      mergeOther new old =
-          map mergePackages allNames
-          where
-            mergePackages name =
-                case (findPackage name new, findPackage name old) of
-                  (Just x, Nothing) -> x
-                  (Nothing, Just x) -> x
-                  (Just x, Just y) -> mergeParagraphs x y
-            findPackage name paras = listToMaybe (filter (hasName name) paras)
-                where hasName name para = lookupP "Package" para == Just name
-            allNames = newNames ++ (oldNames \\ newNames)
-            newNames = catMaybes $ map (lookupP "Package") new
-            oldNames = catMaybes $ map (lookupP "Package") old
-
-mergeParagraphs new@(Paragraph newFields) old@(Paragraph oldFields) =
-    Paragraph (map mergeField fieldNames)
-    where
-      fieldNames = map fieldName oldFields ++ (map fieldName newFields \\ map fieldName oldFields)
-      fieldName (Field (name, _)) = name
-      mergeField :: String -> Field
-      mergeField name =
-          case (lookupP name new, lookupP name old) of
-            (Just (Field (_, x)), Nothing) -> Field (name, x)
-            (Nothing, Just (Field (_, x))) -> Field (name, x)
-            (Just (Field (_, x)), Just (Field (_, y))) -> Field (name, mergeValues name x y)
-            _ -> error $ "Internal error"
-      mergeValues :: String -> String -> String -> String
-      mergeValues "Build-Depends" x y =
-          " " ++ (showDeps' "Build-Depends:" $ mergeDeps (parseDeps x) (parseDeps y))
-      mergeValues "Depends" x y =
-          " " ++ (showDeps' "Depends:" $ mergeDeps (parseDeps x) (parseDeps y))
-      mergeValues _ x _ = x
-      parseDeps s = either (error . show) id (D.parseRelations s)
-
-mergeDeps :: D.Relations -> D.Relations -> D.Relations
-mergeDeps x y = 
-    -- foldr :: (a -> b -> b) -> b -> [a] -> b
-    nub $ foldr insertDep x y
-    where
-      insertDep :: [D.Relation] -> D.Relations -> D.Relations
-      insertDep ys xss =
-          case depPackageNames ys of
-            [name] -> case break (\ xs -> depPackageNames xs == [name]) xss of
-                        (a, b : c) -> a ++ [b, ys] ++ c
-                        (a, []) -> a ++ [ys]
-            _ -> xss ++ [ys]
-      depPackageNames xs = nub (map depPackageName xs)
-      depPackageName (D.Rel x _ _) = x
-
-control :: Flags -> [Bundled] -> Compiler -> String -> PackageDescription -> Control
-control flags bundled compiler debianMaintainer pkgDesc =
-    Control {unControl =
-             ([sourceSpec] ++
-              develLibrarySpecs ++
-              profileLibrarySpecs ++ 
-              docLibrarySpecs ++
-              map executableSpec (executables pkgDesc))}
-    where
-      --buildDepsIndep = ""
-      sourceSpec =
-          Paragraph
-          ([Field ("Source", " " ++ debianSourcePackageName pkgDesc),
-            Field ("Priority", " " ++ "extra"),
-            Field ("Section", " " ++ "haskell"),
-            Field ("Maintainer", " " ++ debianMaintainer),
-            Field ("Build-Depends", " " ++ showDeps' "Build-Depends:" debianBuildDeps),
-            Field ("Build-Depends-Indep", " " ++ showDeps' "Build-Depends-Indep:" debianBuildDepsIndep),
-            --Field ("Build-Depends-Indep", " " ++ buildDepsIndep),
-            Field ("Standards-Version", " " ++ "3.9.1"),
-            Field ("Homepage",
-                   " " ++
-                   if homepage pkgDesc == ""
-                   then "http://hackage.haskell.org/package/" ++
-                        unPackageName (pkgName $ package pkgDesc)
-                   else homepage pkgDesc)])
-      executableSpec executable =
-          Paragraph
-          [Field ("Package", " " ++ map toLower (exeName executable)),
-           Field ("Architecture", " " ++ "any"),
-           Field ("Section", " " ++ "misc"),
-           -- No telling what the dependencies of an executable might
-           -- be.  The developer will have to fill them in
-           Field ("Depends", " " ++ showDeps [[D.Rel "${shlibs:Depends}" Nothing Nothing], 
-                                              [D.Rel "${haskell:Depends}" Nothing Nothing],
-                                              [D.Rel "${misc:Depends}" Nothing Nothing]]),
-           Field ("Description", " " ++ maybe debianDescription (const executableDescription) (library pkgDesc))]
-      develLibrarySpecs = if isJust (library pkgDesc) then [librarySpec "any" "-dev"] else []
-      profileLibrarySpecs = if debLibProf flags && isJust  (library pkgDesc) then [librarySpec "any" "-prof"] else []
-      docLibrarySpecs = if isJust (library pkgDesc) then [docSpecsParagraph] else []
-      docSpecsParagraph =
-          Paragraph
-          [Field ("Package", " " ++ debianDocumentationPackageName (unPackageName . pkgName . package $ pkgDesc)),
-           Field ("Architecture", " " ++ "all"),
-           Field ("Section", " " ++ "doc"),
-           Field ("Depends", " " ++ showDeps' "Depends:" [[D.Rel "${haskell:Depends}" Nothing Nothing],
-                                                           [D.Rel "${misc:Depends}" Nothing Nothing]]),
-           Field ("Recommends", " " ++ "${haskell:Recommends}"),
-           Field ("Suggests", " " ++ "${haskell:Suggests}"),
-           Field ("Description", " " ++ libraryDescription "-doc")]
-      librarySpec arch suffix =
-          Paragraph
-          [Field ("Package", " " ++ prefix ++ map toLower (unPackageName . pkgName . package $ pkgDesc) ++ suffix),
-           Field ("Architecture", " " ++ arch),
-           Field ("Depends", " " ++ showDeps' "Depends:" (
-                     (if suffix == "-dev"
-                      then [[D.Rel "${shlibs:Depends}" Nothing Nothing]]
-                      else []) ++
-                     [[D.Rel "${haskell:Depends}" Nothing Nothing],
-                      [D.Rel "${misc:Depends}" Nothing Nothing]])),
-           Field ("Recommends", " " ++ "${haskell:Recommends}"),
-           Field ("Suggests", " " ++ "${haskell:Suggests}"),
-           Field ("Provides", " " ++ "${haskell:Provides}"),
-           Field ("Description", " " ++ libraryDescription suffix)]
-          where prefix = case suffix of
-                           "-dev" -> "libghc-"
-                           "-prof" -> "libghc-"
-                           -- "-doc" -> docPrefix (unPackageName . pkgName . package $ pkgDesc)
-                           _ -> error $ "Unknown suffix: " ++ suffix
-      -- The haskell-cdbs package contains the hlibrary.mk file with
-      -- the rules for building haskell packages.
-      debianBuildDeps :: D.Relations
-      debianBuildDeps = 
-          nub $
-          [[D.Rel "debhelper" (Just (D.GRE (parseDebianVersion "7.0"))) Nothing],
-           [D.Rel "haskell-devscripts" (Just (D.GRE (parseDebianVersion "0.8"))) Nothing],
-           [D.Rel "cdbs" Nothing Nothing],
-           [D.Rel "ghc" Nothing Nothing]] ++
-          (if debLibProf flags then [[D.Rel "ghc-prof" Nothing Nothing]] else []) ++
-          (concat . map (debianDependencies bundled compiler buildDependencies) . allBuildDepends $ pkgDesc)
-      debianBuildDepsIndep :: D.Relations
-      debianBuildDepsIndep =
-          nub $
-          [[D.Rel "ghc-doc" Nothing Nothing]] ++
-          (concat . map (debianDependencies bundled compiler docDependencies) . allBuildDepends $ pkgDesc)
-      debianDescription = 
-          (synopsis pkgDesc) ++
-          case description pkgDesc of
-            "" -> ""
-            text ->
-                let text' = text ++ "\n" ++
-                            list "" ("\n Author: " ++) (author pkgDesc) ++
-                            list "" ("\n Upstream-Maintainer: " ++) (maintainer pkgDesc) ++
-                            list "" ("\n Url: " ++) (pkgUrl pkgDesc) in
-                "\n " ++ (trim . intercalate "\n " . map addDot . lines $ text')
-      addDot line = if all (flip elem " \t") line then "." else line
-      executableDescription = " " ++ "An executable built with the " ++ display (package pkgDesc) ++ " library."
-      libraryDescription "-prof" = debianDescription ++ "\n .\n This package contains the libraries compiled with profiling enabled."
-      libraryDescription "-dev" = debianDescription ++ "\n .\n This package contains the normal library files."
-      libraryDescription "-doc" = debianDescription ++ "\n .\n This package contains the documentation files."
-      libraryDescription x = error $ "Unexpected library package name suffix: " ++ show x
-
-showDeps xss = intercalate ", " (map (intercalate " | " . map show) xss)
-showDeps' prefix xss =
-    intercalate (",\n " ++ prefix') (map (intercalate " | " . map show) xss)
-    where prefix' = map (\ _ -> ' ') prefix
-
-data Dependency_
-  = BuildDepends Dependency
-      | BuildTools Dependency
-      | PkgConfigDepends Dependency
-      | ExtraLibs String
-    deriving (Eq, Show)
-
-unboxDependency :: Dependency_ -> Dependency
-unboxDependency (BuildDepends d) = d
-unboxDependency (BuildTools d) = d
-unboxDependency (PkgConfigDepends d) = d
-unboxDependency (ExtraLibs d) = Dependency (PackageName d) AnyVersion
-
--- |Debian packages don't have per binary package build dependencies,
--- so we just gather them all up here.
-allBuildDepends pkgDesc =
-    nub $ map BuildDepends (buildDepends pkgDesc) ++
-          concat (map (map BuildTools . buildTools) (allBuildInfo pkgDesc) ++
-                  map
-                    (map PkgConfigDepends . pkgconfigDepends)
-                    (allBuildInfo pkgDesc) ++
-                  map (map ExtraLibs . extraLibs) (allBuildInfo pkgDesc))
-
--- Turn a cabal dependency into a list of debian relations.  If a
--- library is required as a build dependency we need the profiling
--- version, which pulls in the regular version, and we need the
--- documentation so the cross references can be resolved.
-debianDependencies :: [Bundled] -> Compiler -> (Compiler -> Dependency_ -> D.Relations) -> Dependency_ -> D.Relations
-debianDependencies bundled compiler toDebRels dep
-  | isBundled bundled compiler $ unboxDependency dep = []
-debianDependencies _ compiler toDebRels dep = toDebRels compiler dep
-
-changelogUpdate :: FilePath -> String -> PackageDescription -> String -> IO ()
-changelogUpdate path debianMaintainer pkgDesc date =
-    try (readFile path) >>= either (\ (_ :: SomeException) -> writeFile path log) (const (writeFile (path ++ ".new") log))
-    where
-      log = changelog debianMaintainer pkgDesc date
-
-changelog :: String -> PackageDescription -> String -> String
-changelog debianMaintainer pkgDesc date =
-    render (prettyEntry
-            (Entry { logPackage = debianSourcePackageName pkgDesc
-                   , logVersion =
-                     updateOriginal (++ "-1~hackage1") $
-                     debianVersionNumber pkgDesc
-                   , logDists = [parseReleaseName "unstable"]
-                   , logUrgency = "low"
-                   , logComments = "  * Debianization generated by cabal-debian\n\n"
-                   , logWho = debianMaintainer
-                   , logDate = date }))
-
-updateOriginal :: (String -> String) -> DebianVersion -> DebianVersion
-updateOriginal f (DebianVersion str dv) = DebianVersion (f str) dv
-
-unPackageName :: PackageName -> String
-unPackageName (PackageName s) = s
-
-debianSourcePackageName :: PackageDescription -> String
-debianSourcePackageName pkgDesc = "haskell-" ++ map toLower (unPackageName . pkgName . package $ pkgDesc)
-
-debianProfilingPackageName :: String -> String
-debianProfilingPackageName x = "libghc-" ++ map toLower x ++ "-prof"
-
-debianDevelPackageName :: String -> String
-debianDevelPackageName x = "libghc-" ++ map toLower x ++ "-dev"
-
---debianDevelPackageName' (Dependency (PackageName name) _) = debianDevelPackageName name
-
--- debianPackageName prefix name suffix = prefix ++ (map toLower name) ++ suffix
-
-debianVersionNumber :: PackageDescription -> DebianVersion
-debianVersionNumber pkgDesc = parseDebianVersion . showVersion . pkgVersion . package $ pkgDesc
-
--- The profiling packages depend on the other profiling packages.
--- FIXME: These should have version dependencies.
-profilingDependencies :: Compiler -> Dependency_ -> D.Relations
-profilingDependencies
-   compiler
-   (BuildDepends (Dependency (PackageName name) ranges))
-  = concat
-    (map
-        (\ x -> debianRelations (debianProfilingPackageName x) ranges)
-      $ filter (not . flip member base) [name])
-profilingDependencies _ _ = []
-
--- The development packages depend on the other development packages,
--- the ones they were built with.  FIXME: These should have version
--- dependencies.
-develDependencies :: Compiler -> Dependency_ -> D.Relations
-develDependencies
-    compiler
-   (BuildDepends (Dependency (PackageName name) ranges))
-  = concat
-    (map
-        (\ x -> debianRelations (debianDevelPackageName x) ranges)
-      $ filter (not . flip member base) [name])
-develDependencies compiler dep@(ExtraLibs _)
-  = concat
-    (map (\ x -> debianRelations x AnyVersion) $ adapt dep)
-develDependencies _ _ = []
-
--- The build dependencies for a package include the profiling
--- libraries and the documentation packages, used for creating cross
--- references.
-buildDependencies :: Compiler -> Dependency_ -> D.Relations
-buildDependencies
-    compiler
-    (BuildDepends (Dependency (PackageName name) ranges))
-  = concat
-    (map
-      (\ x -> debianRelations x ranges)
-      (if member name base
-        then []
-        else [debianDevelPackageName name, debianProfilingPackageName name]))
-buildDependencies compiler dep@(ExtraLibs _)
-  = concat
-    (map (\ x -> debianRelations x AnyVersion) $ adapt dep)
-buildDependencies compiler dep
-  = concat
-    (map (\ x -> debianRelations x ranges) $ adapt dep)
-    where (Dependency (PackageName name) ranges) = unboxDependency dep
-
-adapt :: Dependency_ -> [String]
-adapt (BuildTools (Dependency (PackageName "gtk2hsC2hs") _))
-  = ["gtk2hs-buildtools"]
-adapt (BuildTools (Dependency (PackageName "gtk2hsHookGenerator") _))
-  = ["gtk2hs-buildtools"]
-adapt (BuildTools (Dependency (PackageName "gtk2hsTypeGen") _))
-  = ["gtk2hs-buildtools"]
-adapt (PkgConfigDepends (Dependency (PackageName pkg) _))
-  = unsafePerformIO
-    $ do
-      ret
-        <- readProcessWithExitCode "apt-file" ["-l", "search", pkg ++ ".pc"] ""
-      return
-        $ case ret of
-            (ExitSuccess, out, _) -> [takeWhile (not . isSpace) out]
-            _ -> []
-adapt (ExtraLibs "gcrypt") = ["libgcrypt11-dev"]
-adapt (ExtraLibs x) = ["lib" ++ x ++ "-dev"]
-adapt dep
-  = [name]
-  where  (Dependency (PackageName name) _) = unboxDependency dep
-
--- The documentation dependencies for a package include the documentation
--- package for any libraries which are build dependencies, so we have access
--- to all the cross references.
-docDependencies :: Compiler -> Dependency_ -> D.Relations
-docDependencies
-    compiler
-    (BuildDepends (Dependency (PackageName name) ranges))
-  = concat
-    (map
-        (\ x -> debianRelations (debianDocumentationPackageName x) ranges)
-      $ filter (not . flip member base) [name])
-docDependencies _ _ = []
-
--- generated with:
--- apt-cache show ghc \
---   | grep ^Provides: \
---   | cut -d\  -f2-
---   | sed 's/, /\n/g' \
---   | grep libghc- \
---   | cut -d- -f2- \
---   | grep dev$ \
---   | sed 's/-dev//;s/$/",/;s/^/"/'
-
-base :: Set String
-base
-  = Data.Set.fromList
-    ["array",
-      "base",
-      "bin-package-db",
-      "bytestring",
-      "cabal",
-      "containers",
-      "directory",
-      "extensible-exceptions",
-      "filepath",
-      "ghc-binary",
-      "ghc-prim",
-      "haskell2010",
-      "haskell98",
-      "hpc",
-      "integer-gmp",
-      "old-locale",
-      "old-time",
-      "pretty",
-      "process",
-      "random",
-      "rts",
-      "template-haskell",
-      "time",
-      "unix"]
-
-debianRelations :: String -> VersionRange -> D.Relations
-debianRelations name range =
-    map (merge . concat . map (relation name)) (canon range)
-    where
-      -- A debian dependency list is always a list of or-relations
-      -- which are anded.  This function turns the more freeform cabal
-      -- relations into that format.
-      canon :: VersionRange -> [[VersionRange]]
-      canon (IntersectVersionRanges a b) = canon a ++ canon b
-      canon (UnionVersionRanges a b) = map concat (cartesianProduct [canon a, canon b])
-      canon x = [[x]]
-      -- Turn simple Cabal relations into Debian relations
-      relation name AnyVersion = [D.Rel name Nothing Nothing]
-      relation name (ThisVersion version) = [D.Rel name (Just (D.EEQ (parseDebianVersion (showVersion version)))) Nothing]
-      relation name (EarlierVersion version) = [D.Rel name (Just (D.SLT (parseDebianVersion (showVersion version)))) Nothing]
-      relation name (LaterVersion version) = [D.Rel name (Just (D.SGR (parseDebianVersion (showVersion version)))) Nothing]
-      relation name (WildcardVersion version) = [D.Rel name (Just (D.GRE (parseDebianVersion (showVersion version)))) Nothing, D.Rel name (Just (D.SLT (parseDebianVersion (showVersion (upperBound version))))) Nothing]
-      relation _ _ = error $ "Invalid argument to debianRelations: " ++ show range
-      -- Merge some combinations that frequently show up.
-      merge (D.Rel name1 (Just (D.EEQ ver1)) arch1 : D.Rel name2 (Just (D.SLT ver2)) arch2 : xs)
-          | name1 == name2 && ver1 == ver2 && arch1 == arch2
-              = merge (D.Rel name1 (Just (D.LTE ver1)) arch1 : xs)
-      merge (D.Rel name1 (Just (D.EEQ ver1)) arch1 : D.Rel name2 (Just (D.SGR ver2)) arch2 : xs)
-          | name1 == name2 && ver1 == ver2 && arch1 == arch2
-              = merge (D.Rel name1 (Just (D.GRE ver1)) arch1 : xs)
-      merge (x : xs) = x : merge xs
-      merge [] = []
-      upperBound v = v { versionBranch = bump (versionBranch v) }
-      bump = reverse . (zipWith (+) (1:(repeat 0))) . reverse
-
-
-debianDocumentationPackageName :: String -> String
-debianDocumentationPackageName x =
-    docPrefix (map toLower x) ++ map toLower x ++ "-doc"
-
--- | cartesianProduct [[1,2,3], [4,5],[6]] -> [[1,4,6],[1,5,6],[2,4,6],[2,5,6],[3,4,6],[3,5,6]]
-cartesianProduct :: [[a]] -> [[a]]
-cartesianProduct = sequence
-
--- | Convert from license to RPM-friendly description.  The strings are
--- taken from TagsCheck.py in the rpmlint distribution.
-
-showLicense :: License -> String
-showLicense (GPL _) = "GPL"
-showLicense (LGPL _) = "LGPL"
-showLicense BSD3 = "BSD"
-showLicense BSD4 = "BSD-like"
-showLicense PublicDomain = "Public Domain"
-showLicense AllRightsReserved = "Proprietary"
-showLicense OtherLicense = "Non-distributable"
diff --git a/Distribution/Package/Debian/Bundled.hs b/Distribution/Package/Debian/Bundled.hs
deleted file mode 100644
--- a/Distribution/Package/Debian/Bundled.hs
+++ /dev/null
@@ -1,332 +0,0 @@
--- |
--- Module      :  Distribution.Package.Debian.Bundled
--- Copyright   :  David Fox 2008
---
--- Maintainer  :  David Fox <dsf@seereason.com>
--- Stability   :  alpha
--- Portability :  portable
---
--- Determine whether a specific version of a Haskell package is
--- bundled with into this particular version of the given compiler.
-
--- This software may be used and distributed according to the terms of
--- the GNU General Public License, incorporated herein by reference.
-
-module Distribution.Package.Debian.Bundled
-    (
-      Bundled 
-    , bundledWith
-    , isBundled
-    , isLibrary
-    , docPrefix
-    , builtIns
-    ) where
-
-import qualified Data.ByteString.Char8 as B
-import Data.Function (on)
-import Data.List (find,isPrefixOf,sortBy)
-import Data.Maybe (maybeToList)
-import Data.Version (Version(..))
-import Debian.Control(Control'(Control), fieldValue, parseControlFromFile)
-import Debian.Relation.ByteString()
-import Debian.Relation(Relation(Rel),parseRelations)
-import Distribution.InstalledPackageInfo(InstalledPackageInfo, libraryDirs, sourcePackageId)
-import Distribution.Simple.Compiler (Compiler(..), CompilerId(..), CompilerFlavor(..), PackageDB(GlobalPackageDB), compilerFlavor)
-import Distribution.Simple.Configure (getInstalledPackages)
--- import Distribution.Simple.GHC  (getInstalledPackages)
-import Distribution.Simple.PackageIndex (PackageIndex, SearchResult(None, Unambiguous, Ambiguous), allPackages, searchByName)
-import Distribution.Simple.Program (configureAllKnownPrograms, defaultProgramConfiguration)
-import Distribution.Package (PackageIdentifier(..), PackageName(..), Dependency(..))
-import Distribution.Verbosity(normal)
-import Distribution.Version (withinRange)
-import Text.ParserCombinators.Parsec(ParseError)
-import Text.Regex.TDFA ((=~))
-
--- | List the packages bundled with this version of the given
--- compiler.  If the answer is not known, return the empty list.
-bundledWith :: [(CompilerFlavor, Version, [PackageIdentifier])] -> Compiler -> Maybe [PackageIdentifier]
-bundledWith builtIns c =
-    let cv = (compilerFlavor c, (\ (CompilerId _ v) -> v) $ compilerId c)
-    in thd `fmap` find (\(n,v,_) -> (n,v) == cv) builtIns
-  where thd (_,_,x) = x
-
--- | Determine whether a specific version of a Haskell package is
--- bundled with into this particular version of the given compiler.
-isBundled :: [(CompilerFlavor, Version, [PackageIdentifier])] -> Compiler -> Dependency -> Bool
-isBundled builtIns c (Dependency pkg version) =
-    let cv = (compilerFlavor c, (\ (CompilerId _ v) -> v) (compilerId c))
-    in
-      case find (\(n, k, _) -> (n,k) == cv) builtIns of
-        Nothing -> False
-        (Just (_, _, cb)) ->
-          any checkVersion $ pkgVersion `fmap` filter ((== pkg) . pkgName) cb
-  where checkVersion = flip withinRange version
-
-type Bundled = (CompilerFlavor, Version, [PackageIdentifier])
-
-builtIns :: Compiler -> IO [Bundled]
-builtIns compiler = 
-    do ghc6 <- fmap maybeToList $ ghc6BuiltIns compiler
-       return $ ghc6 ++ [ (GHC, Version [7,0,1] [], ghc701BuiltIns)
-                        , (GHC, Version [6,8,3] [], ghc683BuiltIns)
-                        , (GHC, Version [6,8,2] [], ghc682BuiltIns)
-                        , (GHC, Version [6,8,1] [], ghc681BuiltIns)
-                        , (GHC, Version [6,6,1] [], ghc661BuiltIns)
-                        , (GHC, Version [6,6] [], ghc66BuiltIns)
-                        ]
-ghc6BuiltIns :: Compiler -> IO (Maybe (CompilerFlavor, Version, [PackageIdentifier]))
-ghc6BuiltIns compiler@(Compiler {compilerId = CompilerId GHC compilerVersion}) =
-#ifdef CABAL19
-    do installedPackages <- getInstalledPackageIndex compiler
-       ghc6Files <- fmap lines $ readFile "/var/lib/dpkg/info/ghc.list"
-       let ghcProvides = filter (\package -> any (\dir -> elem dir ghc6Files) (libraryDirs package)) (allPackages installedPackages)
-       return (Just (GHC, compilerVersion, map sourcePackageId ghcProvides))
-#else
-    do mInstalledPackages <- getInstalledPackageIndex compiler
-       case mInstalledPackages of
-         Nothing -> error "Could not find the installed package database."
-         (Just installedPackages) ->
-             do ghc6Files <- fmap lines $ readFile "/var/lib/dpkg/info/ghc.list"
-                let ghcProvides = filter (\package -> any (\dir -> elem dir ghc6Files) (libraryDirs package)) (allPackages installedPackages)
-                return (Just (GHC, compilerVersion, map sourcePackageId ghcProvides))
-#endif
-ghc6BuiltIns _ = return Nothing
-
-ghc6BuiltIns' :: Compiler -> IO (Maybe (CompilerFlavor, Version, [PackageIdentifier]))
-ghc6BuiltIns' compiler@(Compiler {compilerId = CompilerId GHC compilerVersion}) =
-    do eDebs <- ghc6Provides
-       case eDebs of
-         Left e -> error e
-         Right debNames ->
-#ifdef CABAL19
-             do installedPackages <- getInstalledPackageIndex compiler
-                let packages = concatMap (\n -> fromRight $ installedVersions (fromRight $ extractBaseName n) installedPackages) debNames
-                return $ Just (GHC, compilerVersion, packages)
-#else
-             do mInstalledPackages <- getInstalledPackageIndex compiler
-                case mInstalledPackages of
-                  Nothing -> error "Could not find the installed package database."
-                  (Just installedPackages) ->
-                      let packages = concatMap (\n -> fromRight $ installedVersions (fromRight $ extractBaseName n) installedPackages) debNames
-                      in
-                        return $ Just (GHC, compilerVersion, packages)
-#endif
-    where
-      fromRight (Right r) = r
-      fromRight (Left e) = error e
-ghc6BuiltIns' compiler@(Compiler {}) = return Nothing
-
-ghc6Provides :: IO (Either String [String])
-ghc6Provides = 
-    do eC <- parseControlFromFile "/var/lib/dpkg/status" :: IO (Either ParseError (Control' B.ByteString))
-       case eC of
-         Left e  -> return $ Left (show e)
-         Right (Control c) ->
-             case find (\p -> fieldValue "Package" p == Just (B.pack "ghc")) c of
-               Nothing -> return $ Left "You do not seem to have ghc installed."
-               (Just p) ->
-                   case fieldValue "Provides" p of
-                     Nothing -> return $ Left "Your ghc package does not seem to Provide anything."
-                     (Just p) -> 
-                         case parseRelations p of
-                           (Left e) -> return (Left (show e))
-                           (Right relations) ->
-                               return $ Right $ filter (isPrefixOf "libghc-") $ map (\ (Rel pkgName _ _) -> pkgName) (concat relations)
-
-
-extractBaseName :: String -> Either String String
-extractBaseName name =
-    let (_,_,_,subs) = (name =~ "^libghc-(.*)-.*$") :: (String, String, String, [String])
-    in case subs of
-         [base] -> Right base
-         _ -> Left ("When attempt to extract the base name of " ++ name ++ " I found the following matches: " ++ show subs)
-                 
---getInstalledPackageIndex :: Compiler -> IO (Maybe PackageIndex)
-getInstalledPackageIndex compiler =
-    do pc  <- configureAllKnownPrograms normal  defaultProgramConfiguration
-       getInstalledPackages normal compiler [GlobalPackageDB] pc
-
-installedVersions :: String -> PackageIndex -> Either String [PackageIdentifier]
-installedVersions name packageIndex = 
-    case searchByName packageIndex name of
-      None -> Left $ "The package " ++ name ++ " does not seem to be installed."
-      Unambiguous pkgs -> 
-          case sortBy (compare `on` (pkgVersion . sourcePackageId)) pkgs of
-            [] -> Left $ "Odd. searchByName returned an empty Unambiguous match for " ++ name
-            ps -> Right (map sourcePackageId ps)
-                                   
-v :: String -> [Int] -> PackageIdentifier
-v n x = PackageIdentifier (PackageName n) (Version x [])
-
-ghc701BuiltIns :: [PackageIdentifier]
-ghc701BuiltIns = [
-    v "Cabal" [1,10,0,0],
-    v "array" [0,3,0,2],
-    v "base" [4,3,0,0],
-    v "bin-package-db" [0,0,0,0],
-    v "bytestring" [0,9,1,8],
-    v "containers" [0,4,0,0],
-    v "directory" [1,1,0,0],
-    v "extensible-exceptions" [0,1,1,2],
-    v "filepath" [1,2,0,0],
-    v "ghc" [7,0,1],
-    v "ghc-binary" [0,5,0,2],
-    v "ghc-prim" [0,2,0,0],
-    v "haskell2010" [1,0,0,0],
-    v "haskell98" [1,1,0,0],
-    v "hpc" [0,5,0,6],
-    v "integer-gmp" [0,2,0,2],
-    v "old-locale" [1,0,0,2],
-    v "old-time" [1,0,0,6],
-    v "pretty" [1,0,1,2],
-    v "process" [1,0,1,4],
-    v "random" [1,0,0,3],
-    v "rts" [1,0],
-    v "template-haskell" [2,5,0,0],
-    v "time" [1,2,0,3],
-    v "unix" [2,4,1,0]
-  ]
-
-ghc683BuiltIns :: [PackageIdentifier]
-ghc683BuiltIns = ghc682BuiltIns
-
-ghc682BuiltIns :: [PackageIdentifier]
-ghc682BuiltIns = [
-    v "Cabal" [1,2,3,0],
-    v "array" [0,1,0,0],
-    v "base" [3,0,1,0],
-    v "bytestring" [0,9,0,1],
-    v "containers" [0,1,0,1],
-    v "directory" [1,0,0,0],
-    v "filepath" [1,1,0,0],
-    v "ghc" [6,8,2,0],
-    v "haskell98" [1,0,1,0],
-    v "hpc" [0,5,0,0],
-    v "old-locale" [1,0,0,0],
-    v "old-time" [1,0,0,0],
-    v "packedstring" [0,1,0,0],
-    v "pretty" [1,0,0,0],
-    v "process" [1,0,0,0],
-    v "random" [1,0,0,0],
-    v "readline" [1,0,1,0],
-    v "template-haskell" [2,2,0,0],
-    v "unix" [2,3,0,0]
-    ]
-
-ghc681BuiltIns :: [PackageIdentifier]
-ghc681BuiltIns = [
-    v "base" [3,0,0,0],
-    v "Cabal" [1,2,2,0],
-    v "GLUT" [2,1,1,1],
-    v "HGL" [3,2,0,0],
-    v "HUnit" [1,2,0,0],
-    v "OpenAL" [1,3,1,1],
-    v "OpenGL" [2,2,1,1],
-    v "QuickCheck" [1,1,0,0],
-    v "X11" [1,2,3,1],
-    v "array" [0,1,0,0],
-    v "bytestring" [0,9,0,1],
-    v "cgi" [3001,1,5,1],
-    v "containers" [0,1,0,0],
-    v "directory" [1,0,0,0],
-    v "fgl" [5,4,1,1],
-    v "filepatch" [1,1,0,0],
-    v "ghc" [6,8,1,0],
-    v "haskell-src" [1,0,1,1],
-    v "haskell98" [1,0,1,0],
-    v "hpc" [0,5,0,0],
-    v "html" [1,0,1,1],
-    v "mtl" [1,1,0,0],
-    v "network" [2,1,0,0],
-    v "old-locale" [1,0,0,0],
-    v "old-time" [1,0,0,0],
-    v "packedstring" [0,1,0,0],
-    v "parallel" [1,0,0,0],
-    v "parsec" [2,1,0,0],
-    v "pretty" [1,0,0,0],
-    v "process" [1,0,0,0],
-    v "random" [1,0,0,0],
-    v "readline" [1,0,1,0],
-    v "regex-base" [0,72,0,1],
-    v "regex-compat" [0,71,0,1],
-    v "regex-posix" [0,72,0,1],
-    v "stm" [2,1,1,0],
-    v "template-haskell" [2,2,0,0],
-    v "time" [1,1,2,0],
-    v "unix" [2,2,0,0],
-    v "xhtml" [3000,0,2,1]
-    ]
-
-ghc661BuiltIns :: [PackageIdentifier]
-ghc661BuiltIns = [
-    v "base" [2,1,1],
-    v "Cabal" [1,1,6,2],
-    v "cgi" [3001,1,1],
-    v "fgl" [5,4,1],
-    v "filepath" [1,0],
-    v "ghc" [6,6,1],
-    v "GLUT" [2,1,1],
-    v "haskell98" [1,0],
-    v "haskell-src" [1,0,1],
-    v "HGL" [3,1,1],
-    v "html" [1,0,1],
-    v "HUnit" [1,1,1],
-    v "mtl" [1,0,1],
-    v "network" [2,0,1],
-    v "OpenAL" [1,3,1],
-    v "OpenGL" [2,2,1],
-    v "parsec" [2,0],
-    v "QuickCheck" [1,0,1],
-    v "readline" [1,0],
-    v "regex-base" [0,72],
-    v "regex-compat" [0,71],
-    v "regex-posix" [0,71],
-    v "rts" [1,0],
-    v "stm" [2,0],
-    v "template-haskell" [2,1],
-    v "time" [1,1,1],
-    v "unix" [2,1],
-    v "X11" [1,2,1],
-    v "xhtml" [3000,0,2]
-    ]
-
-ghc66BuiltIns :: [PackageIdentifier]
-ghc66BuiltIns = [
-    v "base" [2,0],
-    v "Cabal" [1,1,6],
-    v "cgi" [2006,9,6],
-    v "fgl" [5,2],
-    v "ghc" [6,6],
-    v "GLUT" [2,0],
-    v "haskell98" [1,0],
-    v "haskell-src" [1,0],
-    v "HGL" [3,1],
-    v "html" [1,0],
-    v "HTTP" [2006,7,7],
-    v "HUnit" [1,1],
-    v "mtl" [1,0],
-    v "network" [2,0],
-    v "OpenAL" [1,3],
-    v "OpenGL" [2,1],
-    v "parsec" [2,0],
-    v "QuickCheck" [1,0],
-    v "readline" [1,0],
-    v "regex-base" [0,71],
-    v "regex-compat" [0,71],
-    v "regex-posix" [0,71],
-    v "rts" [1,0],
-    v "stm" [2,0],
-    v "template-haskell" [2,0],
-    v "time" [1,0],
-    v "unix" [1,0],
-    v "X11" [1,1],
-    v "xhtml" [2006,9,13]
-    ]
-
--- |Some dependencies are libraries, some are executables.
-isLibrary :: Compiler -> Dependency -> Bool
-isLibrary _ (Dependency (PackageName "happy") _ ) = False
-isLibrary _ _ = True
-
-docPrefix :: String -> String
-docPrefix _ = "libghc-"
diff --git a/Distribution/Package/Debian/Main.hs b/Distribution/Package/Debian/Main.hs
deleted file mode 100644
--- a/Distribution/Package/Debian/Main.hs
+++ /dev/null
@@ -1,28 +0,0 @@
--- |
--- Module      :  Distribution.Package.Debian.Main
--- Copyright   :  David Fox 2008
---
--- Maintainer  :  David Fox <dsf@seereason.com>
--- Stability   :  alpha
--- Portability :  portable
---
--- Explanation: Main entry point for Debianizer of Cabal packages.
-
--- This software may be used and distributed according to the terms of
--- the GNU General Public License, incorporated herein by reference.
-
-module Distribution.Package.Debian.Main where
-
-import Distribution.PackageDescription.Parse (readPackageDescription)
-import Distribution.Package.Debian (debian)
-import Distribution.Package.Debian.Setup (Flags (..), parseArgs)
-import Distribution.Simple.Utils (defaultPackageDesc)
-import System.Environment (getArgs)
-
-main :: IO ()
-
-main = do opts <- getArgs >>= parseArgs
-          let verbosity = rpmVerbosity opts
-          descPath <- defaultPackageDesc verbosity
-          pkgDesc <- readPackageDescription verbosity descPath
-          debian pkgDesc opts
diff --git a/Distribution/Package/Debian/Setup.hs b/Distribution/Package/Debian/Setup.hs
deleted file mode 100644
--- a/Distribution/Package/Debian/Setup.hs
+++ /dev/null
@@ -1,159 +0,0 @@
--- |
--- Module      :  Distribution.Package.Debian.Setup
--- Copyright   :  David Fox 2008
---
--- Maintainer  :  David Fox <dsf@seereason.com>
--- Stability   :  alpha
--- Portability :  portable
---
--- Explanation: Command line option processing for building RPM
--- packages.
-
--- This software may be used and distributed according to the terms of
--- the GNU General Public License, incorporated herein by reference.
-
-module Distribution.Package.Debian.Setup (
-      Flags(..)
-    , DebAction(..)
-    , DebType(..)
-    , parseArgs
-    ) where
-
-import Control.Monad (when)
-import Data.Char (toLower)
-import Distribution.Compiler (CompilerFlavor(..))
-import Distribution.ReadE (readEOrFail)
-import Distribution.PackageDescription (FlagName(..))
-import Distribution.Verbosity (Verbosity, flagToVerbosity, normal)
-import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..),
-                              usageInfo, getOpt')
-import System.Environment (getProgName)
-import System.Exit (exitWith, ExitCode (..))
-import System.IO (Handle, hPutStrLn, stderr, stdout)
-
-data Flags = Flags
-    {
-      rpmPrefix :: FilePath
-    , rpmCompiler :: CompilerFlavor
-    , rpmConfigurationsFlags :: [(FlagName, Bool)]
-    , rpmHaddock :: Bool
-    , rpmHelp :: Bool
-    , debLibProf :: Bool
-    , rpmName :: Maybe String
-    , rpmOptimisation :: Bool
-    , rpmRelease :: Maybe String
-    , rpmSplitObjs :: Bool
-    , debOutputDir :: FilePath
-    , rpmVerbosity :: Verbosity
-    , rpmVersion :: Maybe String
-    , debMaintainer :: Maybe String
-    , debAction :: DebAction
-    }
-    deriving (Eq, Show)
-
-data DebType = Dev| Prof | Doc deriving (Eq, Read, Show)
-
-data DebAction = Usage | Debianize | SubstVar DebType | UpdateDebianization deriving (Eq, Show)
-
-emptyFlags :: Flags
-
-emptyFlags = Flags
-    {
-      rpmPrefix = "/usr/lib/haskell-packages/ghc6"
-    , rpmCompiler = GHC
-    , rpmConfigurationsFlags = []
-    , rpmHaddock = True
-    , rpmHelp = False
-    , debLibProf = True
-    , rpmName = Nothing
-    , rpmOptimisation = True
-    , rpmRelease = Nothing
-    , rpmSplitObjs = True
-    , debOutputDir = "./debian"
-    , rpmVerbosity = normal
-    , rpmVersion = Nothing
-    , debMaintainer = Nothing
-    , debAction = Usage
-    }
-
-options :: [OptDescr (Flags -> Flags)]
-
-options =
-    [
-      Option "" ["prefix"] (ReqArg (\ path x -> x { rpmPrefix = path }) "PATH")
-             "Pass this prefix if we need to configure the package",
-      Option "" ["ghc"] (NoArg (\x -> x { rpmCompiler = GHC }))
-             "Compile with GHC",
-      Option "" ["hugs"] (NoArg (\x -> x { rpmCompiler = Hugs }))
-             "Compile with Hugs",
-      Option "" ["jhc"] (NoArg (\x -> x { rpmCompiler = JHC }))
-             "Compile with JHC",
-      Option "" ["nhc"] (NoArg (\x -> x { rpmCompiler = NHC }))
-             "Compile with NHC",
-      Option "h?" ["help"] (NoArg (\x -> x { rpmHelp = True }))
-             "Show this help text",
-      Option "" ["name"] (ReqArg (\name x -> x { rpmName = Just name }) "NAME")
-             "Override the default package name",
-      Option "" ["disable-haddock"] (NoArg (\x -> x { rpmHaddock = False }))
-             "Don't generate API docs",
-      Option "" ["disable-library-profiling"] (NoArg (\x -> x { debLibProf = False }))
-             "Don't generate profiling libraries",
-      Option "" ["disable-optimization"] (NoArg (\x -> x { rpmOptimisation = False }))
-             "Don't generate optimised code",
-      Option "" ["disable-split-objs"] (NoArg (\x -> x { rpmSplitObjs = False }))
-             "Don't split object files to save space",
-      Option "f" ["flags"] (ReqArg (\flags x -> x { rpmConfigurationsFlags = rpmConfigurationsFlags x ++ flagList flags }) "FLAGS")
-             "Set given flags in Cabal conditionals",
-      Option "" ["release"] (ReqArg (\rel x -> x { rpmRelease = Just rel }) "RELEASE")
-             "Override the default package release",
-      Option "" ["debdir"] (ReqArg (\path x -> x { debOutputDir = path }) "DEBDIR")
-             ("Override the default output directory (" ++ show (debOutputDir emptyFlags) ++ ")"),
-      Option "v" ["verbose"] (ReqArg (\verb x -> x { rpmVerbosity = readEOrFail flagToVerbosity verb }) "n")
-             "Change build verbosity",
-      Option "" ["version"] (ReqArg (\vers x -> x { rpmVersion = Just vers }) "VERSION")
-             "Override the default package version",
-      Option "" ["maintainer"] (ReqArg (\maint x -> x { debMaintainer = Just maint }) "Maintainer Name <email addr>")
-             "Override the Maintainer name and email in $DEBEMAIL/$EMAIL/$DEBFULLNAME/$FULLNAME",
-      Option "" ["debianize"] (NoArg (\x -> x {debAction = Debianize}))
-             "Generate a new debianization, replacing any existing one.  One of --debianize, --substvar, or --update-debianization is required.",
-      Option "" ["substvar"] (ReqArg (\ name x -> x {debAction = SubstVar (read name)}) "Doc, Prof, or Dev")
-             (unlines ["Write out the list of dependencies required for the dev, prof or doc package depending",
-                       "on the argument.  This value can be added to the appropriate substvars file."]),
-      Option "" ["update-debianization"] (NoArg (\x -> x {debAction = UpdateDebianization}))
-             "Update an existing debianization, or generate a new one."
-    ]
-
--- Lifted from Distribution.Simple.Setup, since it's not exported.
-flagList :: String -> [(FlagName, Bool)]
-flagList = map tagWithValue . words
-  where tagWithValue ('-':name) = (FlagName (map toLower name), False)
-        tagWithValue name       = (FlagName (map toLower name), True)
-
-printHelp :: Handle -> IO ()
-
-printHelp h = do
-    progName <- getProgName
-    let info = "Usage: " ++ progName ++ " [FLAGS]\n"
-    hPutStrLn h (usageInfo info options)
-
-parseArgs :: [String] -> IO Flags
-
-parseArgs args = do
-     let (os, args', unknown, errs) = getOpt' RequireOrder options args
-         opts = foldl (flip ($)) emptyFlags os
-     when (rpmHelp opts || debAction opts == Usage) $ do
-       printHelp stdout
-       exitWith ExitSuccess
-     when (not (null errs)) $ do
-       hPutStrLn stderr "Errors:"
-       mapM_ (hPutStrLn stderr) errs
-       exitWith (ExitFailure 1)
-     when (not (null unknown)) $ do
-       hPutStrLn stderr "Unrecognised options:"
-       mapM_ (hPutStrLn stderr) unknown
-       exitWith (ExitFailure 1)
-     when (not (null args')) $ do
-       hPutStrLn stderr "Unrecognised arguments:"
-       mapM_ (hPutStrLn stderr) args'
-       exitWith (ExitFailure 1)
-     return opts
diff --git a/Setup.hs b/Setup.hs
--- a/Setup.hs
+++ b/Setup.hs
@@ -6,9 +6,10 @@
 import System.Exit
 
 main = defaultMainWithHooks simpleUserHooks {
-         runTests = runTestScript
+         postBuild = \ _ _ _ _ -> runTestScript
+       , runTests = \ _ _ _ _ -> runTestScript
        }
 
-runTestScript _args _flag _pd _lbi =
-    system "runhaskell Test/Main.hs" >>=
-    \ code -> if code == ExitSuccess then return () else error "Test Failure"
+runTestScript =
+    system "runhaskell Test/Main.hs" >>= \ code ->
+    if code == ExitSuccess then return () else error "Test Failure"
diff --git a/Test/Changes.hs b/Test/Changes.hs
--- a/Test/Changes.hs
+++ b/Test/Changes.hs
@@ -5,7 +5,11 @@
 import Data.List (intercalate)
 import Debian.Changes
 import Debian.Release (ReleaseName(ReleaseName, relName))
-import Debian.Version (parseDebianVersion)
+import Debian.Version (DebianVersion, prettyDebianVersion, parseDebianVersion)
+
+instance Show DebianVersion where
+    show = show . prettyDebianVersion
+deriving instance Show ChangeLogEntry
 
 s3 = intercalate "\n" 
      ["name (version) dist; urgency=urgency",
diff --git a/Test/Dependencies.hs b/Test/Dependencies.hs
--- a/Test/Dependencies.hs
+++ b/Test/Dependencies.hs
@@ -1,3 +1,4 @@
+{-# LANGUAGE StandaloneDeriving #-}
 module Test.Dependencies where
 
 import Control.Arrow
@@ -131,6 +132,13 @@
 
 mapSnd :: (b -> c) -> [(a,b)] -> [(a,c)]
 mapSnd f = map (second f)
+
+instance Show DebianVersion where
+    show = show . prettyDebianVersion
+deriving instance Show Status
+deriving instance Show Relation
+deriving instance Show VersionReq
+deriving instance Show ArchitectureReq
 
 test1 =
     let csp = mkCSP control "a" depends
diff --git a/Test/SourcesList.hs b/Test/SourcesList.hs
--- a/Test/SourcesList.hs
+++ b/Test/SourcesList.hs
@@ -3,7 +3,7 @@
 import Test.HUnit
 
 import Debian.Sources
-import Data.Maybe
+--import Data.Maybe
 
 -- * Unit Tests
 
@@ -40,7 +40,7 @@
                     , "deb http://ftp.debian.org/whee space%20dist main"
                     , "deb http://ftp.debian.org/whee dist space%20section"
                     ]
-      invalidSourcesListStr1 = "deb http://pkg-kde.alioth.debian.org/kde-3.5.0/ ./ main contrib non-free # exact path with sections"
+      _invalidSourcesListStr1 = "deb http://pkg-kde.alioth.debian.org/kde-3.5.0/ ./ main contrib non-free # exact path with sections"
 
 testSourcesListParse :: Test
 testSourcesListParse =
@@ -55,5 +55,6 @@
                       "deb http://security.ubuntu.com/ubuntu/ gutsy-security main restricted universe multiverse\n",
                       "deb-src http://security.ubuntu.com/ubuntu/ gutsy-security main restricted universe multiverse\n"])
 
+sourcesListTests :: [Test]
 sourcesListTests =
     [ testQuoteWords, testSourcesList, testSourcesListParse ]
diff --git a/cbits/gwinsz.h b/cbits/gwinsz.h
new file mode 100644
--- /dev/null
+++ b/cbits/gwinsz.h
@@ -0,0 +1,1 @@
+unsigned long c_get_window_size(void);
diff --git a/debian.cabal b/debian.cabal
--- a/debian.cabal
+++ b/debian.cabal
@@ -1,11 +1,11 @@
 Name:           debian
-Version:        3.55
+Version:        3.61
 License:        BSD3
 License-File:   debian/copyright
-Author:         David Fox <dsf@seereason.com>
-Category:       System
-Maintainer:     Marco Túlio Gontijo e Silva <marcot@debian.org>
-Homepage:       http://marcot.eti.br/darcs/haskell-debian
+Author:         David Fox <dsf@seereason.com>, Jeremy Shaw <jeremy@seereason.com>, Clifford Beshers <beshers@seereason.com>
+Category:       Debian
+Maintainer:     David Fox ,dsf@seereason.com>
+Homepage:       http://src.seereason.com/haskell-debian-new
 Build-Type:     Simple
 Synopsis:       Modules for working with the Debian package system
 Cabal-Version: >= 1.6
@@ -22,9 +22,9 @@
 Library
  Build-Depends:  base >= 4 && < 5, bytestring, containers, directory,
                  filepath, mtl, network, old-locale, parsec >= 2 && <4, pretty, process,
-                 regex-tdfa, regex-compat, time, unix, bzlib, HaXml == 1.20.*, Unixutils >= 1.32, zlib, HUnit,
+                 regex-tdfa, regex-compat, time, unix, bzlib, HaXml >= 1.20, Unixutils >= 1.41, zlib, HUnit,
                  utf8-string
- ghc-options: -W -Wall
+ ghc-options: -W -Wall -O2
  if flag(cabal19)
    build-depends: Cabal >= 1.9
    cpp-options: -DCABAL19
@@ -62,10 +62,6 @@
         Debian.Util.FakeChanges
  other-modules:
         Debian.Version.Internal,
-        Distribution.Package.Debian.Bundled,
-        Distribution.Package.Debian.Setup,
-        Distribution.Package.Debian.Main,
-        Distribution.Package.Debian,
         Test.Changes,
         Test.Dependencies,
         Test.SourcesList,
@@ -73,7 +69,7 @@
 
 Executable fakechanges
  Main-is: utils/FakeChanges.hs
- ghc-options: -threaded -W
+ ghc-options: -threaded -W -O2
  Extensions:           ExistentialQuantification CPP
  if flag(cabal19)
    build-depends: Cabal >= 1.9
@@ -84,7 +80,7 @@
 
 Executable debian-report
  Main-is: utils/Report.hs
- ghc-options: -threaded -W
+ ghc-options: -threaded -W -O2
  C-Sources:           cbits/gwinsz.c
  Include-Dirs:        cbits
  Install-Includes:    gwinsz.h
@@ -96,21 +92,9 @@
    build-depends: Cabal >= 1.8
    cpp-options: -DCABAL18
 
-Executable cabal-debian
- Main-is: utils/CabalDebian.hs
- ghc-options: -threaded -W
- Build-Depends: Cabal >= 1.6.0.1
- Extensions:           ExistentialQuantification CPP
- if flag(cabal19)
-   build-depends: Cabal >= 1.9
-   cpp-options: -DCABAL19
- else
-   build-depends: Cabal >= 1.8
-   cpp-options: -DCABAL18
-
 Executable apt-get-build-depends
  Main-is: utils/AptGetBuildDeps.hs
- ghc-options: -threaded -W
+ ghc-options: -threaded -W -O2
  Extensions:           ExistentialQuantification CPP
  if flag(cabal19)
    build-depends: Cabal >= 1.9
@@ -121,4 +105,4 @@
 
 source-repository head
   type:     darcs
-  location: http://marcot.eti.br/darcs/haskell-debian
+  location: http://src.seereason.com/darcs/haskell-debian-new
diff --git a/debian/apt-get-build-depends.1 b/debian/apt-get-build-depends.1
new file mode 100644
--- /dev/null
+++ b/debian/apt-get-build-depends.1
@@ -0,0 +1,17 @@
+.TH APT-GET-BUILD-DEPENDS 1  "May 10, 2010"
+
+.SH NAME
+apt-get-build-depends \- apt-get install build depends
+
+.SH SYNOPSIS
+.B apt-get-build-depends
+.RI 
+
+.SH DESCRIPTION
+apt-get-build-depends parse the Build-Depends{-Indep} lines from a
+debian/control file and apt-get installs the required packages.
+
+.SH AUTHOR
+This manual page was originally written by Erik de Castro Lopo 
+<erikd@mega-nerd.com> for the Debian GNU/Linux system (but may be used by 
+others).
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,121 @@
+haskell-debian (3.61) unstable; urgency=low
+
+  * Uploading to hackage.
+  * Remove crypto++ dependency (it was a mistake.)
+  * Add optimization flag to ghc-options
+  * Reference seereason darcs repo
+
+ -- David Fox <dsf@seereason.com>  Thu, 06 Oct 2011 09:04:38 -0700
+
+haskell-debian (3.60) unstable; urgency=low
+
+  * Replace bogus Show instances in Debian.Relation.Common with pretty
+    printing functions.
+  * Change cabal category from System to Debian (to join the dpkg package)
+  * Fix some of the compiler warnings.
+  * Change the Show instances in Debian.Version into pretty printing
+    functions too.
+
+ -- David Fox <dsf@seereason.com>  Sun, 25 Sep 2011 07:33:25 -0700
+
+haskell-debian (3.59) unstable; urgency=low
+
+  * Move the cabal-debian program into a separate pacakge.
+
+ -- David Fox <dsf@seereason.com>  Sun, 18 Sep 2011 06:43:36 -0700
+
+haskell-debian (3.58-0.2) unstable; urgency=low
+
+  * Remove the --deb-name option, all the package name special cases need
+    to be encoded in the Distribution.Package.Debian.Bundled.debianName function
+    so that we can fix both the names for the package we are building and
+    the names of its dependencies.
+
+ -- David Fox <dsf@seereason.com>  Thu, 25 Aug 2011 10:58:11 -0700
+
+haskell-debian (3.58-0.1) unstable; urgency=low
+
+  * Add --deb-name option, which sets the part of the package name between
+    the prefix libghc- and the suffix -dev.
+  * Add --epoch
+  * Add --deb-version
+
+ -- David Fox <dsf@seereason.com>  Wed, 24 Aug 2011 20:45:33 -0700
+
+haskell-debian (3.58) unstable; urgency=low
+
+  * Add a --ghc-version option to specify what the ghc version is in the
+    build environment, in case it is different from the one where the
+    autobuilder is being run.  This affects what packages cabal-debian
+    thinks are built into the compiler.  I have non-working code to actually
+    look in the environment for this information, but it depends on having
+    the compiler already installed there.
+  * Greatly sped-up cabal-debian.
+  * Add --build-dep to specify extra build dependencies.
+  * Generate a haskell-packagename-utils deb with all the executables, rather
+    than one deb per executable.
+
+ -- David Fox <dsf@seereason.com>  Fri, 19 Aug 2011 08:34:36 -0700
+
+haskell-debian (3.57) unstable; urgency=low
+
+  * Re-order generated dependencies so we are more likely to build
+    with newer packages installed.
+
+ -- David Fox <dsf@seereason.com>  Tue, 16 Aug 2011 19:04:29 -0700
+
+haskell-debian (3.56-1) unstable; urgency=low
+
+  * I created a new repository by importing the sid version of
+    haskell-debian-3.55 and then applying my patches.  This is because
+    I don't understand why Marco's repository is so different from the
+    code in sid.  At some point we will get this all sorted out.
+
+ -- David Fox <dsf@seereason.com>  Tue, 16 Aug 2011 13:00:15 -0700
+
+haskell-debian (3.55-2) unstable; urgency=low
+
+  * Build against parsec 3
+
+ -- Joachim Breitner <nomeata@debian.org>  Mon, 13 Jun 2011 18:13:10 +0200
+
+haskell-debian (3.55-1) unstable; urgency=low
+
+  * Use ghc instead of ghc6
+  * control: Standards-Version: Bump, no changes needed.
+  * control: haskell-debian-utils: Adds Recommends: apt-file.
+  * New upstream version.
+  * patches/dont-build-teste.patch: Update patch to new upstream
+    version.
+  * control: Update dependency on haxml to 1.20.*.
+  * control: Depends on utf8-string.
+
+ -- Marco Túlio Gontijo e Silva <marcot@debian.org>  Fri, 03 Jun 2011 22:49:23 -0300
+
+haskell-debian (3.47-3) unstable; urgency=low
+
+  * Re-add dont-build-tests.patch, lost in the previous upload 
+
+ -- Joachim Breitner <nomeata@debian.org>  Thu, 24 Jun 2010 19:33:30 +0200
+
+haskell-debian (3.47-2) unstable; urgency=low
+
+  [ Erik de Castro Lopo ]
+  * debian/control: Fix lintian warnings.
+  * Add man pages for apt-get-build-depends, cabal-debian, debian-report and
+    fakechanges.
+  * Add libghc6-debian-doc.doc-base.
+  * Move installation of binaries and man pages from rules file to new file
+    haskell-debian-utils.install.
+
+  [ Joachim Breitner ]
+  * Adjust copyright file per FTP master request. 
+  * Bump haskell-regex-tdfa dependency
+
+ -- Joachim Breitner <nomeata@debian.org>  Thu, 24 Jun 2010 09:47:55 +0200
+
+haskell-debian (3.47-1) unstable; urgency=low
+
+  * Initial release.
+
+ -- Joachim Breitner <nomeata@debian.org>  Sun, 09 May 2010 19:08:20 +0200
diff --git a/debian/changelog.pre-debian b/debian/changelog.pre-debian
new file mode 100644
--- /dev/null
+++ b/debian/changelog.pre-debian
@@ -0,0 +1,625 @@
+haskell-debian (3.53) unstable; urgency=low
+
+  * Changes for unixutils-1.30
+  * Changes for unixutils-1.31
+
+ -- David Fox <dsf@seereason.com>  Sun, 26 Dec 2010 09:12:20 -0800
+
+haskell-debian (3.52) unstable; urgency=low
+
+  * Update to work with Cabal 1.10, shipped with ghc7.
+
+ -- David Fox <dsf@seereason.com>  Sat, 20 Nov 2010 07:54:52 -0800
+
+haskell-debian (3.51) unstable; urgency=low
+
+  * Remove dependency on haskell-utils, it is no longer in the repository.
+  * Change the doc package prefix generated by cabal-debian from haskell-
+    to libghc6-, this is the prefix chosen by the Debian packaging team.
+    and I believe that if haskell- is used the documentation ends up in
+    a directory in /usr/share/doc with the libghc6- prefix anyway.
+
+ -- David Fox <dsf@seereason.com>  Mon, 19 Jul 2010 10:37:39 -0700
+
+haskell-debian (3.50) unstable; urgency=low
+
+  * Switch back to regex-tdfa, regex-posix can't match extended ASCII
+    like "\250" =~ "[\249\250]"
+
+ -- David Fox <dsf@seereason.com>  Sun, 18 Jul 2010 22:34:13 +0100
+
+haskell-debian (3.49) unstable; urgency=low
+
+  * Add Show instances.
+
+ -- David Fox <dsf@seereason.com>  Fri, 16 Jul 2010 14:35:15 -0700
+
+haskell-debian (3.48) unstable; urgency=low
+
+  * Switch from regex-tdfa to regex-posix to avoid this failure, which
+    seems to have appeared going from 1.1.2 to 1.1.3:
+    "Explict error in module Text.Regex.TDFA.NewDFA : compressOrbit,1"
+
+ -- David Fox <dsf@seereason.com>  Fri, 16 Jul 2010 10:43:13 -0700
+
+haskell-debian (3.47) unstable; urgency=low
+
+  * require HaXml < 1.14
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Wed, 05 May 2010 14:23:26 -0500
+
+haskell-debian (3.46) unstable; urgency=low
+
+  * Relax the Cabal >= 1.9 requirement by conditionalizing the code
+    that is affected by the change.
+  * Remove the applicative-extras dependency, instead of Failing a
+    use Either [String] a.
+  * Include Joachim Breitner's fixes for the Relation Ord instance.
+  * Do case insensitive field name comparisons in Debian.Control.
+
+ -- David Fox <dsf@seereason.com>  Tue, 04 May 2010 11:55:24 -0700
+
+haskell-debian (3.45) unstable; urgency=low
+
+  * Don't require targets to be Show instance in GenBuildDeps.buildable.
+  * Eliminate use of OldException.
+
+ -- David Fox <dsf@seereason.com>  Fri, 19 Feb 2010 06:47:04 -0800
+
+haskell-debian (3.44) unstable; urgency=low
+
+  * Add a rule to debian/rules to install the executables.
+
+ -- David Fox <dsf@seereason.com>  Thu, 18 Feb 2010 12:16:18 -0800
+
+haskell-debian (3.43) unstable; urgency=low
+
+  * Add a strict version of fileFromURI.
+  * Catch errors thrown by hGetContents when reading control files
+
+ -- David Fox <dsf@seereason.com>  Sat, 02 Jan 2010 12:29:45 -0800
+
+haskell-debian (3.42) unstable; urgency=low
+
+  * Fix signature regex so we always split at the first pair of spaces.
+
+ -- David Fox <dsf@seereason.com>  Tue, 29 Dec 2009 19:25:27 -0800
+
+haskell-debian (3.41) unstable; urgency=low
+
+  * Use Text.Regex.TDFA for parsing changelog instead of Text.Regex.Compat, it
+    can handle Unicode.
+  * Run unit tests during build, add some changelog unit tests.
+
+ -- David Fox <dsf@seereason.com>  Tue, 29 Dec 2009 12:22:40 -0800
+
+haskell-debian (3.40) unstable; urgency=low
+
+  * Remove the now unused Extra.CIO and Debian.Extra.CIO modules
+
+ -- David Fox <dsf@seereason.com>  Mon, 14 Sep 2009 09:41:52 -0700
+
+haskell-debian (3.39) unstable; urgency=low
+
+  * Remove dependency on Extra
+  * Remove debian directory from .cabal
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Wed, 09 Sep 2009 11:57:03 -0500
+
+haskell-debian (3.38) unstable; urgency=low
+
+  * Use parsec 3
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Tue, 28 Jul 2009 19:12:03 -0500
+
+haskell-debian (3.37) unstable; urgency=low
+
+  * Escape the vendor tag before embedding it in a regular expression.
+    (I wrote an escapeForRegex that only escapes +, the character I want
+    to use right now.  This function should be available somewhere in the
+    haskell standard libraries, right?)
+  * Moved the VersionPolicy module to haskell-debian-repo.
+
+ -- David Fox <dsf@seereason.com>  Thu, 23 Jul 2009 07:38:00 -0700
+
+haskell-debian (3.36) unstable; urgency=low
+
+  * Make the changelog parser more liberal, allow a tab character at
+    the beginning of a text line instead of two spaces.  This parses
+    the new changelog entry for hscolour.
+
+ -- David Fox <dsf@seereason.com>  Tue, 21 Jul 2009 06:45:24 -0700
+
+haskell-debian (3.35) unstable; urgency=low
+
+  * removed dependencies on Extra.HaXml
+  * Updated to base >= 4 && < 5
+  * Fixed test suite
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Wed, 01 Jul 2009 09:48:00 -0500
+
+haskell-debian (3.34) unstable; urgency=low
+
+  * cabal-debian: move -doc packages to Build-Depends-Indep
+  * cabal-debian: properly nub Build-Depends and Build-Depends-Indep
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Sun, 03 May 2009 12:15:52 -0500
+
+haskell-debian (3.33) unstable; urgency=low
+
+  * cabal-debian: Setion: libdevel -> haskell
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Thu, 16 Apr 2009 16:22:35 -0500
+
+haskell-debian (3.32) unstable; urgency=low
+
+  * Add fields to Debian.Changes.ChangedFileSpec for SHA1 and SHA256
+    checksums.
+
+ -- David Fox <dsf@seereason.com>  Fri, 03 Apr 2009 07:14:59 -0700
+
+haskell-debian (3.31) unstable; urgency=low
+
+  * update to use newer haskell-devscripts which includes hlibrary.mk
+  * change libghc6-*-doc to haskell-*-doc
+  * move haskell-*-doc to Section: doc
+  * build haskell-*-doc for Architecture 'all' instead of 'any'
+  * make ghc6-doc and haddock Build-Depends-Indep
+  * update Standards-Version to 3.8.1
+  * depend on cdbs and haskell-devscripts instead of haskell-cdbs
+  * only use one space at the beginning of lines in the long description
+  * add ${misc:Depends} to Depends lines
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Mon, 23 Mar 2009 20:18:41 -0500
+
+haskell-debian (3.30) unstable; urgency=low
+
+  * Move the modules for dealing with the repository into a new package
+    named haskell-debian-repo.  The cabal-debian tool remains in this
+    package, so this split means that the repo package can change without
+    triggering massive rebuilding due to build dependencies on
+    cabal-debian.
+
+ -- David Fox <dsf@seereason.com>  Wed, 18 Feb 2009 06:36:25 -0800
+
+haskell-debian (3.29) unstable; urgency=low
+
+  * Add System.Chroot to list of exported modules
+  * Reduce number of modules loaded by CabalDebian.
+
+ -- David Fox <dsf@seereason.com>  Tue, 10 Feb 2009 17:06:47 -0800
+
+haskell-debian (3.28) unstable; urgency=low
+
+  * Add System.Chroot.useEnv, and use it to allow contact with the ssh
+    agent from inside of changeroots.
+
+ -- David Fox <dsf@seereason.com>  Mon, 09 Feb 2009 11:18:59 -0800
+
+haskell-debian (3.27) unstable; urgency=low
+
+  * Added apt-get-build-deps. not librarized yet :(
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Fri, 06 Feb 2009 18:52:36 -0600
+
+haskell-debian (3.26) unstable; urgency=low
+
+  * Improve the code that decides whether the sources.list has changed,
+    to avoid recreating the build environment as often.
+
+ -- David Fox <dsf@seereason.com>  Thu, 05 Feb 2009 08:56:32 -0800
+
+haskell-debian (3.25) unstable; urgency=low
+
+  * Use State monad instead of RWS monad for AptIO
+  * Rename IOState to AptState
+
+ -- David Fox <dsf@seereason.com>  Wed, 04 Feb 2009 09:34:24 -0800
+
+haskell-debian (3.24) unstable; urgency=low
+
+  * Use Data.Time instead of System.Time
+  * Fix code to compute the elapsed time for the dpkg-buildpackage.
+  * Restore some generated dependencies that got dropped out of
+    cabal-debian.
+
+ -- David Fox <dsf@seereason.com>  Sat, 31 Jan 2009 08:45:51 -0800
+
+haskell-debian (3.23) unstable; urgency=low
+
+  * Eliminate the use of EnvPath in most places, just use a regular
+    path instead.  There were very few places where we actually were
+    inside a changeroot.
+
+ -- David Fox <dsf@seereason.com>  Thu, 29 Jan 2009 16:48:23 -0800
+
+haskell-debian (3.22) unstable; urgency=low
+
+  * cabal-debian now has autodetection of ghc6 bundled packages
+
+ -- Jeremy Shaw <jeremy@seereason.com>  Thu, 29 Jan 2009 15:26:25 -0600
+
+haskell-debian (3.21) unstable; urgency=low
+
+  * Don't write out postinst and postrm for the doc package, they are
+    now automatically added by haskell-cdbs.
+
+ -- David Fox <dsf@seereason.com>  Tue, 27 Jan 2009 10:14:20 -0800
+
+haskell-debian (3.20) unstable; urgency=low
+
+  * Modify the buildable function in GenBuildDeps so it returns more
+    info about the ready packages and what packages each one blocks.
+
+ -- David Fox <dsf@seereason.com>  Tue, 27 Jan 2009 06:55:39 -0800
+
+haskell-debian (3.19) unstable; urgency=low
+
+  * Make cabal-debian depend on haskell-cdbs, it used to be the opposite.
+
+ -- David Fox <dsf@seereason.com>  Sun, 25 Jan 2009 15:22:41 -0800
+
+haskell-debian (3.18) unstable; urgency=low
+
+  * Modify cabal-debian to it creates debianizations that use the new
+    haskell-cdbs package instead of our modified haskell-devscripts with
+    the cdbs file hlibrary.mk added in.
+  * Have cabal-debian explain what changes it is making to the dependency
+    list.
+
+ -- David Fox <dsf@seereason.com>  Sat, 24 Jan 2009 07:27:47 -0800
+
+haskell-debian (3.17) unstable; urgency=low
+
+  * Have cabal-debian --substvar print its result to stderr.
+
+ -- David Fox <dsf@seereason.com>  Fri, 23 Jan 2009 10:33:48 -0800
+
+haskell-debian (3.16) unstable; urgency=low
+
+  * Back out register/unregister stuff, just have cabal-debian die if the
+    package doesn't have a library section.
+
+ -- David Fox <dsf@seereason.com>  Thu, 22 Jan 2009 15:33:43 -0800
+
+haskell-debian (3.15) unstable; urgency=low
+
+  * Don't leave package registered after computing lbi.
+
+ -- David Fox <dsf@seereason.com>  Thu, 22 Jan 2009 14:19:23 -0800
+
+haskell-debian (3.14) unstable; urgency=low
+
+  * Fix a bug that resulted in a fromJust Nothing error.
+
+ -- David Fox <dsf@seereason.com>  Thu, 22 Jan 2009 09:59:16 -0800
+
+haskell-debian (3.13) unstable; urgency=low
+
+  * Add the cabal-debian executable to this package to ease bootstrapping.
+
+ -- David Fox <dsf@seereason.com>  Fri, 16 Jan 2009 06:41:40 -0800
+
+haskell-debian (3.12) unstable; urgency=low
+
+  * Export some functions and types from Debian.Apt.Index that were
+    already being used by other applications
+  * Allow relation parser to skip empty relations like such as: a, ,c
+
+ -- Jeremy Shaw <jeremy@n-heptane.com>  Fri, 09 Jan 2009 18:22:09 -0600
+
+haskell-debian (3.11) unstable; urgency=low
+
+  * Gather code to retrieve the text an URI points to into the Debian.URI
+    module.
+
+ -- David Fox <dsf@seereason.com>  Tue, 04 Nov 2008 13:53:33 -0800
+
+haskell-debian (3.10) unstable; urgency=low
+
+  * Change name and arch of doc package.
+
+ -- David Fox <dsf@seereason.com>  Sat, 20 Sep 2008 12:07:38 -0700
+
+haskell-debian (3.9) unstable; urgency=low
+
+  * Compute exactly which packages participate in dependency cycles.
+
+ -- David Fox <dsf@seereason.com>  Mon, 18 Aug 2008 12:42:56 -0700
+
+haskell-debian (3.8) unstable; urgency=low
+
+  * Don't add an extra newline at the end of the Files section when
+    editing the .changes file.
+
+ -- David Fox <dsf@seereason.com>  Mon, 21 Jul 2008 10:57:49 -0700
+
+haskell-debian (3.7) unstable; urgency=low
+
+  * Eliminate all direct uses of TIO, we always use CIO m => so
+    that all functions can be called from the regular IO monad.
+
+ -- David Fox <dsf@seereason.com>  Sat, 19 Jul 2008 10:27:49 -0700
+
+haskell-debian (3.6) unstable; urgency=low
+
+  * Remove useless arguments from insertRelease.
+  * Replace debianization
+
+ -- David Fox <dsf@seereason.com>  Tue, 01 Jul 2008 10:41:22 -0700
+
+haskell-debian (3.5) unstable; urgency=low
+
+  * Debianization generated by cabal-debian
+
+ -- David Fox <dsf@seereason.com>  Sat, 28 Jun 2008 15:49:07 -0700
+
+haskell-debian (3.4) unstable; urgency=low
+
+  * Even correcter code for doing Relax-Depends.  The relaxDeps function
+    is now seperate from the other build depenency functions, which makes
+    things a bit simpler and easier to document.
+
+ -- David Fox <dsf@seereason.com>  Wed, 18 Jun 2008 21:00:36 +0000
+
+haskell-debian (3.3) unstable; urgency=low
+
+  * Add code to correctly implement Relax-Depends for non-global
+    dependencies.
+
+ -- David Fox <dsf@seereason.com>  Sat, 31 May 2008 07:31:15 +0000
+
+haskell-debian (3.2) unstable; urgency=low
+
+  * Redo the buildable function in GenBuildDeps.
+  * Improve message from OSImage.updateLists.
+
+ -- David Fox <dsf@seereason.com>  Sat, 24 May 2008 13:06:09 +0000
+
+haskell-debian (3.1-1) unstable; urgency=low
+
+  * Version number follies.
+
+ -- David Fox <dsf@seereason.com>  Thu, 22 May 2008 16:18:47 -0700
+
+haskell-debian (3.1) unstable; urgency=low
+
+  * Re-worked the build dependency computation
+
+ -- David Fox <dsf@seereason.com>  Thu, 22 May 2008 10:59:22 -0700
+
+haskell-debian (3.0) unstable; urgency=low
+
+  * Re-organization of module heirarchy.
+
+ -- David Fox <dsf@seereason.com>  Mon, 19 May 2008 12:47:25 -0700
+
+haskell-debian (2.28) unstable; urgency=low
+
+  * Eliminate use of haskell-ugly library.
+
+ -- David Fox <dsf@seereason.com>  Wed, 14 May 2008 12:30:40 -0700
+
+haskell-debian (2.27) unstable; urgency=low
+
+  * Changes for switch to lazy bytestrings in haskell-unixutils.
+
+ -- David Fox <dsf@seereason.com>  Tue, 06 May 2008 05:52:51 -0700
+
+haskell-debian (2.26) unstable; urgency=low
+
+  * Improve error report from "Missing control file or changelog"
+
+ -- David Fox <dsf@seereason.com>  Mon, 05 May 2008 05:59:27 -0700
+
+haskell-debian (2.25) unstable; urgency=low
+
+  * Packaging changes for haskell-devscripts 0.6.10.
+
+ -- David Fox <dsf@seereason.com>  Sat, 29 Mar 2008 10:25:54 -0700
+
+haskell-debian (2.24) unstable; urgency=low
+
+  * New version of dupload reads both /etc/dupload.conf and ~/.dupload.conf, so
+    we have to explicitly unset $preupload in ~/.dupload.conf.
+
+ -- David Fox <dsf@seereason.com>  Tue, 25 Mar 2008 05:49:08 -0700
+
+haskell-debian (2.23) unstable; urgency=low
+
+  * Fix a divide by zero error in Debian.Shell.  This should also improve
+    the behavior of the code that outputs one dot per 128 characters of
+    shell command output.
+
+ -- David Fox <dsf@seereason.com>  Wed, 12 Mar 2008 16:55:59 +0000
+
+haskell-debian (2.22) unstable; urgency=low
+
+  * Add a chars/dot argument to Shell.dotOutput
+  * Moved some functions from Shell to haskell-unixutils
+  * Moved TIO module to haskell-extra
+
+ -- David Fox <dsf@seereason.com>  Sun, 02 Mar 2008 10:14:13 -0800
+
+haskell-debian (2.21) unstable; urgency=low
+
+  * Change some writeFile calls to avoid lazyness in evaluating the
+    second argument, which appears to lead to locked file errors.
+
+ -- David Fox <dsf@seereason.com>  Sun, 24 Feb 2008 11:06:53 -0800
+
+haskell-debian (2.20) unstable; urgency=low
+
+  * Message Improvements
+  * Discard duplicate dependency relations
+  * Fix rfc822DateFormat
+
+ -- Jeremy Shaw <jeremy@n-heptane.com>  Wed, 20 Feb 2008 13:34:34 -0800
+
+haskell-debian (2.19) unstable; urgency=low
+
+  * Added more functions for working with index files
+
+ -- Jeremy Shaw <jeremy@n-heptane.com>  Tue, 19 Feb 2008 16:07:46 -0800
+
+haskell-debian (2.18) unstable; urgency=low
+
+  * Hack: Debian.Local.Insert.addPackagesToIndexes work-around for optimizer bug
+  * Debian.Package: use controlFromIndex instead of calling zcat
+
+ -- Jeremy Shaw <jeremy@n-heptane.com>  Mon, 11 Feb 2008 23:08:30 -0800
+
+haskell-debian (2.17) unstable; urgency=low
+
+  * TIO module fixes and cleanups.
+
+ -- David Fox <dsf@seereason.com>  Thu, 07 Feb 2008 05:45:00 -0800
+
+haskell-debian (2.16) unstable; urgency=low
+
+  * Add setRepoMap to install cached repository info
+  * Print more info about what happened when a repository appears not to exist.
+
+ -- David Fox <ddssff@gmail.com>  Wed, 06 Feb 2008 16:00:45 -0800
+
+haskell-debian (2.15) unstable; urgency=low
+
+  * Fix bug in Debian.VersionPolicy
+  * Split a simple TIO monad out of the AptIO monad.
+  * Simplify Repository type, eliminate parameterized Release etc.
+  * Improve type safety of the SourcesList related types
+
+ -- David Fox <ddssff@gmail.com>  Wed, 06 Feb 2008 05:38:12 -0800
+
+haskell-debian (2.14) unstable; urgency=low
+
+  * Rewrite of Debian.VersionPolicy.
+  * Run unit tests during build
+
+ -- David Fox <ddssff@gmail.com>  Mon, 28 Jan 2008 13:07:00 -0800
+
+haskell-debian (2.13) unstable; urgency=low
+
+  * Improvements in code currently used to compute the build dependencies.
+    This allows builds of packages which previously caused an combinatoric
+    explosion in memory and time use.  The specific modifications are to
+    avoid making a huge list of all the solution candidates that failed,
+    and to put the relations into a normal form which only involves equals
+    dependencies on packages that are actually available for installation.
+    Finally, a bug in handling of architecture specific dependencies was
+    fixed which might have been causing the extremely long and fruitless
+    searches for some packages' build dependencies.
+
+ -- David Fox <ddssff@gmail.com>  Sat, 19 Jan 2008 19:28:32 +0000
+
+haskell-debian (2.12) unstable; urgency=low
+
+  * Add Debian.Apt.Dependecies and Debian.Apt.Package to debian.cabal
+
+ -- Jeremy Shaw <jeremy.shaw@linspireinc.com>  Fri, 18 Jan 2008 17:13:24 -0800
+
+haskell-debian (2.11) unstable; urgency=low
+
+  * Added trump detector
+  * Added code to find parents and siblings of a binary package from the
+    Packages/Sources files
+  * Packaging updates
+
+ -- Jeremy Shaw <jeremy.shaw@linspireinc.com>  Fri, 14 Dec 2007 13:55:20 -0800
+
+haskell-debian (2.10) unstable; urgency=low
+
+  * Added new interface, Apt.Debian.Methods.fetch which allows the UI
+    portion of fetching (status, authentication), to be controlled by
+    providing a set of callback functions.
+
+ -- Jeremy Shaw <jeremy.shaw@linspireinc.com>  Tue, 20 Nov 2007 14:07:43 -0800
+
+haskell-debian (2.9) unstable; urgency=low
+
+  * Add caching of loaded package indexes based on the path and the
+    file status of the cached index file.  Also splits Debian.Types
+    into several modules.
+
+ -- David Fox <dsf@seereason.org>  Fri,  9 Nov 2007 11:05:11 -0800
+
+haskell-debian (2.8) unstable; urgency=low
+
+  * Last version had bogus dependencies due to an unknown build error.
+    Make loading of package indexes less lazy in an attempt to reduce
+    memory usage.
+
+ -- David Fox <dsf@seereason.org>  Wed,  7 Nov 2007 10:54:27 -0800
+
+haskell-debian (2.7) unstable; urgency=low
+
+  * Make loading of package indexes lazy.
+
+ -- David Fox <dsf@seereason.org>  Mon, 22 Oct 2007 11:11:34 -0700
+
+haskell-debian (2.6) unstable; urgency=low
+
+  * Pass --immediate-configure-false to build-env so we can create
+    environments for gutsy, lenny, and sid.
+
+ -- David Fox <dsf@seereason.org>  Sat, 20 Oct 2007 16:17:59 -0700
+
+haskell-debian (2.5) unstable; urgency=low
+
+  * Reduce amount of apt-get updating that occurs.
+
+ -- David Fox <ddssff@gmail.com>  Sat, 20 Oct 2007 13:50:25 +0000
+
+haskell-debian (2.4) unstable; urgency=low
+
+  * Fix parsing of version tags in VersionPolicy.  It was always failing
+    and therefore not understanding versions we had generated.
+
+ -- David Fox <ddssff@gmail.com>  Sat, 13 Oct 2007 04:44:39 -0700
+
+haskell-debian (2.3) unstable; urgency=low
+
+  * The EnvPath and EnvRoot types had show methods that were not
+    invertable by read.  Now they use deriving Show, and use rootPath
+    and the new outsidePath to convert EnvRoot and EnvPath to the
+    FilePath type.  This is a big looking change, but safe.
+  * Replace code that looked at the "Package" and "Version" fields
+    of a parsed control file with calls to packageName and
+    packageVersion, which just returns values already computed and
+    saved in the Package object.
+  * Use EnvPath instead of FilePath in places where it makes sense, such
+    as the copyDebianBuildTree and other places in Debian.SourceTree.
+    This change propagated down in various places, and the cutoff may be
+    a little out of whack in some places, but it is all typesafe (and
+    therefore wonderful?)
+
+ -- David Fox <ddssff@gmail.com>  Thu, 11 Oct 2007 15:43:03 +0000
+
+haskell-debian (2.2) unstable; urgency=low
+
+  * Fix a bug in parsing of dependency relations when there is
+    whitespace after a right square brace.
+
+ -- David Fox <ddssff@gmail.com>  Tue,  9 Oct 2007 21:00:24 +0000
+
+haskell-debian (2.1) unstable; urgency=low
+
+  * Fix show method of SliceList, the elements need to be
+    terminated by newlines.
+
+ -- David Fox <ddssff@gmail.com>  Fri,  5 Oct 2007 00:11:33 -0700
+
+haskell-debian (2.0) unstable; urgency=low
+
+  * Change Apt. to Debian.
+  * Added Debian.Apt.Methods
+  * Added Debian.Deb
+  * Added Debian.Time
+
+ -- Jeremy Shaw <jeremy.shaw@linspire.com>  Wed, 19 Sep 2007 15:14:10 -0700
+
+haskell-apt (1.0) unstable; urgency=low
+
+  * Initial Debian package.
+
+ -- David Fox <ddssff@gmail.com>  Tue, 18 Sep 2007 09:33:24 -0700
diff --git a/debian/compat b/debian/compat
new file mode 100644
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1,1 @@
+7
diff --git a/debian/control b/debian/control
new file mode 100644
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,135 @@
+Source: haskell-debian
+Section: haskell
+Priority: extra
+Maintainer: Debian Haskell Group <pkg-haskell-maintainers@lists.alioth.debian.org>
+Uploaders: Joachim Breitner <nomeata@debian.org>
+Build-Depends: debhelper (>= 7)
+  , cdbs
+  , haskell-devscripts (>= 0.7)
+  , ghc
+  , ghc-prof
+  , libghc-mtl-dev
+  , libghc-mtl-prof
+  , libghc-parsec3-dev
+  , libghc-parsec3-prof
+  , libghc-regex-compat-dev
+  , libghc-regex-compat-prof
+  , libghc-regex-tdfa-dev (>= 1.1.3)
+  , libghc-regex-tdfa-prof
+  , libghc-bzlib-dev (>= 0.5.0.0-4)
+  , libghc-bzlib-prof
+  , libghc-haxml-prof (>= 1:1.20)
+  , libghc-unixutils-dev (>= 1.41)
+  , libghc-unixutils-prof (>= 1.41)
+  , libghc-zlib-dev
+  , libghc-zlib-prof
+  , libghc-network-dev
+  , libghc-network-prof
+  , libghc-utf8-string-dev
+  , libghc-utf8-string-prof,
+  , libcrypto++-dev
+Build-Depends-Indep: ghc-doc
+  , libghc-mtl-doc
+  , libghc-parsec3-doc
+  , libghc-regex-compat-doc
+  , libghc-regex-tdfa-doc
+  , libghc-bzlib-doc
+  , libghc-haxml-doc (>= 1:1.20)
+  , libghc-unixutils-doc (>= 1.41)
+  , libghc-zlib-doc
+  , libghc-network-doc
+  , libghc-utf8-string-doc
+Build-Conflicts:
+  libghc-parsec2-dev
+Standards-Version: 3.9.2
+Homepage: http://hackage.haskell.org/package/debian
+Vcs-Darcs: http://darcs.debian.org/pkg-haskell/haskell-debian
+Vcs-Browser: http://darcs.debian.org/cgi-bin/darcsweb.cgi?r=pkg-haskell/haskell-debian
+
+Package: libghc-debian-dev
+Architecture: any
+Depends: ${haskell:Depends}
+  , ${shlibs:Depends}
+  , ${misc:Depends}
+Recommends: ${haskell:Recommends}
+Suggests: ${haskell:Suggests}
+Provides: ${haskell:Provides}
+Description: Haskell library for working with the Debian package system
+ This package provides a library for the Haskell programming language.
+ See http://www.haskell.org/ for more information on Haskell.
+ .
+ This library includes modules covering almost every aspect of the Debian
+ packaging system, including low level data types such as version numbers
+ and dependency relations, on up to the types necessary for computing and
+ installing build dependencies, building source and binary packages,
+ and inserting them into a repository.
+ .
+ This package contains the libraries compiled for GHC 6.
+
+Package: libghc-debian-prof
+Architecture: any
+Depends: ${haskell:Depends}
+  , ${shlibs:Depends}
+  , ${misc:Depends}
+Recommends: ${haskell:Recommends}
+Suggests: ${haskell:Suggests}
+Provides: ${haskell:Provides}
+Description: Profiling library for working with the Debian package system
+ This package provides a library for the Haskell programming language,
+ compiled for profiling.
+ See http://www.haskell.org/ for more information on Haskell.
+ .
+ This library includes modules covering almost every aspect of the Debian
+ packaging system, including low level data types such as version numbers
+ and dependency relations, on up to the types necessary for computing and
+ installing build dependencies, building source and binary packages,
+ and inserting them into a repository.
+ .
+ This package contains the profiling libraries compiled for GHC 6.
+
+Package: libghc-debian-doc
+Section: doc
+Architecture: all
+Depends: ${misc:Depends}, ${haskell:Depends}
+Recommends: ${haskell:Recommends}
+Suggests: ${haskell:Suggests}
+Description: Documentation for Debian package system library
+ This package provides the documentation for a library for the Haskell
+ programming language.
+ See http://www.haskell.org/ for more information on Haskell.
+ .
+ This library includes modules covering almost every aspect of the Debian
+ packaging system, including low level data types such as version numbers
+ and dependency relations, on up to the types necessary for computing and
+ installing build dependencies, building source and binary packages,
+ and inserting them into a repository.
+ .
+ This package contains the library documentation.
+
+Package: haskell-debian-utils
+Section: devel
+Architecture: any
+Depends: ghc, ${misc:Depends}, ${shlibs:Depends}
+Recommends: apt-file
+Description: Various helpers to work with Debian packages
+ This package contains tools shipped with the Haskell library “debian”:
+ .
+   * fakechanges:
+     Sometimes you have the .debs, .dsc, .tar.gz, .diff.gz, etc from a package
+     build, but not the .changes file. This package lets you create a fake
+     .changes file in case you need one.
+ .
+   * debian-report:
+     Analyze Debian repositories and generate reports about their contents and
+     relations. For example, a list of all packages in a distribution that are
+     trumped by another distribution.
+ .
+   * cabal-debian:
+     Tool for creating debianizations of Haskell packages based on the .cabal
+     file.  If apt-file is installed it will use it to discover what is the
+     debian package name of a C library.
+ .
+   * apt-get-build-depends:
+     Tool which will parse the Build-Depends{-Indep} lines from debian/control
+     and apt-get install the required packages
+
diff --git a/debian/copyright b/debian/copyright
--- a/debian/copyright
+++ b/debian/copyright
@@ -1,6 +1,11 @@
 This package was debianized by David Fox
 <dsf@seereason.com> on September 18, 2007.
 
+The packageing was adjusted to Debian conventions by Joachim Breitner
+<nomeata@debian.org> on Sat, 01 May 2010 21:16:18 +0200, and is licenced under
+the same terms as the package itself..
+
+
 Copyright (c) 2007, David Fox
 Copyright (c) 2007, Jeremy Shaw
 
diff --git a/debian/debian-report.1 b/debian/debian-report.1
new file mode 100644
--- /dev/null
+++ b/debian/debian-report.1
@@ -0,0 +1,20 @@
+.\"Original page generated by txt2man and then hacked extensively.
+.TH DEBIAN-REPORT 1  "May 10, 2010"
+
+.SH NAME
+debian-report \- report differences in packages referenced by two sources.list
+files.
+
+.SH SYNOPSIS
+.B debian-report
+.RI "<old sources.list> <new sources.list>"
+
+.SH DESCRIPTION
+debian-report is given two Debain sources.list files as arguments and will
+find all the packages referenced by the second which trump packages found in
+the first.
+
+.SH AUTHOR
+This manual page was originally written by Erik de Castro Lopo 
+<erikd@mega-nerd.com> for the Debian GNU/Linux system (but may be used by 
+others).
diff --git a/debian/fakechanges.1 b/debian/fakechanges.1
new file mode 100644
--- /dev/null
+++ b/debian/fakechanges.1
@@ -0,0 +1,17 @@
+.TH FAKECHANGES 1  "May 10, 2010"
+
+.SH NAME
+fakechanges \- reverse engineer a Debian .changes file.
+
+.SH SYNOPSIS
+.B fakechanges
+.RI "[OPTION]  files..."
+
+.SH DESCRIPTION
+fakechanges can reverse engineer the .changes file from the .debs, .dsc,
+ .tar.gz, .diff.gz, etc from a package build.
+
+.SH AUTHOR
+This manual page was originally written by Erik de Castro Lopo 
+<erikd@mega-nerd.com> for the Debian GNU/Linux system (but may be used by 
+others).
diff --git a/debian/haskell-debian-utils.install b/debian/haskell-debian-utils.install
new file mode 100644
--- /dev/null
+++ b/debian/haskell-debian-utils.install
@@ -0,0 +1,3 @@
+dist-ghc/build/apt-get-build-depends/apt-get-build-depends		usr/bin/
+dist-ghc/build/debian-report/debian-report						usr/bin/
+dist-ghc/build/fakechanges/fakechanges							usr/bin/
diff --git a/debian/haskell-debian-utils.manpages b/debian/haskell-debian-utils.manpages
new file mode 100644
--- /dev/null
+++ b/debian/haskell-debian-utils.manpages
@@ -0,0 +1,1 @@
+debian/*.1
diff --git a/debian/libghc-debian-doc.doc-base b/debian/libghc-debian-doc.doc-base
new file mode 100644
--- /dev/null
+++ b/debian/libghc-debian-doc.doc-base
@@ -0,0 +1,13 @@
+Document: libghc-debian-doc
+Title: Manual for the Haskell Debian library
+Abstract:  This library includes modules covering almost every aspect of the
+ Debian packaging system, including low level data types such as version
+ numbers and dependency relations, on up to the types necessary for computing
+ and installing build dependencies, building source and binary packages,
+ and inserting them into a repository.
+Section: Programming
+
+Format: HTML
+Index: /usr/share/doc/libghc-debian-doc/html/doc-index.html
+Files: /usr/share/doc/libghc-debian-doc/html/*.html
+ /usr/share/doc/libghc-debian-doc/html/src/*.html
diff --git a/debian/patches/dont-build-tests.patch b/debian/patches/dont-build-tests.patch
new file mode 100644
--- /dev/null
+++ b/debian/patches/dont-build-tests.patch
@@ -0,0 +1,26 @@
+Index: debian-3.55/debian.cabal
+===================================================================
+--- debian-3.55.orig/debian.cabal	2011-06-03 21:02:01.000000000 -0300
++++ debian-3.55/debian.cabal	2011-06-03 21:03:43.000000000 -0300
+@@ -22,7 +22,7 @@
+ Library
+  Build-Depends:  base >= 4 && < 5, bytestring, containers, directory,
+                  filepath, mtl, network, old-locale, parsec >= 2 && <4, pretty, process,
+-                 regex-tdfa, regex-compat, time, unix, bzlib, HaXml == 1.20.*, Unixutils >= 1.32, zlib, HUnit,
++                 regex-tdfa, regex-compat, time, unix, bzlib, HaXml == 1.20.*, Unixutils >= 1.32, zlib,
+                  utf8-string
+  ghc-options: -W -Wall
+  if flag(cabal19)
+@@ -65,11 +65,7 @@
+         Distribution.Package.Debian.Bundled,
+         Distribution.Package.Debian.Setup,
+         Distribution.Package.Debian.Main,
+-        Distribution.Package.Debian,
+-        Test.Changes,
+-        Test.Dependencies,
+-        Test.SourcesList,
+-        Test.Versions
++        Distribution.Package.Debian
+ 
+ Executable fakechanges
+  Main-is: utils/FakeChanges.hs
diff --git a/debian/patches/series b/debian/patches/series
new file mode 100644
--- /dev/null
+++ b/debian/patches/series
@@ -0,0 +1,1 @@
+dont-build-tests.patch
diff --git a/debian/rules b/debian/rules
new file mode 100644
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,8 @@
+#!/usr/bin/make -f
+
+DEB_BUILD_DEPENDENCIES = build-arch
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+include /usr/share/cdbs/1/class/hlibrary.mk
+
+
diff --git a/debian/watch b/debian/watch
new file mode 100644
--- /dev/null
+++ b/debian/watch
@@ -0,0 +1,5 @@
+version=3
+opts="downloadurlmangle=s|archive/([\w\d_-]+)/([\d\.]+)/|archive/$1/$2/$1-$2.tar.gz|,\
+filenamemangle=s|(.*)/$|debian-$1.tar.gz|" \
+    http://hackage.haskell.org/packages/archive/debian \
+    ([\d\.]*\d)/
diff --git a/utils/CabalDebian.hs b/utils/CabalDebian.hs
deleted file mode 100644
--- a/utils/CabalDebian.hs
+++ /dev/null
@@ -1,20 +0,0 @@
--- |
--- Module      :  CabalDebian
--- Copyright   :  David Fox 2008
---
--- Maintainer  :  David Fox <dsf@seereason.com>
--- Stability   :  alpha
--- Portability :  portable
---
--- Explanation: Main entry point for generating Debianizations from Cabal data.
-
--- This software may be used and distributed according to the terms of
--- the GNU General Public License, incorporated herein by reference.
-
-module Main where
-
-import qualified Distribution.Package.Debian.Main as Debian
-
-main :: IO ()
-
-main = Debian.main
