diff --git a/HSCurses/CWString.hsc b/HSCurses/CWString.hsc
deleted file mode 100644
--- a/HSCurses/CWString.hsc
+++ /dev/null
@@ -1,388 +0,0 @@
---
--- Copyright (c) 2002-2004 John Meacham (john at repetae dot net)
--- Copyright (c) 2004      Don Stewart - http://www.cse.unsw.edu.au/~dons
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-
-module HSCurses.CWString (
-
-    -- * utf8 versions
-    withUTF8String,
-    withUTF8StringLen,
-    newUTF8String,
-    newUTF8StringLen,
-    peekUTF8String,
-    peekUTF8StringLen,
-
-    -- * WChar stuff
-#ifdef HAVE_WCHAR_H
-    withCWString,
-    withCWStringLen,
-    newCWString,
-    newCWStringLen,
-    peekCWString,
-    peekCWStringLen,
-    wcharIsUnicode,
-    CWChar, 
-    CWString, 
-    CWStringLen,
-#endif
-    -- * Locale versions 
-    withLCString,
-    withLCStringLen,
-    newLCString,
-    newLCStringLen,
-    peekLCStringLen,
-    peekLCString,
---  charIsRepresentable
-
-    ) where
-
-import Data.Char            ( ord, chr )
-import Data.Bits            ( Bits((.|.), (.&.), shift) )
-import Foreign.C.String
-
-#if __GLASGOW_HASKELL__ < 603
-import GHC.Exts
-#endif
-
-#ifdef HAVE_WCHAR_H
-
-import Foreign.C.Types
-
-#include <wchar.h>
-#include <limits.h>
-#include <stdlib.h>
-
-type CWChar = (#type wchar_t)
-type CWString = Ptr CWChar
-type CWStringLen = (CWString, Int)
-
-fi :: (Integral a, Num b) => a -> b
-fi x = fromIntegral x
-
--------------------
--- CWChar functions
--------------------
-
-{-# INLINE wcharIsUnicode #-}
-wcharIsUnicode :: Bool
-
-#if defined(__STDC_ISO_10646__)
-
-wcharIsUnicode = True
-
--- support functions 
-wNUL :: CWChar
-wNUL = 0
-#ifndef __GLASGOW_HASKELL__
-pairLength :: String -> CString -> CStringLen
-pairLength  = flip (,) . length
-
-cwCharsToChars :: [CWChar] -> [Char]
-cwCharsToChars xs  = map castCWCharToChar xs
-charsToCWChars :: [Char] -> [CWChar]
-charsToCWChars xs  = map castCharToCWChar xs
-
-#endif
--- __STDC_ISO_10646__
-
-castCWCharToChar :: CWChar -> Char
-castCWCharToChar ch = chr (fromIntegral ch )
-
-castCharToCWChar :: Char -> CWChar
-castCharToCWChar ch = fromIntegral (ord ch)
-
--- exported functions
-peekCWString    :: CWString -> IO String
-#ifndef __GLASGOW_HASKELL__
-peekCString cp  = do cs <- peekArray0 wNUL cp; return (cwCharsToChars cs)
-#else
-peekCWString cp = loop 0
-  where
-    loop i = do
-        val <- peekElemOff cp i
-        if val == wNUL then return [] else do
-            rest <- loop (i+1)
-            return (castCWCharToChar val : rest)
-#endif
-
-peekCWStringLen           :: CWStringLen -> IO String
-#ifndef __GLASGOW_HASKELL__
-peekCWStringLen (cp, len)  = do cs <- peekArray len cp; return (cwCharsToChars cs)
-#else
-peekCWStringLen (cp, len) = loop 0
-  where
-    loop i | i == len  = return []
-           | otherwise = do
-                val <- peekElemOff cp i
-                rest <- loop (i+1)
-                return (castCWCharToChar val : rest)
-#endif
-
-newCWString :: String -> IO CWString
-#ifndef __GLASGOW_HASKELL__
-newCWString  = newArray0 wNUL . charsToCWChars
-#else
-newCWString str = do
-  ptr <- mallocArray0 (length str)
-  let
-        go [] n##   = pokeElemOff ptr (I## n##) wNUL
-        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
-  go str 0##
-  return ptr
-#endif
-
-newCWStringLen     :: String -> IO CWStringLen
-#ifndef __GLASGOW_HASKELL__
-newCWStringLen str  = do a <- newArray (charsToCWChars str)
-                        return (pairLength str a)
-#else
-newCWStringLen str = do
-  ptr <- mallocArray0 len
-  let
-        go [] _       = return ()
-        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
-  go str 0##
-  return (ptr, len)
-  where
-    len = length str
-#endif
-
-withCWString :: String -> (CWString -> IO a) -> IO a
-#ifndef __GLASGOW_HASKELL__
-withCWString  = withArray0 wNUL . charsToCWChars
-#else
-withCWString str f =
-  allocaArray0 (length str) $ \ptr ->
-      let
-        go [] n##     = pokeElemOff ptr (I## n##) wNUL
-        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
-      in do
-      go str 0##
-      f ptr
-#endif
-
-withCWStringLen         :: String -> (CWStringLen -> IO a) -> IO a
-#ifndef __GLASGOW_HASKELL__
-withCWStringLen str act  = withArray (charsToCWChars str) $ act . pairLength str
-#else
-withCWStringLen str f =
-  allocaArray len $ \ptr ->
-      let
-        go [] _       = return ()
-        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
-      in do
-      go str 0##
-      f (ptr,len)
-  where
-    len = length str
-#endif
-
-
-#else
--- no __STDC_ISO_10646__
-wcharIsUnicode = False
-#endif
-
-newtype MBState = MBState { _mbstate :: (Ptr MBState)}
-
-withMBState :: (MBState -> IO a) -> IO a
-withMBState act = allocaBytes (#const sizeof(mbstate_t)) (\mb -> c_memset mb 0 (#const sizeof(mbstate_t)) >> act (MBState mb)) 
-
-clearMBState :: MBState -> IO ()
-clearMBState (MBState mb) = c_memset mb 0 (#const sizeof(mbstate_t)) >> return ()
-
-wcsrtombs :: CWString -> (CString, CSize) -> IO CSize
-wcsrtombs wcs (cs,len) = 
-    alloca (\p -> 
-        poke p wcs >> withMBState (\mb -> 
-            wcsrtombs' p cs len mb)) 
-    where
-        wcsrtombs'  p cs' len' mb = do
-            x <- c_wcsrtombs cs p len' mb
-            case x of 
-                -1 -> do
-                    sp <- peek p 
-                    poke sp ((fi (ord '?'))::CWChar)
-                    poke p wcs
-                    clearMBState mb
-                    wcsrtombs' p cs' len' mb
-                e | e >= 0 && e <= len' -> do
-                    let ep = advancePtr cs' (fi e)
-                    poke ep (fi (0::Int))
-                    return x
-                e -> error $ "HSCurses.CWString.wcsrtombs: impossible case: "++show e
-
-#def inline HsInt hs_get_mb_cur_max () { return MB_CUR_MAX; }
-foreign import ccall unsafe hs_get_mb_cur_max :: IO Int 
-
-mb_cur_max :: Int
-mb_cur_max = unsafePerformIO hs_get_mb_cur_max 
-
-{-
-charIsRepresentable :: Char -> IO Bool
-charIsRepresentable ch = fmap (/= -1) $ allocaBytes mb_cur_max (\cs -> c_wctomb cs (fi $ ord ch)) 
--}
-
-{-
-foreign import ccall unsafe "stdlib.h wctomb" c_wctomb :: CString -> CWChar -> IO CInt
--}
-
-foreign import ccall unsafe "stdlib.h wcsrtombs" 
-        c_wcsrtombs :: CString -> (Ptr (Ptr CWChar)) -> CSize -> MBState -> IO CSize
-
-foreign import ccall unsafe "string.h memset" 
-        c_memset :: Ptr a -> CInt -> CSize -> IO (Ptr a)
-
-foreign import ccall unsafe "stdlib.h mbstowcs" 
-        c_mbstowcs :: CWString -> CString -> CSize -> IO CSize
-
-mbstowcs :: CWString
-         -> Foreign.C.String.CString
-         -> Foreign.C.Types.CSize -> IO Foreign.C.Types.CSize
-
-mbstowcs a b s = throwIf (== -1) (const "mbstowcs") $ c_mbstowcs a b s 
-
-peekLCString    :: CString -> IO String
-peekLCString cp  = do 
-    sz <- mbstowcs nullPtr cp 0
-    allocaArray (fi $ sz + 1) (\wcp -> mbstowcs wcp cp (sz + 1) >> peekCWString wcp)
-
--- TODO fix for embeded NULs
-peekLCStringLen           :: CStringLen -> IO String
-peekLCStringLen (cp, len)  =  allocaBytes (len + 1) $ \ncp -> do
-    copyBytes ncp cp len
-    pokeElemOff ncp len 0
-    peekLCString ncp
-    
-newLCString :: String -> IO CString
-newLCString s = 
-    withCWString s $ \wcs -> do 
-        cs <- mallocArray0 alen
-        wcsrtombs wcs (cs, fi alen)
-        return cs 
-
-    where alen = mb_cur_max * length s
-
-newLCStringLen     :: String -> IO CStringLen
-newLCStringLen str  = newLCString str >>= \cs -> return (pairLength1 str cs)
-
-withLCString :: String -> (CString -> IO a) -> IO a
-withLCString s a = 
-    withCWString s $ \wcs -> 
-        allocaArray0 alen $ \cs -> 
-            wcsrtombs wcs (cs,fi alen) >> a cs
-
-    where alen = mb_cur_max * length s
-
-withLCStringLen :: String -> (CStringLen -> IO a) -> IO a
-withLCStringLen s a = 
-    withCWString s $ \wcs -> 
-        allocaArray0 alen $ \cs -> do
-            sz <- wcsrtombs wcs (cs,fi alen)
-            a (cs,fi sz)
-
-    where alen = mb_cur_max * length s
-
-pairLength1 :: String -> CString -> CStringLen
-pairLength1  = flip (,) . length
-
-#else
--- -----------------------------------------------------------
--- no CF_WCHAR_SUPPORT (OpenBSD)
-
-{-
-charIsRepresentable :: Char -> IO Bool
-charIsRepresentable ch = return $ isLatin1 ch
--}
-
-withLCString :: String -> (Foreign.C.String.CString -> IO a) -> IO a
-withLCString = withCString
-
-withLCStringLen  :: String -> (Foreign.C.String.CStringLen -> IO a) -> IO a
-withLCStringLen = withCStringLen
-
-newLCString :: String -> IO Foreign.C.String.CString
-newLCString = newCString
-
-newLCStringLen :: String -> IO Foreign.C.String.CStringLen
-newLCStringLen = newCStringLen
-
-peekLCString :: Foreign.C.String.CString -> IO String
-peekLCString = peekCString
-
-peekLCStringLen :: Foreign.C.String.CStringLen -> IO String
-peekLCStringLen = peekCStringLen
-
-#endif
--- no CF_WCHAR_SUPPORT
-
------------------
--- UTF8 versions
------------------
-
-withUTF8String :: String -> (CString -> IO a) -> IO a
-withUTF8String hsStr = withCString (toUTF hsStr)
-
-withUTF8StringLen :: String -> (CStringLen -> IO a) -> IO a
-withUTF8StringLen hsStr = withCStringLen (toUTF hsStr)
-
-newUTF8String :: String -> IO CString
-newUTF8String = newCString . toUTF
-
-newUTF8StringLen :: String -> IO CStringLen
-newUTF8StringLen = newCStringLen . toUTF
-
-peekUTF8String :: CString -> IO String
-peekUTF8String strPtr = fmap fromUTF $ peekCString strPtr
-
-peekUTF8StringLen :: CStringLen -> IO String
-peekUTF8StringLen strPtr = fmap fromUTF $ peekCStringLen strPtr
-
--- these should read and write directly from/to memory.
--- A first pass will be needed to determine the size of the allocated region
-
-toUTF :: String -> String
-toUTF [] = []
-toUTF (x:xs) | ord x<=0x007F = x:toUTF xs
-             | ord x<=0x07FF = chr (0xC0 .|. ((ord x `shift` (-6)) .&. 0x1F)):
-                               chr (0x80 .|. (ord x .&. 0x3F)):
-                               toUTF xs
-             | otherwise     = chr (0xE0 .|. ((ord x `shift` (-12)) .&. 0x0F)):
-                               chr (0x80 .|. ((ord x `shift` (-6)) .&. 0x3F)):
-                               chr (0x80 .|. (ord x .&. 0x3F)):
-                               toUTF xs
-
-fromUTF :: String -> String
-fromUTF [] = []
-fromUTF (al@(x:xs)) | ord x<=0x7F = x:fromUTF xs
-                     | ord x<=0xBF = err
-                     | ord x<=0xDF = twoBytes al
-                     | ord x<=0xEF = threeBytes al
-                     | otherwise   = err
-  where
-    twoBytes (x1:x2:xs') = chr (((ord x1 .&. 0x1F) `shift` 6) .|.
-                               (ord x2 .&. 0x3F)):fromUTF xs'
-    twoBytes _ = error "fromUTF: illegal two byte sequence"
-
-    threeBytes (x1:x2:x3:xs') = chr (((ord x1 .&. 0x0F) `shift` 12) .|.
-                                    ((ord x2 .&. 0x3F) `shift` 6) .|.
-                                    (ord x3 .&. 0x3F)):fromUTF xs'
-    threeBytes _ = error "fromUTF: illegal three byte sequence" 
-    
-    err = error "fromUTF: illegal UTF-8 character"
-
diff --git a/HSCurses/Curses.hsc b/HSCurses/Curses.hsc
deleted file mode 100644
--- a/HSCurses/Curses.hsc
+++ /dev/null
@@ -1,1403 +0,0 @@
-{-# OPTIONS -fffi -fglasgow-exts #-}
--- glaexts needed for newtype deriving 
-
--- Copyright (c) 2002-2004 John Meacham (john at repetae dot net)
--- Copyright (c) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
--- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-
-
---
--- | Binding to the [wn]curses library. From the ncurses man page:
---
--- >      The curses library routines give the user a terminal-inde-
--- >      pendent method of updating character screens with  reason-
--- >      able  optimization.
--- 
--- Sections of the quoted documentation are from the OpenBSD man pages, which
--- are distributed under a BSD license.
---
--- A useful reference is: 
---        /Writing Programs with NCURSES/, by Eric S. Raymond and Zeyd
---        M. Ben-Halim, <http://dickey.his.com/ncurses/>
---
--- N.B attrs don't work with Irix curses.h. This should be fixed.
---
-
-module HSCurses.Curses (
-
-    -- * Basic Functions
-    stdScr,             -- :: Window
-    initScr,            -- :: IO Window
-    initCurses,         -- :: IO ()
-    resetParams,
-    endWin,             -- :: IO ()
-    scrSize,            -- :: IO (Int, Int)
-
-    -- * Windows and Pads
-    Window,             -- data Window deriving Eq
-    touchWin,
-    newPad, pRefresh, delWin, newWin,
-
-    -- * Refresh Routines
-    refresh,            -- :: IO ()
-    update,
-    resizeTerminal,
-
-    -- * Navigation
-    move,           -- :: Int -> Int -> IO ()
-    getYX,    
-    
-    -- * Input 
-    getCh, getch, decodeKey, ungetCh, keyResizeCode,
-
-    -- * Input Options
-    cBreak,             -- :: Bool -> IO ()
-    raw,                -- :: Bool -> IO ()
-    echo,               -- :: Bool -> IO ()
-    intrFlush,          -- :: Bool -> IO ()
-    keypad,             -- :: Window -> Bool -> IO ()
-    noDelay,            -- :: Window -> Bool -> IO ()
-
-    -- * Output
-    wAddStr, 
-    addLn,         -- :: IO ()
-    mvWAddStr,
-    wMove,
-    bkgrndSet,      -- :: Attr -> Pair -> IO ()
-    erase,          -- :: IO ()
-    wclear,         -- :: Window -> IO ()
-    clrToEol,       -- :: IO ()
-    wClrToEol,
-    beep,
-    waddch, 
-
-    -- * Output Options    
-    clearOk,
-    leaveOk,
-    nl,                 -- :: Bool -> IO ()
-
-    -- * Cursor Routines
-    CursorVisibility(..), cursSet,
-    
-    -- * Color Support
-    hasColors,      -- :: IO Bool
-    startColor,     -- :: IO ()
-    useDefaultColors,   -- :: IO ()
-    Pair(..),       -- newtype Pair = Pair Int deriving (Eq, Ord, Ix)
-    colorPairs,     -- :: IO Int
-    Color(..),      -- newtype Color = Color Int deriving (Eq, Ord, Ix)
-    colors,         -- :: IO Int
-    color,          -- :: String -> Maybe Color
---    black, red, green, yellow, blue, magenta, cyan, white, -- :: Color
-    initPair,       -- :: Pair -> Color -> Color -> IO ()
-    pairContent,    -- :: Pair -> IO (Color, Color)
-    canChangeColor, -- :: IO Bool
-    initColor,      -- :: Color -> (Int, Int, Int) -> IO ()
-    colorContent,   -- :: Color -> IO (Int, Int, Int)
-    defaultBackground, defaultForeground,
-    
-    -- * Attributes
-    attrPlus,
-    Attr,  
-    attr0, -- :: Attr
-    
-    isAltCharset, isBlink, isBold, isDim, isHorizontal, isInvis,
-    isLeft, isLow, isProtect, isReverse, isRight, isStandout, isTop,
-    isUnderline, isVertical,
-        -- :: Attr -> Bool
-    
-    setAltCharset, setBlink, setBold, setDim, setHorizontal, setInvis,
-    setLeft, setLow, setProtect, setReverse, setRight, setStandout,
-    setTop, setUnderline, setVertical,
-        -- :: Attr -> Bool -> Attr
-    
-    attrSet, -- :: Attr -> Pair -> IO ()
-    attrOn, attrOff,
-
-    standout,standend,
-    attrDim, attrBold,
-    attrDimOn, attrDimOff,
-    attrBoldOn, attrBoldOff,
-    wAttrOn,
-    wAttrOff, 
-    wAttrSet, wAttrGet,
-
-    -- * Mouse Routines
-    withMouseEventMask,
-    ButtonEvent(..),
-    MouseEvent(..),
-
-    -- * Keys
-    Key(..),
-
-    -- * Lines
-    vline,
-    ulCorner, llCorner, urCorner, lrCorner, rTee, lTee, bTee, tTee, hLine,
-    vLine, plus, s1, s9, diamond, ckBoard, degree, plMinus, bullet,
-    lArrow, rArrow, dArrow, uArrow, board, lantern, block,
-    s3, s7, lEqual, gEqual, pi, nEqual, sterling,
-
-    -- * Signals
-    cursesSigWinch,
-
-    -- * Misc
-    cursesTest,
-    throwIfErr, throwIfErr_,
-    flushinp,
-    recognize
-        
-  ) where 
-
-#include <config.h>
-#include <HSCurses.h>
-
-#if HAVE_SIGNAL_H
-# include <signal.h>
-#endif
-
-import HSCurses.CWString       ( withLCStringLen )
-import HSCurses.MonadException
-import HSCurses.Logging
-
-import Prelude hiding           ( pi )
-import Data.Char
-import Data.List
-import Data.Ix                  ( Ix )
-
-import Control.Monad
-import Control.Monad.Trans
-import Control.Concurrent
-import Control.Concurrent.Chan
-
-import Foreign
-import CForeign
-import Foreign.C.Error
-import System.Posix.Signals
-
-#if __GLASGOW_HASKELL__ < 603
-import Data.Bits
-#endif
-
-
-------------------------------------------------------------------------
---
--- | @initCurses fn@ does all initialization necessary for a Curses
---   application. 
---
-initCurses :: IO ()
-initCurses = do
-    initScr
-    b <- hasColors
-    when b $ startColor >> useDefaultColors
-
-resetParams :: IO ()
-resetParams = do
-    raw True    -- raw mode please
-    echo False
-    nl False
-    intrFlush True
-    leaveOk False
-    keypad stdScr True
-    defineKey (#const KEY_UP) "\x1b[1;2A"
-    defineKey (#const KEY_DOWN) "\x1b[1;2B"
-    defineKey (#const KEY_SLEFT) "\x1b[1;2D"
-    defineKey (#const KEY_SRIGHT) "\x1b[1;2C"
-
-------------------------------------------------------------------------
-
-fi :: (Integral a, Num b) => a -> b
-fi = fromIntegral
-
-throwIfErr :: Num a => String -> IO a -> IO a
---throwIfErr name act = do
---    res <- act
---    if res == (#const ERR)
---        then ioError (userError ("Curses: "++name++" failed"))
---        else return res
-throwIfErr s = throwIf (== (#const ERR)) (\a -> "Curses[" ++ show a ++ "]:"  ++ s)
-
-throwIfErr_ :: Num a => String -> IO a -> IO ()
-throwIfErr_ name act = void $ throwIfErr name act
-
-------------------------------------------------------------------------
-
-type WindowTag = ()
-type Window = Ptr WindowTag
-
---
--- | The standard screen
---
-stdScr :: Window
-stdScr = unsafePerformIO (peek stdscr)
-foreign import ccall "static HSCurses.h &stdscr" 
-    stdscr :: Ptr Window
-
---
--- | initscr is normally the first curses routine to call when
--- initializing a program. curs_initscr(3):
---
--- >     To initialize the routines, the routine initscr or newterm
--- >     must be called before any of the other routines that  deal
--- >     with  windows  and  screens  are used. 
---
--- >     The initscr code determines the terminal type and initial-
--- >     izes all curses data structures.  initscr also causes  the
--- >     first  call  to  refresh  to  clear the screen.  If errors
--- >     occur, initscr writes  an  appropriate  error  message  to
--- >     standard error and exits; otherwise, a pointer is returned
--- >     to stdscr.
---
-initScr :: IO Window
-initScr = throwIfNull "initscr" initscr
-foreign import ccall unsafe "HSCurses.h initscr" initscr :: IO Window
-
---
--- | > The cbreak routine
---   > disables line buffering and erase/kill  character-process-
---   > ing  (interrupt  and  flow  control  characters  are unaf-
---   > fected), making characters typed by the  user  immediately
---   > available  to  the  program.  The nocbreak routine returns
---   > the terminal to normal (cooked) mode.
---
-cBreak :: Bool -> IO ()
-cBreak True  = throwIfErr_ "cbreak"   cbreak
-cBreak False = throwIfErr_ "nocbreak" nocbreak
-
-foreign import ccall unsafe "HSCurses.h cbreak"     cbreak :: IO CInt
-foreign import ccall unsafe "HSCurses.h nocbreak" nocbreak :: IO CInt
-
---
--- |>    The  raw and noraw routines place the terminal into or out
--- >     of raw mode.  Raw mode is similar to cbreak mode, in  that
--- >     characters  typed  are  immediately  passed through to the
--- >     user program.  The differences are that in raw  mode,  the
--- >     interrupt,  quit, suspend, and flow control characters are
--- >     all passed through uninterpreted, instead of generating  a
--- >     signal.   The  behavior  of the BREAK key depends on other
--- >     bits in the tty driver that are not set by curses.
---
-raw :: Bool -> IO ()
-raw False = throwIfErr_ "noraw" noraw
-raw True  = throwIfErr_ "raw"   raw_c
-
-foreign import ccall unsafe "HSCurses.h noraw" noraw :: IO CInt
-foreign import ccall unsafe "HSCurses.h raw"   raw_c :: IO CInt
-
---
--- |>      The  echo  and  noecho routines control whether characters
--- >       typed by the user are echoed by getch as they  are  typed.
--- >       Echoing  by  the  tty  driver is always disabled, but ini-
--- >       tially getch is in echo  mode,  so  characters  typed  are
--- >       echoed.  Authors of most interactive programs prefer to do
--- >       their own echoing in a controlled area of the  screen,  or
--- >       not  to  echo  at  all, so they disable echoing by calling
--- >       noecho.  [See curs_getch(3) for a discussion of how  these
--- >       routines interact with cbreak and nocbreak.]
--- >
---
-echo :: Bool -> IO ()
-echo False = throwIfErr_ "noecho" noecho
-echo True  = throwIfErr_ "echo"   echo_c
-
-foreign import ccall unsafe "HSCurses.h noecho" noecho :: IO CInt
-foreign import ccall unsafe "HSCurses.h echo" echo_c :: IO CInt
-
---
--- |>       The  nl  and  nonl routines control whether the underlying
--- >        display device translates the return key into  newline  on
--- >        input,  and  whether it translates newline into return and
--- >        line-feed on output (in either case, the call  addch('\n')
--- >        does the equivalent of return and line feed on the virtual
--- >        screen).  Initially, these translations do occur.  If  you
--- >        disable  them using nonl, curses will be able to make bet-
--- >        ter use of the line-feed capability, resulting  in  faster
--- >        cursor  motion.   Also, curses will then be able to detect
--- >        the return key.
--- > 
-nl :: Bool -> IO ()
-nl True  = throwIfErr_ "nl"   nl_c
-nl False = throwIfErr_ "nonl" nonl
-
-foreign import ccall unsafe "HSCurses.h nl" nl_c :: IO CInt
-foreign import ccall unsafe "HSCurses.h nonl" nonl :: IO CInt
-
--- |>       If  the intrflush option is enabled, (bf is TRUE), when an
--- >        interrupt key  is  pressed  on  the  keyboard  (interrupt,
--- >        break,  quit)  all  output in the tty driver queue will be
--- >        flushed, giving the  effect  of  faster  response  to  the
--- >        interrupt,  but  causing  curses to have the wrong idea of
--- >        what is on the  screen.   Disabling  (bf  is  FALSE),  the
--- >        option  prevents the flush.
--- > 
-intrFlush :: Bool -> IO ()
-intrFlush bf =
-    throwIfErr_ "intrflush" $ intrflush stdScr (if bf then 1 else 0)
-foreign import ccall unsafe "HSCurses.h intrflush" intrflush :: Window -> (#type bool) -> IO CInt
-
---
--- | Enable the keypad of the user's terminal.
---
-keypad :: Window -> Bool -> IO ()
-keypad win bf = throwIfErr_ "keypad" $ keypad_c win (if bf then 1 else 0)
-foreign import ccall unsafe "HSCurses.h keypad" 
-    keypad_c :: Window -> (#type bool) -> IO CInt
-
-noDelay :: Window -> Bool -> IO ()
-noDelay win bf =
-    throwIfErr_ "nodelay" $ nodelay win (if bf then 1 else 0)
-
-foreign import ccall unsafe "HSCurses.h nodelay" 
-    nodelay :: Window -> (#type bool) -> IO CInt
-
---
--- |   Normally, the hardware cursor is left at the  location  of
---     the  window  cursor  being  refreshed.  The leaveok option
---     allows the cursor to be left wherever the  update  happens
---     to leave it.  It is useful for applications where the cur-
---     sor is not used, since it  reduces  the  need  for  cursor
---     motions.   If  possible, the cursor is made invisible when
---     this option is enabled.
---
-leaveOk  :: Bool -> IO CInt
-leaveOk True  = leaveok_c stdScr 1
-leaveOk False = leaveok_c stdScr 0
-
-foreign import ccall unsafe "HSCurses.h leaveok" 
-    leaveok_c :: Window -> (#type bool) -> IO CInt
-
-clearOk :: Bool -> IO CInt
-clearOk True  = clearok_c stdScr 1
-clearOk False = clearok_c stdScr 0
-
-foreign import ccall unsafe "HSCurses.h clearok" 
-    clearok_c :: Window -> (#type bool) -> IO CInt
-
-------------------------------------------------------------------------
-
-foreign import ccall unsafe "HSCurses.h use_default_colors" 
-    useDefaultColors :: IO ()
-
-defaultBackground, defaultForeground :: Color
-defaultBackground = Color (-1)
-defaultForeground = Color (-1)
-
-------------------------------------------------------------------------
-
-defineKey :: CInt -> String -> IO ()
-defineKey k s =  withCString s (\s' -> define_key s' k) >> return ()
-
-foreign import ccall unsafe "HSCurses.h define_key" 
-    define_key :: Ptr CChar -> CInt -> IO ()
-
---
--- | >  The program must call endwin for each terminal being used before
---   >  exiting from curses.
---
-endWin :: IO ()
-endWin = throwIfErr_ "endwin" endwin
-foreign import ccall unsafe "HSCurses.h endwin" endwin :: IO CInt
-
-------------------------------------------------------------------------
-
---
--- | get the dimensions of the screen
---
-scrSize :: IO (Int, Int)
-scrSize = do
-    lnes <- peek linesPtr
-    cols <- peek colsPtr
-    return (fromIntegral lnes, fromIntegral cols)
-
-foreign import ccall "HSCurses.h &LINES" linesPtr :: Ptr CInt
-foreign import ccall "HSCurses.h &COLS"  colsPtr  :: Ptr CInt
-
---
--- | refresh curses windows and lines. curs_refresh(3)
---
-refresh :: IO ()
-refresh = throwIfErr_ "refresh" refresh_c
-
-foreign import ccall unsafe "HSCurses.h refresh" 
-    refresh_c :: IO CInt
-
---
--- | Do an actual update. Used after endWin on linux to restore the terminal
---
-update :: IO ()
-update = throwIfErr_ "update" update_c
-
-foreign import ccall unsafe "HSCurses.h doupdate" 
-    update_c :: IO CInt
-
-------------------------------------------------------------------------
-
-hasColors :: IO Bool
-hasColors = liftM (/= 0) has_colors
-foreign import ccall unsafe "HSCurses.h has_colors" has_colors :: IO (#type bool)
-
---
--- | Initialise the color settings, also sets the screen to the
--- default colors (white on black)
---
-startColor :: IO ()
-startColor = throwIfErr_ "start_color" start_color
-foreign import ccall unsafe start_color :: IO CInt
-
-newtype Pair = Pair Int deriving (Eq, Ord, Ix, Show)
-
---
--- | colorPairs defines the maximum number of color-pairs the terminal
--- can support). 
---
-colorPairs :: IO Int
-colorPairs = fmap fromIntegral $ peek colorPairsPtr
-
-foreign import ccall "HSCurses.h &COLOR_PAIRS" 
-        colorPairsPtr :: Ptr CInt
-
-newtype Color = Color Int deriving (Eq, Ord, Ix)
-
-colors :: IO Int
-colors = liftM fromIntegral $ peek colorsPtr
-
-foreign import ccall "HSCurses.h &COLORS" colorsPtr :: Ptr CInt
-
---black, red, green, yellow, blue, magenta, cyan, white :: Color
-
-color :: String -> Maybe Color
-color "default"  = Just $ Color (-1)
-color "black"    = Just $ Color (#const COLOR_BLACK)
-color "red"      = Just $ Color (#const COLOR_RED)
-color "green"    = Just $ Color (#const COLOR_GREEN)
-color "yellow"   = Just $ Color (#const COLOR_YELLOW)
-color "blue"     = Just $ Color (#const COLOR_BLUE)
-color "magenta"  = Just $ Color (#const COLOR_MAGENTA)
-color "cyan"     = Just $ Color (#const COLOR_CYAN)
-color "white"    = Just $ Color (#const COLOR_WHITE)
-color _ =  Nothing
-
-
---
--- |   curses support color attributes  on  terminals  with  that
---     capability.   To  use  these  routines start_color must be
---     called, usually right after initscr.   Colors  are  always
---     used  in pairs (referred to as color-pairs).  A color-pair
---     consists of a foreground  color  (for  characters)  and  a
---     background color (for the blank field on which the charac-
---     ters are displayed).  A programmer  initializes  a  color-
---     pair  with  the routine init_pair.  After it has been ini-
---     tialized, COLOR_PAIR(n), a macro  defined  in  <curses.h>,
---     can be used as a new video attribute.
---
---     If  a  terminal  is capable of redefining colors, the pro-
---     grammer can use the routine init_color to change the defi-
---     nition   of   a   color.
---
---     The init_pair routine changes the definition of  a  color-
---     pair.   It takes three arguments: the number of the color-
---     pair to be changed, the foreground color number,  and  the
---     background color number.  For portable applications:
---
---     -    The value of the first argument must be between 1 and
---          COLOR_PAIRS-1.
---
---     -    The value of the second and third arguments  must  be
---          between  0  and  COLORS (the 0 color pair is wired to
---          white on black and cannot be changed).
---
---
-initPair :: Pair -> Color -> Color -> IO ()
-initPair (Pair p) (Color f) (Color b) =
-    throwIfErr_ "init_pair" $
-        init_pair (fromIntegral p) (fromIntegral f) (fromIntegral b)
-
-foreign import ccall unsafe 
-    init_pair :: CShort -> CShort -> CShort -> IO CInt
-
-
-pairContent :: Pair -> IO (Color, Color)
-pairContent (Pair p) =
-    alloca $ \fPtr ->
-    alloca $ \bPtr -> do
-        throwIfErr "pair_content" $ pair_content (fromIntegral p) fPtr bPtr
-        f <- peek fPtr
-        b <- peek bPtr
-        return (Color (fromIntegral f), Color (fromIntegral b))
-
-foreign import ccall unsafe pair_content :: CShort -> Ptr CShort -> Ptr CShort -> IO CInt
-
-canChangeColor :: IO Bool
-canChangeColor = liftM (/= 0) can_change_color
-
-foreign import ccall unsafe can_change_color :: IO (#type bool)
-
-initColor :: Color -> (Int, Int, Int) -> IO ()
-initColor (Color c) (r, g, b) =
-    throwIfErr_ "init_color" $
-        init_color (fromIntegral c) (fromIntegral r) (fromIntegral g) (fromIntegral b)
-foreign import ccall unsafe init_color :: CShort -> CShort -> CShort -> CShort -> IO CInt
-
-colorContent :: Color -> IO (Int, Int, Int)
-colorContent (Color c) =
-    alloca $ \rPtr ->
-    alloca $ \gPtr ->
-    alloca $ \bPtr -> do
-        throwIfErr "color_content" $ color_content (fromIntegral c) rPtr gPtr bPtr
-        r <- peek rPtr
-        g <- peek gPtr
-        b <- peek bPtr
-        return (fromIntegral r, fromIntegral g, fromIntegral b)
-
-foreign import ccall unsafe 
-    color_content :: CShort -> Ptr CShort -> Ptr CShort -> Ptr CShort -> IO CInt
-
-foreign import ccall unsafe "HSCurses.h hs_curses_color_pair" 
-    colorPair :: Pair -> (#type chtype)
-#def inline chtype hs_curses_color_pair (HsInt pair) {return COLOR_PAIR (pair);}
-
--------------
--- Attributes 
--------------
-
-foreign import ccall unsafe "HSCurses.h attr_set" 
-    attr_set :: Attr -> CShort -> Ptr a -> IO Int
-
--- foreign import ccall unsafe "HSCurses.h attr_get" :: Attr -> CShort -> Ptr a -> IO Int
-
-foreign import ccall unsafe "HSCurses.h wattr_set" 
-    wattr_set :: Window -> Attr -> CInt -> Ptr a -> IO CInt
-
-foreign import ccall unsafe "HSCurses.h wattr_get" 
-    wattr_get :: Window -> Ptr Attr -> Ptr CShort -> Ptr a -> IO CInt
-
-foreign import ccall "HSCurses.h attr_on" attr_on :: (#type attr_t) -> Ptr a -> IO Int
-foreign import ccall "HSCurses.h attr_off" attr_off :: (#type attr_t) -> Ptr a -> IO Int
-foreign import ccall "HSCurses.h attron" attron :: Int -> IO Int
-foreign import ccall "HSCurses.h attroff" attroff :: Int -> IO Int
-foreign import ccall unsafe "HSCurses.h wattron" wattron :: Window -> CInt -> IO CInt
-foreign import ccall unsafe "HSCurses.h wattroff" wattroff :: Window -> CInt -> IO CInt
-foreign import ccall standout :: IO Int
-foreign import ccall standend :: IO Int
-
---
--- |
---
-wAttrSet :: Window -> (Attr,Pair) -> IO ()
-wAttrSet w (a,(Pair p)) = throwIfErr_ "wattr_set" $ 
-    wattr_set w a (fromIntegral p) nullPtr
-
---
--- | manipulate the current attributes of the named window. see curs_attr(3)
---
-wAttrGet :: Window -> IO (Attr,Pair)
-wAttrGet w =
-    alloca $ \pa -> 
-        alloca $ \pp -> do
-            throwIfErr_ "wattr_get" $ wattr_get w pa pp nullPtr
-            a <- peek pa
-            p <- peek pp
-            return (a,Pair $ fromIntegral p)
-
-
-newtype Attr = Attr (#type attr_t) deriving (Eq,Storable,Bits, Num, Show)
-
---
--- | Normal display (no highlight)
---
-attr0 :: Attr
-attr0 = Attr (#const WA_NORMAL)
-
-isAltCharset, isBlink, isBold, isDim, isHorizontal, isInvis, isLeft,
-    isLow, isProtect, isReverse, isRight, isStandout, isTop,
-    isUnderline, isVertical :: Attr -> Bool
-
-isAltCharset = isAttr (#const WA_ALTCHARSET)
-isBlink      = isAttr (#const WA_BLINK)
-isBold       = isAttr (#const WA_BOLD)
-isDim        = isAttr (#const WA_DIM)
-isHorizontal = isAttr (#const WA_HORIZONTAL)
-isInvis      = isAttr (#const WA_INVIS)
-isLeft       = isAttr (#const WA_LEFT)
-isLow        = isAttr (#const WA_LOW)
-isProtect    = isAttr (#const WA_PROTECT)
-isReverse    = isAttr (#const WA_REVERSE)
-isRight      = isAttr (#const WA_RIGHT)
-isStandout   = isAttr (#const WA_STANDOUT)
-isTop        = isAttr (#const WA_TOP)
-isUnderline  = isAttr (#const WA_UNDERLINE)
-isVertical   = isAttr (#const WA_VERTICAL)
-
-isAttr :: (#type attr_t) -> Attr -> Bool
-isAttr b (Attr a) = a .&. b /= 0
-
---
--- | Setting attributes
---
-setAltCharset, setBlink, setBold, setDim, setHorizontal, setInvis,
-    setLeft, setLow, setProtect, setReverse, setRight, setStandout,
-    setTop, setUnderline, setVertical :: Attr -> Bool -> Attr
-
-setAltCharset = setAttr (#const WA_ALTCHARSET)
-setBlink      = setAttr (#const WA_BLINK)
-setBold       = setAttr (#const WA_BOLD)
-setDim        = setAttr (#const WA_DIM)
-setHorizontal = setAttr (#const WA_HORIZONTAL)
-setInvis      = setAttr (#const WA_INVIS)
-setLeft       = setAttr (#const WA_LEFT)
-setLow        = setAttr (#const WA_LOW)
-setProtect    = setAttr (#const WA_PROTECT)
-setReverse    = setAttr (#const WA_REVERSE)
-setRight      = setAttr (#const WA_RIGHT)
-setStandout   = setAttr (#const WA_STANDOUT)
-setTop        = setAttr (#const WA_TOP)
-setUnderline  = setAttr (#const WA_UNDERLINE)
-setVertical   = setAttr (#const WA_VERTICAL)
-
-setAttr :: (#type attr_t) -> Attr -> Bool -> Attr
-setAttr b (Attr a) False = Attr (a .&. complement b)
-setAttr b (Attr a) True  = Attr (a .|.            b)
-
-attrPlus :: Attr -> Attr -> Attr
-attrPlus (Attr a) (Attr b) = Attr (a .|. b)
-
-attrSet :: Attr -> Pair -> IO ()
-attrSet attr (Pair p) = throwIfErr_ "attrset" $
-    attr_set attr (fromIntegral p) nullPtr
-
-attrOn :: Attr -> IO ()
-attrOn (Attr attr) = throwIfErr_ "attr_on" $
-    attr_on attr nullPtr
-
-
-attrOff :: Attr -> IO ()
-attrOff (Attr attr) = throwIfErr_ "attr_off" $
-    attr_off attr nullPtr
-
-
-
-wAttrOn :: Window -> Int -> IO ()
-wAttrOn w x = throwIfErr_ "wattron" $ wattron w (fi x)
-
-wAttrOff :: Window -> Int -> IO ()
-wAttrOff w x = throwIfErr_ "wattroff" $ wattroff w (fi x)
-
-attrDimOn :: IO ()
-attrDimOn  = throwIfErr_ "attron A_DIM" $
-    attron (#const A_DIM) 
-
-attrDimOff :: IO ()
-attrDimOff = throwIfErr_ "attroff A_DIM" $
-    attroff (#const A_DIM) 
-
-attrBoldOn :: IO ()
-attrBoldOn  = throwIfErr_ "attron A_BOLD" $
-    attron (#const A_BOLD) 
-
-attrBoldOff :: IO ()
-attrBoldOff = throwIfErr_ "attroff A_BOLD" $
-    attroff (#const A_BOLD) 
-
-
-attrDim :: Int
-attrDim = (#const A_DIM)
-attrBold :: Int
-attrBold = (#const A_BOLD)
-
-------------------------------------------------------------------------
-
-mvWAddStr :: Window -> Int -> Int -> String -> IO ()
-mvWAddStr w y x str = wMove w y x >> wAddStr w str 
-
-addLn :: IO ()
-addLn = wAddStr stdScr "\n" 
-
---
--- | normalise the string, stripping \\r and making control chars
--- printable. Called over all output(?)
-
-{-
-normalise :: String -> String
-normalise []        = []
-normalise ('\r':cs) = normalise cs
-normalise (c:cs) | isControl c   = '@' : normalise cs
-                 | otherwise     = c   : normalise cs
-{-# INLINE normalise #-}
--}
-
-{-
-normalise s = map f . filter (/= '\r') s
-    where
-        f c | isPrint c  = c
-        f c = '@'
--}
-
-------------------------------------------------------------------------
-
-#if defined(HAVE_WCHAR_H) && defined(HAVE_LIBNCURSESW)
-
---wAddStr :: Window -> String -> IO ()
---wAddStr w str = throwIfErr_ ("waddnwstr: " ++ show str) $ withCWStringLen (normalise str) (\(ws,len) -> waddnwstr w ws (fi len))
-    
-foreign import ccall unsafe 
-    waddnwstr :: Window -> CWString -> CInt -> IO CInt
-
-foreign import ccall unsafe 
-    waddch :: Window -> (#type chtype) -> IO CInt
-
-wAddStr :: Window -> String -> IO ()
-wAddStr win str = do
-    let
-        convStr f = case f [] of
-            [] -> return ()
-            s  -> throwIfErr_ "waddnstr" $
-                withCWStringLen  (s) (\(ws,len) ->  (waddnwstr win ws (fi len)))
-        loop []        acc = convStr acc
-        loop (ch:str') acc = recognize
-            ch
-            (loop str' (acc . (ch:)))
-            (\ch' -> do
-                convStr acc
-                throwIfErr "waddch" $ waddch win ch'
-                loop str' id)
-    loop str id 
-
-#else
-
---
--- This is heavily called, and does a lot of allocs.  We walk over all
--- the string accumulating a list of characters to be drawn.
---
--- Got it down to:
---
---      wAddStr Yi.Curses 20.0   38.1
---      wAddStr Yi.Curses 10.0   32.5
--- 
--- TODO make this way less expensive. That accum sucks.
--- use difference lists for O(1) append
---
-wAddStr :: Window -> [Char] -> IO ()
-wAddStr _   [] = return ()
-wAddStr win s  = throwIfErr_ ("waddnstr: <" ++ s ++ ">") $
-    withLCStringLen (s) (\(ws,len) -> waddnstr win ws (fi len))
-
-foreign import ccall threadsafe
-    waddnstr :: Window -> CString -> CInt -> IO CInt
-
-foreign import ccall threadsafe
-    waddch :: Window -> (#type chtype) -> IO CInt
-
-foreign import ccall threadsafe 
-    waddchnstr :: Window -> CString -> CInt -> IO CInt
-
-#endif
-
-foreign import ccall threadsafe
-    vline  :: Char -> Int -> IO ()
-
-------------------------------------------------------------------------
-
---
--- what ?
---
-
-#let translate_attr attr =                              \
-    "(if a .&. %lu /= 0 then %lu else 0) .|.",          \
-    (unsigned long) WA_##attr, (unsigned long) A_##attr
-
-bkgrndSet :: Attr -> Pair -> IO ()
-bkgrndSet (Attr a) p = bkgdset $
-    fromIntegral (ord ' ') .|.
-    #translate_attr ALTCHARSET
-    #translate_attr BLINK
-    #translate_attr BOLD
-    #translate_attr DIM
-    #translate_attr INVIS
-    #translate_attr PROTECT
-    #translate_attr REVERSE
-    #translate_attr STANDOUT
-    #translate_attr UNDERLINE
-    colorPair p
-
-foreign import ccall unsafe bkgdset :: (#type chtype) -> IO ()
-
-erase :: IO ()
-erase = throwIfErr_ "erase" $ werase_c  stdScr
-foreign import ccall unsafe "werase" werase_c :: Window -> IO CInt
-
-wclear :: Window -> IO ()
-wclear w = throwIfErr_ "wclear" $ wclear_c  w
-foreign import ccall unsafe "wclear" wclear_c :: Window -> IO CInt
-
-clrToEol :: IO ()
-clrToEol = throwIfErr_ "clrtoeol" clrtoeol
-foreign import ccall unsafe clrtoeol :: IO CInt
-
---
--- | >    move the cursor associated with the window
---   >    to line y and column x.  This routine does  not  move  the
---   >    physical  cursor  of the terminal until refresh is called.
---   >    The position specified is relative to the upper  left-hand
---   >    corner of the window, which is (0,0).
---
--- Note that 'move_c' may be a macro.
---
-move :: Int -> Int -> IO ()
-move y x = throwIfErr_ "move" $ move_c (fromIntegral y) (fromIntegral x)
-
-foreign import ccall unsafe "move" 
-    move_c :: CInt -> CInt -> IO CInt
-
---
--- | >    move the cursor associated with the window
---   >    to line y and column x.  This routine does  not  move  the
---   >    physical  cursor  of the terminal until refresh is called.
---   >    The position specified is relative to the upper  left-hand
---   >    corner of the window, which is (0,0).
---
-wMove :: Window -> Int -> Int -> IO ()
-wMove w y x = throwIfErr_ "wmove" $ wmove w (fi y) (fi x)
-
-foreign import ccall unsafe  
-    wmove :: Window -> CInt -> CInt -> IO CInt
-
-------------------
--- Cursor routines
-------------------
-
-data CursorVisibility = CursorInvisible | CursorVisible | CursorVeryVisible
-
-vis_c :: CursorVisibility -> CInt
-vis_c vis = case vis of
-    CursorInvisible   -> 0
-    CursorVisible     -> 1
-    CursorVeryVisible -> 2
-    
-c_vis :: CInt -> CursorVisibility
-c_vis 0 = CursorInvisible
-c_vis 1 = CursorVisible
-c_vis 2 = CursorVeryVisible
-c_vis n = error ("Illegal C value for cursor visibility: " ++ show n)
-
---
--- | Set the cursor state
---
--- >       The curs_set routine sets  the  cursor  state  is  set  to
--- >       invisible, normal, or very visible for visibility equal to
--- >       0, 1, or 2 respectively.  If  the  terminal  supports  the
--- >       visibility   requested,   the  previous  cursor  state  is
--- >       returned; otherwise, ERR is returned.
---
-cursSet :: CursorVisibility -> IO CursorVisibility
-cursSet CursorInvisible = 
-    do leaveOk True
-       old <- curs_set 0
-       return $ c_vis old
-cursSet v = 
-    do leaveOk False 
-       old <- curs_set (vis_c v)
-       return $ c_vis old
-
-foreign import ccall unsafe "HSCurses.h curs_set" 
-    curs_set :: CInt -> IO CInt
-
--- 
--- | Get the current cursor coordinates
---
-getYX :: Window -> IO (Int, Int)
-getYX w =
-    alloca $ \py ->                 -- allocate two ints on the stack
-        alloca $ \px -> do
-            nomacro_getyx w py px   -- writes current cursor coords
-            y <- peek py
-            x <- peek px
-            return (fromIntegral y, fromIntegral x)
-
---
--- | Get the current cursor coords, written into the two argument ints.
---
--- >    The getyx macro places the current cursor position of the given
--- >    window in the two integer variables y and x.
---
---      void getyx(WINDOW *win, int y, int x);
---
-foreign import ccall unsafe "HSCursesUtils.h hscurses_nomacro_getyx" 
-        nomacro_getyx :: Window -> Ptr CInt -> Ptr CInt -> IO ()
-
-------------------------------------------------------------------------
-
-
-touchWin :: Window -> IO ()
-touchWin w = throwIfErr_ "touchwin" $ touchwin w
-foreign import ccall touchwin :: Window -> IO CInt
-
-newPad :: Int -> Int -> IO Window
-newPad nlines ncols = throwIfNull "newpad" $ 
-    newpad (fromIntegral nlines) (fromIntegral ncols)
-
-pRefresh :: Window -> Int -> Int -> Int -> Int -> Int -> Int -> IO ()
-pRefresh pad pminrow pmincol sminrow smincol smaxrow smaxcol = 
-    throwIfErr_ "prefresh" $
-        prefresh pad (fromIntegral pminrow) 
-                     (fromIntegral pmincol) 
-                     (fromIntegral sminrow) 
-                     (fromIntegral smincol) 
-                     (fromIntegral smaxrow) 
-                     (fromIntegral smaxcol)
-
-delWin :: Window -> IO ()
-delWin w = throwIfErr_ "delwin" $ delwin w
-    
-foreign import ccall unsafe 
-    prefresh :: Window -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt
-
-foreign import ccall unsafe 
-    newpad :: CInt -> CInt -> IO Window
-
-foreign import ccall unsafe 
-    delwin :: Window -> IO CInt
-
-newWin :: Int -> Int -> Int -> Int -> IO Window
-newWin nlines ncolumn begin_y begin_x = throwIfNull "newwin" $ 
-    newwin (fi nlines) (fi ncolumn) (fi begin_y) (fi begin_x)
-
-foreign import ccall unsafe 
-    newwin :: CInt -> CInt -> CInt -> CInt -> IO Window
-
-wClrToEol :: Window -> IO ()
-wClrToEol w = throwIfErr_ "wclrtoeol" $ wclrtoeol w
-
-foreign import ccall unsafe wclrtoeol :: Window -> IO CInt
-
---
--- | >      The getch, wgetch, mvgetch and mvwgetch, routines read a
---   >      character  from the window.
---
-foreign import ccall unsafe getch :: IO CInt
-
---foreign import ccall unsafe def_prog_mode :: IO CInt
---foreign import ccall unsafe reset_prog_mode :: IO CInt
-foreign import ccall unsafe flushinp :: IO CInt
-
-foreign import ccall unsafe "HSCurses.h noqiflush" 
-    noqiflush :: IO ()
-
-foreign import ccall unsafe "HSCurses.h beep" c_beep :: IO CInt
-foreign import ccall unsafe "HSCurses.h flash" c_flash :: IO CInt
-
-beep :: IO ()
-beep = do
-    br <- c_beep
-    when (br /= (#const OK)) (c_flash >> return ()) 
-
-------------------------------------------------------------------------
---
--- | Map curses keys to key abstraction
---
-
-data Key
-    = KeyChar Char | KeyBreak | KeyDown | KeyUp | KeyLeft | KeyRight
-    | KeyHome | KeyBackspace | KeyF Int | KeyDL | KeyIL | KeyDC
-    | KeyIC | KeyEIC | KeyClear | KeyEOS | KeyEOL | KeySF | KeySR
-    | KeyNPage | KeyPPage | KeySTab | KeyCTab | KeyCATab | KeyEnter
-    | KeySReset | KeyReset | KeyPrint | KeyLL | KeyA1 | KeyA3
-    | KeyB2 | KeyC1 | KeyC3 | KeyBTab | KeyBeg | KeyCancel | KeyClose
-    | KeyCommand | KeyCopy | KeyCreate | KeyEnd | KeyExit | KeyFind
-    | KeyHelp | KeyMark | KeyMessage | KeyMove | KeyNext | KeyOpen
-    | KeyOptions | KeyPrevious | KeyRedo | KeyReference | KeyRefresh
-    | KeyReplace | KeyRestart | KeyResume | KeySave | KeySBeg
-    | KeySCancel | KeySCommand | KeySCopy | KeySCreate | KeySDC
-    | KeySDL | KeySelect | KeySEnd | KeySEOL | KeySExit | KeySFind
-    | KeySHelp | KeySHome | KeySIC | KeySLeft | KeySMessage | KeySMove
-    | KeySNext | KeySOptions | KeySPrevious | KeySPrint | KeySRedo
-    | KeySReplace | KeySRight | KeySRsume | KeySSave | KeySSuspend
-    | KeySUndo | KeySuspend | KeyUndo | KeyResize | KeyMouse | KeyUnknown Int
-    deriving (Eq,Show)
-
-decodeKey :: CInt -> Key
-decodeKey key = case key of
-    _ | key >= 0 && key <= 255 -> KeyChar (chr (fromIntegral key))
-    (#const KEY_BREAK)         -> KeyBreak
-    (#const KEY_DOWN)          -> KeyDown
-    (#const KEY_UP)            -> KeyUp
-    (#const KEY_LEFT)          -> KeyLeft
-    (#const KEY_RIGHT)         -> KeyRight
-    (#const KEY_HOME)          -> KeyHome
-    (#const KEY_BACKSPACE)     -> KeyBackspace
-    _ | key >= (#const KEY_F0) && key <= (#const KEY_F(63))
-                               -> KeyF (fromIntegral (key - #const KEY_F0))
-    (#const KEY_DL)            -> KeyDL
-    (#const KEY_IL)            -> KeyIL
-    (#const KEY_DC)            -> KeyDC
-    (#const KEY_IC)            -> KeyIC
-    (#const KEY_EIC)           -> KeyEIC
-    (#const KEY_CLEAR)         -> KeyClear
-    (#const KEY_EOS)           -> KeyEOS
-    (#const KEY_EOL)           -> KeyEOL
-    (#const KEY_SF)            -> KeySF
-    (#const KEY_SR)            -> KeySR
-    (#const KEY_NPAGE)         -> KeyNPage
-    (#const KEY_PPAGE)         -> KeyPPage
-    (#const KEY_STAB)          -> KeySTab
-    (#const KEY_CTAB)          -> KeyCTab
-    (#const KEY_CATAB)         -> KeyCATab
-    (#const KEY_ENTER)         -> KeyEnter
-    (#const KEY_SRESET)        -> KeySReset
-    (#const KEY_RESET)         -> KeyReset
-    (#const KEY_PRINT)         -> KeyPrint
-    (#const KEY_LL)            -> KeyLL
-    (#const KEY_A1)            -> KeyA1
-    (#const KEY_A3)            -> KeyA3
-    (#const KEY_B2)            -> KeyB2
-    (#const KEY_C1)            -> KeyC1
-    (#const KEY_C3)            -> KeyC3
-    (#const KEY_BTAB)          -> KeyBTab
-    (#const KEY_BEG)           -> KeyBeg
-    (#const KEY_CANCEL)        -> KeyCancel
-    (#const KEY_CLOSE)         -> KeyClose
-    (#const KEY_COMMAND)       -> KeyCommand
-    (#const KEY_COPY)          -> KeyCopy
-    (#const KEY_CREATE)        -> KeyCreate
-    (#const KEY_END)           -> KeyEnd
-    (#const KEY_EXIT)          -> KeyExit
-    (#const KEY_FIND)          -> KeyFind
-    (#const KEY_HELP)          -> KeyHelp
-    (#const KEY_MARK)          -> KeyMark
-    (#const KEY_MESSAGE)       -> KeyMessage
-    (#const KEY_MOVE)          -> KeyMove
-    (#const KEY_NEXT)          -> KeyNext
-    (#const KEY_OPEN)          -> KeyOpen
-    (#const KEY_OPTIONS)       -> KeyOptions
-    (#const KEY_PREVIOUS)      -> KeyPrevious
-    (#const KEY_REDO)          -> KeyRedo
-    (#const KEY_REFERENCE)     -> KeyReference
-    (#const KEY_REFRESH)       -> KeyRefresh
-    (#const KEY_REPLACE)       -> KeyReplace
-    (#const KEY_RESTART)       -> KeyRestart
-    (#const KEY_RESUME)        -> KeyResume
-    (#const KEY_SAVE)          -> KeySave
-    (#const KEY_SBEG)          -> KeySBeg
-    (#const KEY_SCANCEL)       -> KeySCancel
-    (#const KEY_SCOMMAND)      -> KeySCommand
-    (#const KEY_SCOPY)         -> KeySCopy
-    (#const KEY_SCREATE)       -> KeySCreate
-    (#const KEY_SDC)           -> KeySDC
-    (#const KEY_SDL)           -> KeySDL
-    (#const KEY_SELECT)        -> KeySelect
-    (#const KEY_SEND)          -> KeySEnd
-    (#const KEY_SEOL)          -> KeySEOL
-    (#const KEY_SEXIT)         -> KeySExit
-    (#const KEY_SFIND)         -> KeySFind
-    (#const KEY_SHELP)         -> KeySHelp
-    (#const KEY_SHOME)         -> KeySHome
-    (#const KEY_SIC)           -> KeySIC
-    (#const KEY_SLEFT)         -> KeySLeft
-    (#const KEY_SMESSAGE)      -> KeySMessage
-    (#const KEY_SMOVE)         -> KeySMove
-    (#const KEY_SNEXT)         -> KeySNext
-    (#const KEY_SOPTIONS)      -> KeySOptions
-    (#const KEY_SPREVIOUS)     -> KeySPrevious
-    (#const KEY_SPRINT)        -> KeySPrint
-    (#const KEY_SREDO)         -> KeySRedo
-    (#const KEY_SREPLACE)      -> KeySReplace
-    (#const KEY_SRIGHT)        -> KeySRight
-    (#const KEY_SRSUME)        -> KeySRsume
-    (#const KEY_SSAVE)         -> KeySSave
-    (#const KEY_SSUSPEND)      -> KeySSuspend
-    (#const KEY_SUNDO)         -> KeySUndo
-    (#const KEY_SUSPEND)       -> KeySuspend
-    (#const KEY_UNDO)          -> KeyUndo
-#ifdef KEY_RESIZE
-    (#const KEY_RESIZE)        -> KeyResize
-#endif
-#ifdef KEY_MOUSE
-    (#const KEY_MOUSE)         -> KeyMouse
-#endif
-    _                          -> KeyUnknown (fromIntegral key)
-
-keyResizeCode :: Maybe CInt
-#ifdef KEY_RESIZE
-keyResizeCode = Just (#const KEY_RESIZE)
-#else
-keyResizeCode = Nothing
-#endif
-
--- ---------------------------------------------------------------------
--- get char
---
-
--- ncurses ungetch and Haskell's threadWaitRead do not work together well.
--- So I decided to implement my own input queue.
-
-ungetCh i = 
-    do debug "ungetCh called"
-       writeChan inputBuf (BufDirect (fi i))
-
-data BufData = BufDirect CInt  -- data directly available
-             | DataViaGetch    -- data can be obtained by calling getch
-
-inputBuf :: Chan BufData
-inputBuf = unsafePerformIO newChan
-{-# NOINLINE inputBuf #-}
-
-getchToInputBuf :: IO ()
-getchToInputBuf =
-    do threadWaitRead (fi 0)
-       {- From the (n)curses manpage:
-       Programmers  concerned  about portability should be prepared for either
-       of two cases: (a) signal receipt does not interrupt getch;  (b)  signal
-       receipt  interrupts getch and causes it to return ERR with errno set to
-       EINTR.  Under the ncurses implementation, handled signals never  inter$B!>(B
-       rupt getch.
-       -}
-       -- we only signalize that getch can now called without getting blocked.
-       -- directly calling `getch' might result in losing the character just
-       -- read (race condition).
-       debug "now input available on stdin"
-       writeChan inputBuf DataViaGetch
---
--- | read a character from the window
---
-getCh :: IO Key
-getCh = 
-    do debug "getCh called"
-       tid <- forkIO getchToInputBuf
-       d <- readChan inputBuf
-       killThread tid  -- we can kill the thread savely, because the thread does
-                       -- not read any data via getch
-       v <- case d of
-              BufDirect x -> 
-                do debug "getCh: getting data directly from buffer"
-                   return x
-              DataViaGetch -> 
-                do debug "getCh: getting data via getch"
-                   getch -- won't block!
-       case v of
-         (#const ERR) -> -- NO CODE IN THIS LINE 
-             do e <- getErrno
-                if e `elem` [eAGAIN, eINTR] 
-                   then do debug "Curses.getCh returned eAGAIN or eINTR" 
-                           getCh
-                   else throwErrno "HSCurses.Curses.getch"
-         k -> let k' = decodeKey k
-                  in do debug ("getCh: result = " ++ show k')
-                        return k'
-
-
-resizeTerminal :: Int -> Int -> IO ()
-
-#ifdef HAVE_RESIZETERM
-resizeTerminal a b = throwIfErr_ "resizeterm"  $ resizeterm (fi a) (fi b)
-
-foreign import ccall unsafe "HSCurses.h resizeterm" 
-    resizeterm :: CInt -> CInt -> IO CInt
-#else
-resizeTerminal _ _ = return ()
-#endif
-
---
--- | The SIGWINCH signal is sent whenever the terminal size changes.
--- This signal is not available on all platforms, so it is a |Maybe| value.
---
-cursesSigWinch :: Maybe Signal
-#ifdef SIGWINCH
-cursesSigWinch = Just (#const SIGWINCH)
-#else
-cursesSigWinch = Nothing
-#endif
-
-------------
--- Test case
-------------
-
-cursesTest :: IO ()
-cursesTest = do
-    initScr
-    hc <- hasColors 
-    when hc startColor
-    ccc <- canChangeColor
-    (ys,xs) <- scrSize
-    cp <- colorPairs
-    cs <- colors
-    endWin
-    putStrLn $ "ScreenSize: " ++ show (xs,ys) 
-    putStrLn $ "hasColors: " ++ show hc
-    putStrLn $ "canChangeColor: " ++ show ccc
-    putStrLn $ "colorPairs: " ++ show cp
-    putStrLn $ "colors: " ++ show cs
-
-    
-
-
------------------
--- Mouse Routines
------------------
-
-data MouseEvent = MouseEvent {
-    mouseEventId :: Int, 
-    mouseEventX :: Int, 
-    mouseEventY :: Int, 
-    mouseEventZ :: Int, 
-    mouseEventButton :: [ButtonEvent]
-   } deriving(Show)
-
-data ButtonEvent = ButtonPressed Int | ButtonReleased Int | ButtonClicked Int | 
-    ButtonDoubleClicked Int | ButtonTripleClicked Int | ButtonShift | ButtonControl | ButtonAlt 
-                deriving(Eq,Show)
-
-withMouseEventMask :: MonadIO m => [ButtonEvent] -> m a -> m a
-
-#ifdef KEY_MOUSE
-
-foreign import ccall unsafe "HSCurses.h mousemask" 
-    mousemask :: (#type mmask_t) -> Ptr (#type mmask_t) -> IO (#type mmask_t)
-
-withMouseEventMask bes action = do
-    ov <- liftIO $ alloca (\a ->  mousemask (besToMouseMask bes) a >> peek a) 
-    r <- action 
-    liftIO $ mousemask ov nullPtr 
-    return r
-
-besToMouseMask :: [ButtonEvent] -> (#type mmask_t)
-besToMouseMask bes = foldl' (.|.) 0 (map cb bes) where
-    cb (ButtonPressed 1) = (#const BUTTON1_PRESSED)
-    cb (ButtonPressed 2) = (#const BUTTON2_PRESSED)
-    cb (ButtonPressed 3) = (#const BUTTON3_PRESSED)
-    cb (ButtonPressed 4) = (#const BUTTON4_PRESSED)
-    cb (ButtonReleased 1) = (#const BUTTON1_RELEASED)
-    cb (ButtonReleased 2) = (#const BUTTON2_RELEASED)
-    cb (ButtonReleased 3) = (#const BUTTON3_RELEASED)
-    cb (ButtonReleased 4) = (#const BUTTON4_RELEASED)
-    cb (ButtonClicked 1) = (#const BUTTON1_CLICKED)
-    cb (ButtonClicked 2) = (#const BUTTON2_CLICKED)
-    cb (ButtonClicked 3) = (#const BUTTON3_CLICKED)
-    cb (ButtonClicked 4) = (#const BUTTON4_CLICKED)
-    cb ButtonShift = (#const BUTTON_SHIFT)
-    cb ButtonAlt = (#const BUTTON_ALT)
-    cb ButtonControl = (#const BUTTON_CTRL)
-    cb _ = 0
-
-
-#else
-withMouseEventMask _ a = a
-
-#endif
-
-
-
-
-ulCorner, llCorner, urCorner, lrCorner, rTee, lTee, bTee, tTee, hLine,
-    vLine, plus, s1, s9, diamond, ckBoard, degree, plMinus, bullet,
-    lArrow, rArrow, dArrow, uArrow, board, lantern, block,
-    s3, s7, lEqual, gEqual, pi, nEqual, sterling
-    :: Char
-
-ulCorner = chr 0x250C
-llCorner = chr 0x2514
-urCorner = chr 0x2510
-lrCorner = chr 0x2518
-rTee     = chr 0x2524
-lTee     = chr 0x251C
-bTee     = chr 0x2534
-tTee     = chr 0x252C
-hLine    = chr 0x2500
-vLine    = chr 0x2502
-plus     = chr 0x253C
-s1       = chr 0x23BA -- was: 0xF800
-s9       = chr 0x23BD -- was: 0xF804
-diamond  = chr 0x25C6
-ckBoard  = chr 0x2592
-degree   = chr 0x00B0
-plMinus  = chr 0x00B1
-bullet   = chr 0x00B7
-lArrow   = chr 0x2190
-rArrow   = chr 0x2192
-dArrow   = chr 0x2193
-uArrow   = chr 0x2191
-board    = chr 0x2591
-lantern  = chr 0x256C
-block    = chr 0x2588
-s3       = chr 0x23BB -- was: 0xF801
-s7       = chr 0x23BC -- was: 0xF803
-lEqual   = chr 0x2264
-gEqual   = chr 0x2265
-pi       = chr 0x03C0
-nEqual   = chr 0x2260
-sterling = chr 0x00A3
-
-{-
--- haddock doesn't like these commented out with --
-   #if defined(__STDC_ISO_10646__)  && defined(HAVE_WADDNWSTR)
-   #else 
--}
-
-recognize :: Char -> IO a -> ((#type chtype) -> IO a) -> IO a
-recognize _ch noConvert _convert = noConvert -- Handle the most common case first.
-
-
-
-
--- ---------------------------------------------------------------------
--- code graveyard
---
-
-{-
-
-addStr :: String -> IO ()
-addStr str =
-    throwIfErr_ "addstr" $
-    withCStringConv (readIORef cursesOutConv) str addstr
-foreign import ccall unsafe addstr :: Ptr CChar -> IO CInt
-
-addStrLn :: String -> IO ()
-addStrLn str = addStr str >> addLn
-
---
--- | add a string of characters to a curses window and advance cursor
--- curs_addstr(3)
---
-wAddStr :: Window -> String -> IO ()
-wAddStr w str = throwIfErr_ "waddstr" $
-    withCStringConv (readIORef cursesOutConv) str (waddstr w)
-
-foreign import ccall unsafe waddstr :: Window -> Ptr CChar -> IO CInt
-
-
-addGraphStr :: String -> IO ()
-addGraphStr str = do
-    conv <- readIORef cursesOutConv
-    let
-        convStr f = case f [] of
-            [] -> return ()
-            s  -> throwIfErr_ "addstr" $
-                withCStringConv (return conv) s addstr
-        loop []        acc = convStr acc
-        loop (ch:str') acc = recognize
-            ch
-            (loop str' (acc . (ch:)))
-            (\ch' -> do
-                convStr acc
-                throwIfErr "addch" $ addch ch'
-                loop str' id)
-    loop str id
-
-addGraphStrLn :: String -> IO ()
-addGraphStrLn str = do addGraphStr str; addLn
-
--}
-
--- vim: sw=4 ts=4
diff --git a/HSCurses/CursesHelper.hs b/HSCurses/CursesHelper.hs
deleted file mode 100644
--- a/HSCurses/CursesHelper.hs
+++ /dev/null
@@ -1,473 +0,0 @@
-{-# OPTIONS -cpp -#include HSCursesUtils.h -#include <signal.h> #-}
-
--- 
--- Copyright (C) 2005 Stefan Wehr
---
--- Derived from: yi/Curses/UI.hs
---      Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
---      Released under the same license.
---
--- Derived from: riot/UI.hs
---      Copyright (c) Tuomo Valkonen 2004.
---      Released under the same license.
--- 
--- This program is free software; you can redistribute it and/or
--- modify it under the terms of the GNU General Public License as
--- published by the Free Software Foundation; either version 2 of
--- the License, or (at your option) any later version.
--- 
--- This program is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
--- General Public License for more details.
--- 
--- You should have received a copy of the GNU General Public License
--- along with this program; if not, write to the Free Software
--- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
--- 02111-1307, USA.
--- 
---
-
-module HSCurses.CursesHelper (
-
-        -- * UI initialisation 
-        start, end, suspend, resizeui,
-
-        -- * Input
-        getKey,
-
-        -- * Drawing
-        drawLine, drawCursor,
-
-        -- * Navigation
-        gotoTop,
-
-        -- * Colors
-        ForegroundColor(..), BackgroundColor(..),
-        defaultColor, black, red, green, yellow, blue, magenta, cyan, white,
-
-        -- * Attributes
-        Attribute(..), convertAttributes,
-
-        -- * Style
-        Style(..), CursesStyle, mkCursesStyle, changeCursesStyle,
-        setStyle, resetStyle, convertStyles,
-        defaultStyle, defaultCursesStyle, withStyle, 
-
-        -- * Keys
-        displayKey,
-
-        -- * Helpers
-        withCursor, withProgram
-  )   where
-
-import HSCurses.Curses hiding ( refresh, Window )
-import qualified HSCurses.Curses as Curses
-import HSCurses.Logging
-
-import Char
-import Data.Maybe
-import Data.List
-import Control.Monad.Trans
-import HSCurses.MonadException
-import System.Posix.Signals
-
---
---
-
---
--- | @start@ initializes the UI and grabs the keyboard.
---
--- This function installs a handler for the SIGWINCH signal
--- which writes the KEY_RESIZE key to the input queue (if KEY_RESIZE and
--- and SIGWINCH are both available). 
--- 
-start :: IO ()
-start = do
-    Curses.initCurses                   -- initialise the screen
-    Curses.resetParams
-    Curses.keypad Curses.stdScr True    -- grab the keyboard
-    case (Curses.cursesSigWinch, Curses.keyResizeCode) of
-      (Just sig, Just key) ->
-          do installHandler sig (Catch $ sigwinch sig key) Nothing
-             return ()
-      _ -> debug ("cannot install SIGWINCH handler: signal=" ++ 
-                  show Curses.cursesSigWinch ++ ", KEY_RESIZE=" ++ 
-                  show Curses.keyResizeCode)
-    where sigwinch sig key = 
-              do debug "SIGWINCH signal received"
-                 Curses.ungetCh key
-                 installHandler sig (Catch $ sigwinch sig key) Nothing
-                 return ()
-
-
-
---
--- | Clean up and go home. 
---
-end :: IO ()
-end = do Curses.endWin
--- Refresh is needed on linux. grr.
-#if NCURSES_UPDATE_AFTER_END
-         Curses.update
-#endif
-
---
--- | Suspend the program.
---
-suspend :: IO ()
-suspend = raiseSignal sigTSTP
-
---
--- | @getKey refresh@ reads a key.
---
--- The @refresh@ function is used to redraw the screen when the terminal size
--- changes (see the documentatio of @start@ for a discussion of the problem).
---
-getKey :: MonadIO m => m () -> m Key
-getKey refresh = do
-    k <- liftIO $ Curses.getCh
-    debug ("getKey: " ++ show k)
-    case k of
-      KeyResize -> 
-          do refresh
-             getKey refresh
-      _ -> return k
-
-
---
--- | @drawLine n s@ draws @n@ characters of string @s@.
---
-drawLine :: Int -> String -> IO ()
--- lazy version is faster than calculating length of s
-drawLine w s = Curses.wAddStr Curses.stdScr $! take w (s ++ repeat ' ')
-
---
--- | Draw the cursor at the given position.
---
-drawCursor :: (Int,Int) -> (Int, Int) -> IO ()
-drawCursor (o_y,o_x) (y,x) = withCursor Curses.CursorVisible $ do
-    gotoTop
-    (h,w) <- scrSize
-    Curses.wMove Curses.stdScr (min (h-1) (o_y + y)) (min (w-1) (o_x + x))
-
---
--- | Move cursor to origin of stdScr.
---
-gotoTop :: IO ()
-gotoTop = Curses.wMove Curses.stdScr 0 0
-
-
---
--- | Resize the window
--- From "Writing Programs with NCURSES", by Eric S. Raymond and 
--- Zeyd M. Ben-Halim
---
---
-resizeui :: IO (Int,Int)
-resizeui = do
-    Curses.endWin
-    Curses.refresh
-    Curses.scrSize
-
-
-
-------------------------------------------------------------------------
---
--- | Basic colors.
---
-defaultColor :: Curses.Color
-defaultColor = fromJust $ Curses.color "default"
-
-black, red, green, yellow, blue, magenta, cyan, white :: Curses.Color
-black     = fromJust $ Curses.color "black"
-red       = fromJust $ Curses.color "red"
-green     = fromJust $ Curses.color "green"
-yellow    = fromJust $ Curses.color "yellow"
-blue      = fromJust $ Curses.color "blue"
-magenta   = fromJust $ Curses.color "magenta"
-cyan      = fromJust $ Curses.color "cyan"
-white     = fromJust $ Curses.color "white"
-
---
--- | Converts a list of 'Curses.Color' pairs (foreground color and
---   background color) into the curses representation 'Curses.Pair'.
---
---   You should call this function exactly once, at application startup.
---
--- (not visible outside this module)
-colorsToPairs :: [(Curses.Color, Curses.Color)] -> IO [Curses.Pair]
-colorsToPairs cs =
-    do p <- Curses.colorPairs
-       let nColors = length cs
-           blackWhite = p < nColors
-       if blackWhite
-          then trace ("Terminal does not support enough colors. Number of " ++
-                      " colors requested: " ++ show nColors ++ 
-                      ". Number of colors supported: " ++ show p)
-                 return $ take nColors (repeat (Curses.Pair 0))
-          else mapM toPairs (zip [1..] cs)
-     where toPairs (n, (fg, bg)) = 
-               let p = Curses.Pair n 
-               in do Curses.initPair p fg bg
-                     return p
-
-------------------------------------------------------------------------
--- Nicer, user-visible color defs.
---
--- We separate colors into dark and bright colors, to prevent users
--- from erroneously constructing bright colors for dark backgrounds,
--- which doesn't work.
-
---
--- | Foreground colors.
---
-data ForegroundColor
-    = BlackF
-    | GreyF
-    | DarkRedF
-    | RedF
-    | DarkGreenF
-    | GreenF
-    | BrownF
-    | YellowF
-    | DarkBlueF
-    | BlueF
-    | PurpleF
-    | MagentaF
-    | DarkCyanF
-    | CyanF
-    | WhiteF
-    | BrightWhiteF
-    | DefaultF
-    deriving (Eq, Show)
-
---
--- | Background colors.
---
-data BackgroundColor
-    = BlackB
-    | DarkRedB
-    | DarkGreenB
-    | BrownB
-    | DarkBlueB
-    | PurpleB
-    | DarkCyanB
-    | WhiteB
-    | DefaultB
-    deriving (Eq, Show)
-
---
--- | Mapping abstract colours to ncurses attributes and colours
---
--- (not visible outside this module)
-
-convertBg :: BackgroundColor -> ([Attribute], Curses.Color)
-convertBg c = case c of
-    BlackB      -> ([], black)
-    DarkRedB    -> ([], red)
-    DarkGreenB  -> ([], green)
-    BrownB      -> ([], yellow)
-    DarkBlueB   -> ([], blue)
-    PurpleB     -> ([], magenta)
-    DarkCyanB   -> ([], cyan)
-    WhiteB      -> ([], white)
-    DefaultB    -> ([], defaultColor)
-
-convertFg :: ForegroundColor -> ([Attribute], Curses.Color)
-convertFg c = case c of
-    BlackF       -> ([], black)
-    GreyF        -> ([Bold], black)
-    DarkRedF     -> ([], red)
-    RedF         -> ([Bold], red)
-    DarkGreenF   -> ([], green)
-    GreenF       -> ([Bold], green)
-    BrownF       -> ([], yellow)
-    YellowF      -> ([Bold], yellow)
-    DarkBlueF    -> ([], blue)
-    BlueF        -> ([Bold], blue)
-    PurpleF      -> ([], magenta)
-    MagentaF     -> ([Bold], magenta)
-    DarkCyanF    -> ([], cyan)
-    CyanF        -> ([Bold], cyan)
-    WhiteF       -> ([], white)
-    BrightWhiteF -> ([Bold], white)
-    DefaultF     -> ([], defaultColor)
-
-
-------------------------------------------------------------------------
---
--- | Abstractions for some commonly used attributes.
---
-data Attribute = Bold
-               | Underline
-               | Dim
-               | Reverse
-               | Blink
-               deriving (Eq, Show)
-
---
--- | Converts an abstract attribute list into its curses representation.
---
-convertAttributes :: [Attribute] -> Curses.Attr
-convertAttributes = 
-    foldr setAttrs Curses.attr0
-    where setAttrs Bold = setBoldA
-          setAttrs Underline = setUnderlineA
-          setAttrs Dim = setDimA
-          setAttrs Reverse = setReverseA
-          setAttrs Blink = setBlinkA
-
-setBoldA, setUnderlineA, setDimA, 
-  setReverseA, setBlinkA :: Curses.Attr -> Curses.Attr
-setBoldA = flip Curses.setBold True
-setUnderlineA = flip Curses.setUnderline True
-setDimA = flip Curses.setDim True
-setReverseA = flip Curses.setReverse   True
-setBlinkA = flip Curses.setBlink True
-
-------------------------------------------------------------------------
---
--- | A humand-readable style.
---
-data Style = Style ForegroundColor BackgroundColor
-           | AttributeStyle [Attribute] ForegroundColor BackgroundColor
-           | ColorlessStyle [Attribute]
-           deriving (Eq, Show)
-
-defaultStyle :: Style
-defaultStyle = Style DefaultF DefaultB
-
---
--- | A style which uses the internal curses representations for
---   attributes and colors.
---
-data CursesStyle = CursesStyle Curses.Attr Curses.Pair
-                 | ColorlessCursesStyle Curses.Attr
-                 deriving (Eq, Show)
-
-{-
-instance Show CursesStyle where
-    show (CursesStyle _ _) = "CursesStyle"
-    show (ColorlessCursesStyle _) = "ColorlessCursesStyle"
--}
-
-mkCursesStyle :: [Attribute] -> CursesStyle
-mkCursesStyle attrs = ColorlessCursesStyle (convertAttributes attrs)
-
---
--- | Changes the attributes of the given CursesStyle.
---
-changeCursesStyle :: CursesStyle -> [Attribute] -> CursesStyle
-changeCursesStyle (CursesStyle _ p) attrs =
-    CursesStyle (convertAttributes attrs) p
-changeCursesStyle _ attrs = ColorlessCursesStyle (convertAttributes attrs)
-
-defaultCursesStyle :: CursesStyle
-defaultCursesStyle = CursesStyle Curses.attr0 (Curses.Pair 0)
-
---
--- | Reset the screen to normal values
---
-resetStyle :: IO ()
-resetStyle = setStyle defaultCursesStyle
-
---
--- | Manipulate the current style of the standard screen
---
-setStyle :: CursesStyle -> IO ()
-setStyle (CursesStyle a p) = Curses.wAttrSet Curses.stdScr (a, p)
-setStyle (ColorlessCursesStyle a) = 
-    do (_, p) <- Curses.wAttrGet Curses.stdScr
-       Curses.wAttrSet Curses.stdScr (a, p)
-
-withStyle :: MonadExcIO m => CursesStyle -> m a -> m a
-withStyle style action = 
-    bracketM
-        (liftIO $ do old <- Curses.wAttrGet Curses.stdScr    -- before
-                     setStyle style
-                     return old)
-        (\old -> liftIO $ Curses.wAttrSet Curses.stdScr old) -- after
-        (\_ -> action)                                       -- do this
-
---
--- | Converts a list of human-readable styles into the corresponding
---   curses representation. 
---
---   This function should be called exactly once at application startup
---   for all styles of the application.
-convertStyles :: [Style] -> IO [CursesStyle]
-convertStyles styleList =
-    do let (attrs, cs) = unzip $ map convertStyle styleList
-           cursesAttrs = map convertAttributes attrs
-       cursesPairs <- colorsToPairs' cs
-       let res = zipWith toCursesStyle cursesAttrs cursesPairs
-       trace ("convertStyles: " ++ show (zip styleList res)) (return res)
-    where convertStyle (Style fg bg) = convertStyle (AttributeStyle [] fg bg)
-          convertStyle (AttributeStyle attrs fg bg) =
-              let (afg, cfg) = convertFg fg
-                  (abg, cbg) = convertBg bg
-              in (afg ++ abg ++ attrs, Just (cfg, cbg))
-          convertStyle (ColorlessStyle attrs) = (attrs, Nothing)
-          colorsToPairs' cs = 
-              do pairs <- colorsToPairs (catMaybes cs)
-                 return $ mergeNothing cs pairs
-          mergeNothing (Just _:crest) (p:prest) = Just p 
-                                                  : mergeNothing crest prest
-          mergeNothing (Nothing:crest) ps = Nothing : mergeNothing crest ps
-          mergeNothing [] [] = []
-          toCursesStyle cursesAttrs Nothing = 
-              ColorlessCursesStyle cursesAttrs
-          toCursesStyle cursesAttrs (Just cursesPair) = 
-              CursesStyle cursesAttrs cursesPair
-
-------------------------------------------------------------------------
---
--- | Converting keys to humand-readable strings
---
-
-displayKey :: Key -> String
-displayKey (KeyChar ' ') = "<Space>"
-displayKey (KeyChar '\t') = "<Tab>"
-displayKey (KeyChar '\r') = "<Enter>"
-displayKey (KeyChar c) 
-    | isPrint c = [c]
-displayKey (KeyChar c)  -- Control
-    | ord '\^A' <= ord c && ord c <= ord '\^Z'
-        = let c' = chr $ ord c - ord '\^A' + ord 'a'
-              in '^':[toUpper c']
-displayKey (KeyChar c) = show c
-displayKey KeyDown = "<Down>"
-displayKey KeyUp = "<Up>"
-displayKey KeyLeft = "<Left>"
-displayKey KeyRight = "<Right>"
-displayKey KeyHome = "<Home>"
-displayKey KeyBackspace = "<BS>"
-displayKey (KeyF i) = 'F' : show i
-displayKey KeyNPage = "<NPage>"
-displayKey KeyPPage = "<PPage>"
-displayKey KeyEnter = "<Return>"
-displayKey KeyEnd = "<End>"
-displayKey KeyIC = "<Insert>"
-displayKey KeyDC = "<Delete>"
-displayKey k = show k
-
-
-------------------------------------------------------------------------
---
--- | Other helpers
---
-
---
--- | set the cursor, and do action
---
-withCursor :: MonadExcIO m => CursorVisibility -> m a -> m a
-withCursor nv action = 
-    bracketM
-        (liftIO $ Curses.cursSet nv)             -- before
-        (\vis -> liftIO $ Curses.cursSet vis)    -- after
-        (\_ -> action)                           -- do this
-
-withProgram :: MonadExcIO m => m a -> m a
-withProgram action = withCursor CursorVisible $ 
-    bracketM_ (liftIO endWin) (liftIO flushinp) action
diff --git a/HSCurses/IConv.hsc b/HSCurses/IConv.hsc
deleted file mode 100644
--- a/HSCurses/IConv.hsc
+++ /dev/null
@@ -1,205 +0,0 @@
-{-# OPTIONS -fffi #-}
-
---
--- Copyright (c) 2004 Tuomo Valkonen <tuomov at iki dot fi>
--- Copyright (c) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
--- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-
--- | Iconv binding
-
-#if HAVE_ICONV_H
-# include <iconv.h>
-#endif
-
-module HSCurses.IConv {-(
-    IConv,
-    iconv,
-    iconv_,
-    with_iconv,
-    to_unicode, 
-    from_unicode,
-    to_unicode_,
-    from_unicode_
-  )-} where
-
-import HSCurses.CWString          ( peekUTF8StringLen, withUTF8StringLen )
-
-import Foreign
-import Foreign.C
-import Foreign.C.String
-import Control.Exception    ( Exception, try, bracket )
-
-type IConv = Ptr () --(#type iconv_t)
-
-err_ptr :: Ptr b -> Bool
-err_ptr p = p == (plusPtr nullPtr (-1))
-
-throw_if_not_2_big :: String -> IO CSize -> IO CSize
-throw_if_not_2_big s r_ = do
-    r <- r_
-    if r == fromIntegral (-1 :: Int) then do
-        errno <- getErrno
-        if errno /= e2BIG then
-	    throwErrno s
-	  else
-	    return r
-      else
-        return r
-    
-iconv_open :: String -> String -> IO IConv
-iconv_open to from =
-    withCString to $
-        \cto -> withCString from $
-            \cfrom -> do
-	        throwErrnoIf err_ptr "iconv_open" 
-		    $ c_iconv_open cto cfrom
-
-
-iconv_close :: IConv -> IO ()
-iconv_close ic = 
-    throwErrnoIfMinus1_ "iconv_close" $ c_iconv_close ic
-    
-outbuf_size :: Int
-outbuf_size = 1024
-
-do_iconv :: ((Ptr a, Int) -> IO String) -> IConv -> (Ptr b, Int) -> IO String
-do_iconv get_string_fn ic (inbuf, inbuf_bytes) =
-    alloca $ \inbuf_ptr -> 
-        alloca $ \inbytesleft_ptr -> 
-            alloca $ \outbuf_ptr -> 
-                alloca $ \outbytesleft_ptr -> 
-                    allocaBytes outbuf_size $ \outbuf -> do
-      poke (inbytesleft_ptr :: Ptr CSize) (fromIntegral inbuf_bytes)
-      poke inbuf_ptr inbuf
-      let loop acc = do
-          poke (outbytesleft_ptr :: Ptr CSize) (fromIntegral outbuf_size)
-          poke outbuf_ptr outbuf
-          ret <- throw_if_not_2_big "c_iconv" $
-              c_iconv ic inbuf_ptr inbytesleft_ptr
-                         outbuf_ptr outbytesleft_ptr
-          left <- peek outbytesleft_ptr
-          res <- get_string_fn (castPtr outbuf, outbuf_size - fromIntegral left)
-          if ret == fromIntegral (-1 :: Int) then
-              loop (acc++res)
-            else
-              return (acc++res)
-      loop []
-
-
-with_iconv :: String -> String -> (IConv -> IO a) -> IO a
-with_iconv to from fn =
-    bracket (iconv_open to from) iconv_close fn
-
-iconv_ :: String -> IConv -> IO String
-iconv_ str ic =
-    withCStringLen str $ do_iconv peekCStringLen ic
-
--- between 8-bit encodings only
-iconv :: String -> String -> String -> Either Exception String
-iconv to from str =
-    unsafePerformIO $ try $ with_iconv to from (iconv_ str)
-
-
-#ifdef HAVE_WCHAR_H
-{-
-type CUni = (#type wchar_t)
-cuni_size = (#size wchar_t)
-unicode_charset = "WCHAR_T"
-
-chartocuni :: Char -> CUni
-chartocuni = fromIntegral . ord
-
-cunitochar :: CUni -> Char
-cunitochar = chr . fromIntegral
--}
-
-cuni_charset :: [Char]
-cuni_charset = "WCHAR_T"
-
-peek_cuni :: (Ptr (#type wchar_t), Int) -> IO String
-peek_cuni (buf, bytes) = do
-    let (chars, rembytes) = bytes `divMod` (#size wchar_t)
-    if rembytes /= 0 then
-        error "Conversion result contains remainder bytes."
-      else
-        peekCWStringLen (buf, chars)
-        --liftM (map cunitochar) $ peekArray chars buf
-
-with_cuni :: String -> ((Ptr (#type wchar_t), Int) -> IO String) -> IO String
-with_cuni str f =
-    withCWStringLen str $ \(s, l) -> f (s, l*(#size wchar_t))
-    --withArray (map chartocuni str) $ \s -> f (s, l*cuni_size)
-
-#else
--- no CF_WCHAR_SUPPORT
-
--- Due to endianness problems, it is easiest to do this through UTF-8
-
-cuni_charset :: [Char]
-cuni_charset = "UTF-8"
-
-peek_cuni :: CStringLen -> IO String
-peek_cuni = peekUTF8StringLen
-
-with_cuni :: [Char] -> (CStringLen -> IO a) -> IO a
-with_cuni = withUTF8StringLen
-
-#endif
-
-to_unicode_ :: String -> String -> IO String
-to_unicode_ from str =    
-     with_iconv cuni_charset from $
-      \ic -> withCStringLen str $ do_iconv peek_cuni ic
-
-to_unicode :: String -> String -> Either Exception String
-to_unicode from str = 
-    unsafePerformIO $ try $ to_unicode_ from str
-    
-from_unicode_ :: String -> String -> IO String
-from_unicode_ to str = 
-     with_iconv to cuni_charset $
-      \ic -> with_cuni str $ do_iconv peekCStringLen ic
-
-from_unicode :: String -> String -> Either Exception String
-from_unicode from str = 
-    unsafePerformIO $ try $ from_unicode_ from str
-
-
-#ifndef ICONV_LIB_PREFIX
-
-foreign import ccall unsafe "iconv.h iconv_open" c_iconv_open
-    :: CString -> CString -> IO IConv
-
-foreign import ccall unsafe "iconv.h iconv_close" c_iconv_close
-    :: IConv -> IO CInt
-
-foreign import ccall unsafe "iconv.h iconv" c_iconv
-    :: IConv -> Ptr a -> Ptr CSize -> Ptr b -> Ptr CSize -> IO CSize
-
-#else
-
-foreign import ccall unsafe "iconv.h libiconv_open" c_iconv_open
-    :: CString -> CString -> IO IConv
-
-foreign import ccall unsafe "iconv.h libiconv_close" c_iconv_close
-    :: IConv -> IO CInt
-
-foreign import ccall unsafe "iconv.h libiconv" c_iconv
-    :: IConv -> Ptr a -> Ptr CSize -> Ptr b -> Ptr CSize -> IO CSize
-
-#endif
diff --git a/HSCurses/Logging.hs b/HSCurses/Logging.hs
deleted file mode 100644
--- a/HSCurses/Logging.hs
+++ /dev/null
@@ -1,70 +0,0 @@
-{-# OPTIONS -cpp -fno-cse #-}
-
--- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-module HSCurses.Logging (trace,debug) where
-
-import IO
-import Time
-import Locale
-import Data.IORef
-import System.IO.Unsafe             ( unsafePerformIO )
-import Control.Monad.Trans
-
-
-trace :: String -> a -> a
-debug :: MonadIO m => String -> m ()
-
-#ifdef __DEBUG__
-
-logFile :: Handle
-logFile = unsafePerformIO $ do h <- openFile ".hscurses.log" AppendMode
-                               debug_ h "logging initialized"
-                               return h
-{-# NOINLINE logFile #-}
-
-formatTime :: IO String
-formatTime =
-    do let fmt = "%Y-%m-%d %H:%M:%S"
-       clockT <- getClockTime
-       calTime <- toCalendarTime clockT
-       let maxSdecLen = 5
-           sdec' = show $ ctPicosec calTime
-           sdec = if length sdec' > maxSdecLen
-                     then take maxSdecLen sdec'
-                     else sdec'
-       return (formatCalendarTime defaultTimeLocale fmt calTime 
-               ++ ":" ++ sdec)
-
-trace s x = 
-    unsafePerformIO $ do debug s
-                         return x
-
-debug s = liftIO $ debug_ logFile s
-
-debug_ f s =
-    do ts <- formatTime
-       hPutStrLn f ("[" ++ ts ++ "] " ++ s)
-       hFlush f
-
-#else
-
-trace _ x = x
-
-debug s = return ()
-
-#endif
diff --git a/HSCurses/MonadException.hs b/HSCurses/MonadException.hs
deleted file mode 100644
--- a/HSCurses/MonadException.hs
+++ /dev/null
@@ -1,143 +0,0 @@
--- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-module HSCurses.MonadException where
-
-import Prelude hiding (catch)
-import Control.Exception
-import Control.Monad.State
-import Data.Typeable
-import Data.Dynamic
-
-class Monad m => MonadExc m where
-    catchM      :: m a -> (Exception -> m a) -> m a
-    blockM      :: m a -> m a
-    unblockM    :: m a -> m a
-
-
-class (MonadIO m, MonadExc m) => MonadExcIO m
-
---
--- Operations implemented in term of catchM, blockM and unblockM
--- (taken from Control.Exception).
---
-
-catchJustM :: MonadExc m =>
-       (Exception -> Maybe b) -- ^ Predicate to select exceptions
-    -> m a                    -- ^ Computation to run
-    -> (b -> m a)             -- ^ Handler
-    -> m a
-catchJustM p a handler = catchM a handler'
-  where handler' e = case p e of 
-            Nothing -> throw e
-            Just b  -> handler b
-
-handleM :: MonadExc m => (Exception -> m a) -> m a -> m a
-handleM = flip catchM
-
-handleJustM :: MonadExc m => 
-              (Exception -> Maybe b) -> (b -> m a) -> m a -> m a
-handleJustM p = flip (catchJustM p)
-
-tryM :: MonadExc m => m a -> m (Either Exception a)
-tryM a = catchM (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-
-tryJustM :: MonadExc m => (Exception -> Maybe b) -> m a -> m (Either b a)
-tryJustM p a = do
-  r <- tryM a
-  case r of
-    Right v -> return (Right v)
-    Left  e -> case p e of
-            Nothing -> throw e
-            Just b  -> return (Left b)
-
-catchDynM :: (MonadExc m, Typeable exc) => 
-             m a -> (exc -> m a) -> m a
-catchDynM m k = catchM m handle
-  where handle ex = case ex of
-               (DynException dyn) ->
-                case fromDynamic dyn of
-                    Just exception  -> k exception
-                    Nothing -> throw ex
-               _ -> throw ex
-
-bracketM :: MonadExc m =>
-       m a         -- ^ computation to run first (\"acquire resource\")
-    -> (a -> m b)  -- ^ computation to run last (\"release resource\")
-    -> (a -> m c)  -- ^ computation to run in-between
-    -> m c         -- returns the value from the in-between computation
-bracketM before after thing =
-  blockM (do
-    a <- before 
-    r <- catchM
-       (unblockM (thing a))
-       (\e -> do { after a; throw e })
-    after a
-    return r
-  )
-
-bracketM_ :: MonadExc m => m a -> m b -> m c -> m c
-bracketM_ before after thing = bracketM before (const after) (const thing)
-
-finally :: IO a -- ^ computation to run first
-    -> IO b     -- ^ computation to run afterward (even if an exception 
-                --   was raised)
-    -> IO a     -- returns the value from the first computation
-a `finally` sequel =
-  blockM (do
-    r <- catchM
-         (unblockM a)
-         (\e -> do { sequel; throw e })
-    sequel
-    return r
-  )
-
-
---
--- Instance declarations
---
-
-instance MonadExc IO where
-    catchM       = catch
-    blockM       = block
-    unblockM     = unblock
-
-instance MonadExcIO IO
-
-instance MonadExc m => MonadExc (StateT s m) where
-    catchM   = catchState
-    blockM   = blockState
-    unblockM = unblockState
-
-instance (MonadExc m, MonadIO m) => MonadExcIO (StateT s m)
-
-modifyState :: MonadExc m => (s -> m (a, s)) -> StateT s m a
-modifyState f = 
-    do oldState <- get
-       (x, newState) <- lift $ f oldState
-       put newState
-       return x
-
-catchState run handler =
-    modifyState (\oldState -> runStateT run oldState `catchM` 
-                              (\e -> runStateT (handler e) oldState))
-
-blockState run =
-    modifyState (\oldState -> blockM (runStateT run oldState))
-
-unblockState run =
-    modifyState (\oldState -> unblockM (runStateT run oldState))
-       
diff --git a/HSCurses/Widgets.hs b/HSCurses/Widgets.hs
deleted file mode 100644
--- a/HSCurses/Widgets.hs
+++ /dev/null
@@ -1,873 +0,0 @@
-{-# OPTIONS -fglasgow-exts #-}
--- glasgow-exts needed for existentials and multi-parameter type classes.
-
--- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
--- 
--- This library is free software; you can redistribute it and/or
--- modify it under the terms of the GNU Lesser General Public
--- License as published by the Free Software Foundation; either
--- version 2.1 of the License, or (at your option) any later version.
--- 
--- This library is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--- Lesser General Public License for more details.
--- 
--- You should have received a copy of the GNU Lesser General Public
--- License along with this library; if not, write to the Free Software
--- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-module HSCurses.Widgets where
-
-import Char
-import List
-import Maybe
-import qualified HSCurses.Curses as Curses
-import qualified HSCurses.CursesHelper as CursesH
-import HSCurses.Logging
-
-import Control.Monad.Trans
-import Control.Exception (assert)
-import HSCurses.MonadException
-
-type Pos = (Int, Int)
-type Offset = (Int, Int)
-
-type Size = (Int, -- height
-             Int  -- width
-            )
-
-getHeight :: Size -> Int
-getHeight = fst
-
-getWidth :: Size -> Int
-getWidth = snd
-
-getYOffset :: Offset -> Int
-getYOffset = fst
-
-getXOffset :: Offset -> Int
-getXOffset = snd
-
-getYPos :: Pos -> Int
-getYPos = fst
-
-getXPos :: Pos -> Int
-getXPos = snd
-
-data Direction = DirLeft | DirRight | DirUp | DirDown
-               deriving (Eq, Show, Ord)
-
-data HAlignment = AlignLeft | AlignCenter | AlignRight
-               deriving (Eq, Show)
-
-data Cont a = Cont a | Done a
-
-class Widget a where
-    draw      :: Pos -> Size -> DrawingHint -> a -> IO ()
-    minSize   :: a -> Size
-
-class Widget a => ActiveWidget a where
-    activate  :: MonadExcIO m => m () -> Pos -> Size -> a -> m (a, String)
-
-type KeyHandler a = Pos -> Size -> a -> IO (Cont a)
-
-mkKeyHandler :: (Pos -> Size -> a -> a)
-                -> KeyHandler a
-mkKeyHandler f pos sz w = return (Cont (f pos sz w))
-
---
--- Drawing
---
-
-data DrawingHint = DHNormal 
-                 | DHFocus
-                 | DHActive
-                   deriving (Eq, Show, Ord)
-
-data DrawingStyle = DStyle
-    { dstyle_normal      :: CursesH.CursesStyle
-    , dstyle_focus       :: CursesH.CursesStyle
-    , dstyle_active      :: CursesH.CursesStyle
-    } deriving (Eq, Show)
-
-
-mkDrawingStyle :: CursesH.CursesStyle -> DrawingStyle
-mkDrawingStyle defStyle = 
-    let revStyle = CursesH.changeCursesStyle defStyle [CursesH.Reverse]
-        in DStyle { dstyle_normal = defStyle
-                  , dstyle_focus = revStyle
-                  , dstyle_active = revStyle
-                  }
-
-defaultDrawingStyle = mkDrawingStyle CursesH.defaultCursesStyle
-_draw :: DrawingHint -> DrawingStyle -> IO a -> IO a
-_draw DHActive sty io = CursesH.withStyle (dstyle_active sty) io
-_draw DHNormal sty io = CursesH.withStyle (dstyle_normal sty) io
-_draw DHFocus sty io = CursesH.withStyle (dstyle_focus sty) io
-
---
--- Helper functions for scrolling
---
-
-scrollFactor = 0.8
-
-scrollBy :: Int -> Int
-scrollBy displayLen = 
-    let amount = floor ((fromInteger.toInteger) displayLen * scrollFactor)
-    in max (displayLen - 1) (min 1 amount)
-
--- returns the new offset for scrolling in forward direction
--- dataLen: total number of data items
--- offset: the index of the first data item shown on the current page
--- displayLen: the number of data items that is shown in one page
-scrollForward dataLen offset displayLen =
-    if offset + displayLen >= dataLen
-       then offset
-       else min (offset + scrollBy displayLen) (dataLen - displayLen)
-
--- returns the new offset for scrolling in backward direction.
--- parameters as for scrollForward
-scrollBackward dataLen offset displayLen = 
-    if offset == 0
-       then offset
-       else max (offset - scrollBy displayLen) 0
-
-
---
--- EmptyWidget
---
-
-data EmptyWidget = EmptyWidget Size
-
-instance Widget EmptyWidget where
-    draw _ _ _ _ = return ()
-    minSize (EmptyWidget sz) = sz
-
-
---
--- An opaque widget
---
-
-data OpaqueWidget = OpaqueWidget Size
-
-instance Widget OpaqueWidget where
-    draw pos@(y,x) sz@(h,w) _ _ = 
-        let draw' n =
-                do Curses.wMove Curses.stdScr (y+n) x
-                   CursesH.drawLine w ""
-        in do mapM draw' (take h [0..])
-              Curses.refresh
-    minSize (OpaqueWidget sz) = sz
-
---
--- Widget for text input
---
-
-data EditWidget = EditWidget
-    { ew_content       :: String,
-      ew_xoffset       :: Int, -- content!!xoffset is the 1st char shown
-      ew_xcursor       :: Int, -- cursor position
-      ew_history       :: [String],
-      ew_historyIndex  :: Int,
-      ew_historySavedContent :: Maybe String,
-      ew_options       :: EditWidgetOptions
-    }
-
-ew_contentPos ew = ew_xcursor ew + ew_xoffset ew
-
-instance Widget EditWidget where
-    draw = drawEditWidget
-    minSize ew = (1, ewopt_minWidth $ ew_options ew)
-
-instance ActiveWidget EditWidget where
-    activate = activateEditWidget
-
-data EditWidgetOptions = EWOptions
-    { ewopt_keyHandlers    :: [(Curses.Key, KeyHandler EditWidget)],
-      ewopt_minWidth       :: Int,
-      ewopt_style          :: DrawingStyle
-    }
-
-defaultEWOptions = EWOptions
-                   { ewopt_keyHandlers = editWidgetKeyHandlers,
-                     ewopt_minWidth = 8,
-                     ewopt_style = defaultDrawingStyle
-                   }
-
-newEditWidget :: EditWidgetOptions -> String -> EditWidget
-newEditWidget opts = 
-    editWidgetSetContent 
-      (EditWidget 
-       { ew_content = "",
-         ew_xoffset = 0,  
-         ew_xcursor = 0,
-         ew_history = [],
-         ew_historyIndex = -1,
-         ew_historySavedContent = Nothing,
-         ew_options = opts
-       })
-
-
-
-editWidgetGoLeft = mkKeyHandler editWidgetGoLeft'
-editWidgetGoRight = mkKeyHandler editWidgetGoRight'
-editWidgetDeleteLeft = mkKeyHandler editWidgetDeleteLeft'
-editWidgetDeleteUnderCursor = mkKeyHandler editWidgetDeleteUnderCursor'
-editWidgetDeleteToEnd = mkKeyHandler editWidgetDeleteToEnd'
-editWidgetGoHome = mkKeyHandler editWidgetGoHome'
-editWidgetGoEnd = mkKeyHandler editWidgetGoEnd'
-editWidgetHistoryUp = mkKeyHandler editWidgetHistoryUp'
-editWidgetHistoryDown = mkKeyHandler editWidgetHistoryDown'
-
-editWidgetKeyHandlers = 
-    [(Curses.KeyLeft, editWidgetGoLeft),
-     (Curses.KeyRight, editWidgetGoRight),
-     (Curses.KeyBackspace, editWidgetDeleteLeft),
-     (Curses.KeyChar '\^D', editWidgetDeleteUnderCursor),
-     (Curses.KeyDC, editWidgetDeleteUnderCursor),
-     (Curses.KeyChar '\^K', editWidgetDeleteToEnd),
-     (Curses.KeyHome, editWidgetGoHome),
-     (Curses.KeyChar '\^A', editWidgetGoHome),
-     (Curses.KeyEnd, editWidgetGoEnd),
-     (Curses.KeyChar '\^E', editWidgetGoEnd),
-     (Curses.KeyChar '\r', editWidgetFinish),
-     (Curses.KeyChar '\t', editWidgetFinish),
-     (Curses.KeyUp, editWidgetHistoryUp),
-     (Curses.KeyDown, editWidgetHistoryDown)
-    ]
-
-editWidgetGetContent ew = ew_content ew
-editWidgetSetContent ew s = 
-    addToHistory (ew { ew_content = s, ew_xoffset = 0, ew_xcursor = 0 }) s
-
-editWidgetGetOptions ew = ew_options ew
-editWidgetSetOptions ew opts = ew { ew_options = opts }
-
-drawEditWidget :: Pos -> Size -> DrawingHint -> EditWidget -> IO ()
-drawEditWidget (y, x) (height, width) hint ew = 
-    _draw hint (ewopt_style . ew_options $ ew) $
-    do Curses.wMove Curses.stdScr y x
-       CursesH.drawLine width (drop (ew_xoffset ew) $ ew_content ew)
-       Curses.refresh
-
-activateEditWidget :: MonadExcIO m => m () -> Pos -> Size 
-                   -> EditWidget -> m (EditWidget, String)
-activateEditWidget refresh pos@(y, x) sz@(height, width) ew =
-    CursesH.withCursor Curses.CursorVisible $ processKey ew
-    where 
-    processKey ew = 
-        do liftIO $ draw ew
-           k <- CursesH.getKey refresh
-           case lookup k (ewopt_keyHandlers $ ew_options ew) of
-             Nothing -> 
-                 case k of
-                   Curses.KeyChar c | isAscii c && isPrint c 
-                       -> processKey $ insertChar ew c
-                   _   -> processKey ew
-             Just f  ->
-                 do x <- liftIO $ f pos sz ew
-                    case x of
-                      Cont ew' -> processKey ew'
-                      Done ew' -> do liftIO $ drawEditWidget pos sz DHActive ew'
-                                     return (ew', editWidgetGetContent ew')
-    insertChar ew c = 
-        let pos = ew_contentPos ew
-            oldContent = ew_content ew
-            newContent = take pos oldContent ++ (c : drop pos oldContent)
-            in editWidgetGoRight' pos sz (ew { ew_content = newContent })
-    draw ew = _draw DHActive  (ewopt_style . ew_options $ ew) $
-        do Curses.wMove Curses.stdScr y x
-           CursesH.drawLine width (drop (ew_xoffset ew) $ ew_content ew)
-           Curses.wMove Curses.stdScr y (x + ew_xcursor ew)
-           Curses.refresh
-
-editWidgetGoLeft' _ _ ew = 
-    let newXcursor = max (ew_xcursor ew - 1) 0
-        newXoffset = if ew_xcursor ew == 0
-                        then max (ew_xoffset ew - 1) 0
-                        else ew_xoffset ew
-        in ew { ew_xoffset = newXoffset,
-                ew_xcursor = newXcursor }
-
-editWidgetGoRight' _ (_, width) ew =
-    let len = length (ew_content ew)
-        lastChar = len - ew_xoffset ew - 1
-        newXcursor = minimum [ew_xcursor ew + 1, lastChar + 1, width - 1]
-        newXoffset = if ew_xcursor ew == width - 1
-                        then min (ew_xoffset ew + 1) (len - width + 1)
-                        else ew_xoffset ew
-        in ew { ew_xoffset = newXoffset,
-                ew_xcursor = newXcursor }
-
-editWidgetDeleteLeft' :: Pos -> Size -> EditWidget -> EditWidget
-editWidgetDeleteLeft' pos sz ew = 
-    let cpos = ew_contentPos ew - 1
-        oldContent = ew_content ew
-        newContent = take cpos oldContent ++ drop (cpos+1) oldContent
-        ew' = editWidgetGoLeft' pos sz (ew { ew_content = newContent })
-        in if ew_xcursor ew == 0 && ew_xoffset ew /= 0
-              then editWidgetGoRight' pos sz (editWidgetGoLeft' pos sz ew')
-              else ew'
-
-editWidgetDeleteUnderCursor' _ _ ew = 
-    let pos = ew_contentPos ew
-        oldContent = ew_content ew
-        newContent = take pos oldContent ++ drop (pos+1) oldContent
-        in ew { ew_content = newContent }
-
-editWidgetDeleteToEnd' _ _ ew =
-    let pos = ew_contentPos ew
-        oldContent = ew_content ew
-        newContent = take pos oldContent
-        in ew { ew_content = newContent }
-
-editWidgetGoHome' _ _ ew =
-    ew { ew_xcursor = 0,
-         ew_xoffset = 0 }
-
-editWidgetGoEnd' :: Pos -> Size -> EditWidget -> EditWidget
-editWidgetGoEnd' pos sz ew =
-    let cpos = ew_contentPos ew
-        len = length (ew_content ew)
-        in if cpos == len
-              then ew
-              else editWidgetGoEnd' pos sz (editWidgetGoRight' pos sz ew)
-
-editWidgetFinish _ _ ew =  return (Done (addToHistory ew (ew_content ew)))
-
-maxHistoryLength = 50
-
-addToHistory ew s = 
-    let newHist = if not (null s)
-                     then take maxHistoryLength (s : ew_history ew)
-                     else ew_history ew
-        in ew { ew_history = newHist, ew_historyIndex = -1,
-                ew_historySavedContent = Nothing }
-
-editWidgetHistoryUp' _ _ ew = editWidgetHistory (+) ew
-editWidgetHistoryDown' _ _ ew = editWidgetHistory (-) ew
-
--- ew_historyList: list of history items, i.e. non-null strings which were 
---   entered into the widget and confirmed with ENTER or which were added
---   via editWidgetSetContent.
--- ew_historyIndex: the index of the history item shown in the widget. The
---   value -1 means that the value saved in ew_historySavedContent should
---   be shown.
-editWidgetHistory op ew = 
-    let i = ew_historyIndex ew
-        l = ew_history ew
-        j =  i `op` 1
-        in if j >= 0 && j < length l
-              then let savedContent =
-                           case ew_historySavedContent ew of
-                             Nothing -> Just (ew_content ew)
-                             x -> x
-                       in ew { ew_historyIndex = j, ew_content = l!!j,
-                               ew_historySavedContent = savedContent,
-                               ew_xcursor = 0, ew_xoffset = 0 }
-              else if j == -1
-                      then case ew_historySavedContent ew of
-                             Nothing -> ew
-                             Just x -> ew { ew_content = x, 
-                                            ew_historyIndex = j,
-                                            ew_xcursor = 0, 
-                                            ew_xoffset = 0  }
-                   else ew
-
-
-
---
--- Text widget
---
-
-data TextWidget = TextWidget
-    { tw_text           :: String,
-      tw_yoffset        :: Int,
-      tw_xoffset        :: Int,
-      tw_options        :: TextWidgetOptions
-    }
-    deriving (Eq, Show)
-
-instance Widget TextWidget where
-    draw = drawTextWidget
-    minSize tw = 
-        case twopt_size $ tw_options tw of
-          TWSizeDefault -> let l = lines (tw_text tw)
-                           in (length l, if null l then 0 else maximum (map length l))
-          TWSizeFixed sz -> sz
-
-data TextWidgetSize = TWSizeDefault    -- minimal size determined by content
-                    | TWSizeFixed Size -- minimal size is fixed, content is
-                                       -- possibly cut off
-                      deriving (Eq, Show)
-                                 {-
-                    | Autowrap   -- minimal width determined by content,
-                                 -- but lines are wrapped if necessary
-                                 -}            
-      
-data TextWidgetOptions = TWOptions
-    { twopt_size   :: TextWidgetSize,
-      twopt_style  :: DrawingStyle,
-      twopt_halign :: HAlignment }  
-    deriving (Eq, Show)
-
-defaultTWOptions = TWOptions
-                { twopt_size = TWSizeDefault,
-                  twopt_style = defaultDrawingStyle,
-                  twopt_halign = AlignLeft }
-
-newTextWidget :: TextWidgetOptions -> String -> TextWidget
-newTextWidget opts s = TextWidget 
-                       { tw_text = s,
-                         tw_yoffset = 0,
-                         tw_xoffset = 0,
-                         tw_options = opts
-                       }
-
-drawTextWidget :: Pos -> Size -> DrawingHint -> TextWidget -> IO ()
-drawTextWidget pos@(y, x) sz@(height, width) hint tw = 
-    let ly = take height $ drop (tw_yoffset tw) (lines (tw_text tw))
-        l = take height $ (map (drop (tw_xoffset tw)) ly ++ repeat [])
-        l' = map (align (twopt_halign $ tw_options tw) width ' ') l
-    in --trace ("drawing text widget at " ++ show pos ++ " with size " ++ show sz) $
-       do _draw hint (twopt_style . tw_options $ tw) 
-                      (mapM drawLine $ zip l' [0..])
-          Curses.refresh
-    where drawLine (s, i) = 
-              do Curses.wMove Curses.stdScr (y + i) x
-                 CursesH.drawLine width s
-
-textWidgetGetText :: TextWidget -> String
-textWidgetGetText = tw_text
-
-textWidgetSetText :: TextWidget -> String -> TextWidget
-textWidgetSetText tw s = tw { tw_text = s }
-
-textWidgetScrollDown :: Size -> TextWidget -> TextWidget
-textWidgetScrollDown (h, _) tw =
-    let dataLen = length $ lines (tw_text tw)
-        offset = tw_yoffset tw
-        in tw { tw_yoffset = scrollForward dataLen offset h }
-
-textWidgetScrollUp :: Size -> TextWidget -> TextWidget
-textWidgetScrollUp (h, _) tw = 
-    let dataLen = length $ lines (tw_text tw)
-        offset = tw_yoffset tw
-        in tw { tw_yoffset = scrollBackward dataLen offset h }
-
-textWidgetScrollLeft :: Size -> TextWidget -> TextWidget
-textWidgetScrollLeft (_, w) tw = 
-    let dataLen = length $ lines (tw_text tw)
-        offset = tw_xoffset tw
-        in tw { tw_xoffset = scrollBackward dataLen offset w }
-
-textWidgetScrollRight :: Size -> TextWidget -> TextWidget
-textWidgetScrollRight (_, w) tw =
-    let dataLen = length $ lines (tw_text tw)
-        offset = tw_xoffset tw
-        in tw { tw_xoffset = scrollForward dataLen offset w }
-
-
---
--- Table widget
---
-
-data TableCell = forall w. Widget w => TableCell w
-               | forall w. ActiveWidget w => ActiveTableCell w
-
-isActive :: TableCell -> Bool
-isActive (TableCell _) = False
-isActive (ActiveTableCell _) = True
-
-instance Widget TableCell where
-    draw pos sz hint (TableCell w) = draw pos sz hint w
-    draw pos sz hint (ActiveTableCell w) = draw pos sz hint w
-    minSize (TableCell w) = minSize w
-    minSize (ActiveTableCell w) = minSize w
-
-_activateTableCell :: MonadExcIO m => m () -> Pos -> Size 
-                   -> TableCell -> m (TableCell, String)
-_activateTableCell _ _ _ (TableCell _) = 
-    error "_activateTableCell: cannot activate non-active cell!"
-_activateTableCell refresh pos sz (ActiveTableCell w) =
-    do (new, res) <- activate refresh pos sz w
-       return (ActiveTableCell new, res)
-
-type Row = [TableCell]
-
-singletonRow :: TableCell -> Row
-singletonRow tc = [tc]
-
-getCellWidget :: TableWidget -> (Int, Int) -> TableCell
-getCellWidget tbw (row, col) = (tbw_rows tbw) !! row !! col
-
-setCellWidget :: TableWidget -> (Int, Int) -> TableCell -> TableWidget
-setCellWidget tbw (rowIndex, colIndex) w =
-    let rows = tbw_rows tbw
-        row = rows !! rowIndex
-        newRow = listReplace row w colIndex
-        newRows = listReplace rows newRow rowIndex
-        in tbw { tbw_rows = newRows }
-
-data TableWidget = TableWidget
-    { tbw_rows     :: [Row],
-      tbw_colOffset  :: Int,
-      tbw_pos      :: Maybe Pos,
-      tbw_options  :: TableWidgetOptions }
-                     
-data FillRow = First | Last | None deriving (Eq,Show)
-
-data TableWidgetOptions = TBWOptions
-    { tbwopt_fillCol    :: Maybe Int,
-      tbwopt_fillRow    :: FillRow,
-      tbwopt_activeCols :: [Int],
-      tbwopt_minSize    :: Size }
-    deriving (Eq, Show)
-
-defaultTBWOptions = TBWOptions
-                    { tbwopt_fillCol = Nothing,
-                      tbwopt_fillRow = None,
-                      tbwopt_activeCols = [],
-                      tbwopt_minSize = (4, 10) }
-
-instance Widget TableWidget where
-    draw      = drawTableWidget
-    minSize   = tbwopt_minSize . tbw_options  
-
-newTableWidget :: TableWidgetOptions -> [Row] -> TableWidget
-newTableWidget opts rows = TableWidget
-                              { tbw_rows = rows,
-                                tbw_colOffset = 0,
-                                tbw_pos = findFirstActiveCell rows opts,
-                                tbw_options = opts }
-
-data TableWidgetDisplayInfo = 
-    TBWDisplayInfo
-    { tbwdisp_height     :: Int   -- height of the display area
-    , tbwdisp_width      :: Int   -- width of the display area
-    , tbwdisp_firstVis   :: Int   -- index of the first row visible
-    , tbwdisp_lastVis    :: Int   -- index of the last row visible
-    , tbwdisp_rows       :: [Row] -- the rows which are visible
-    , tbwdisp_nrows      :: Int   -- the number of rows visible
-    , tbwdisp_heights    :: [Int] -- the heights of the visible rows
-    , tbwdisp_widths     :: [Int] -- the widths of the visible rows
-      -- free space at the right side (xoffset, size)
-    , tbwdisp_rightMargin :: Maybe (Int, Size) 
-    }
-
-tableWidgetDisplayInfo :: Size -> TableWidget -> TableWidgetDisplayInfo
-tableWidgetDisplayInfo sz@(height, width) tbw = 
-    assert (isQuadratic (tbw_rows tbw)) $
-    let allRows = tbw_rows tbw
-        ncols = length (allRows!!0)
-        colOffset = tbw_colOffset tbw
-        allHeights = minSpaces getHeight allRows
-        heights' = drop colOffset allHeights
-        nrows = getNRows heights' 0 0
-        rows = take nrows $ drop colOffset allRows
-        (heights, heightDummy) = 
-            let hs = take nrows heights'
-                s = sum hs
-                d = height - s
-                in case tbwopt_fillRow $ tbw_options tbw of
-                     First -> (applyToFirst (+d) hs, 0)
-                     Last -> (applyToLast (+d) hs, 0)
-                     None -> (hs, d)
-        widths' = minSpaces getWidth (transpose $ tbw_rows tbw)
-        (widths, rightMargin) = 
-            if sum widths' > width 
-               then error ("table to wide: width=" ++ show (sum widths') ++
-                           ", available width=" ++ show width)
-               else case tbwopt_fillCol $ tbw_options tbw of
-                      Just i | i >= 0 && i < ncols
-                                 -> (take i widths' ++ 
-                                     let rest = drop i widths'
-                                     in (head rest + width - sum widths') : tail rest
-                                    , Nothing)
-                      _ -> let diff = width - sum widths'
-                               msz = (height, diff)
-                               m = if diff > 0 then Just (sum widths', msz) 
-                                   else Nothing
-                           in (widths', m)
-        dummyHeights = if heightDummy == 0 then [] else [heightDummy]
-        dummyRows = if heightDummy == 0 then [] 
-                    else [map (\w -> TableCell (OpaqueWidget (heightDummy, w))) 
-                          widths]
-        in TBWDisplayInfo
-               { tbwdisp_height = height
-               , tbwdisp_width = width
-               , tbwdisp_firstVis = colOffset
-               , tbwdisp_lastVis = colOffset + nrows - 1
-               , tbwdisp_rows = rows ++ dummyRows
-               , tbwdisp_nrows = nrows + length dummyRows
-               , tbwdisp_heights = heights ++ dummyHeights
-               , tbwdisp_widths = widths
-               , tbwdisp_rightMargin = rightMargin
-               }
-    where
-        minSpaces f ls = 
-            snd $ mapAccumL 
-                    (\acc ws -> 
-                       (acc, acc + maximum (map (f . minSize) ws)))
-                    0 ls
-        getNRows (h:hs) n acc | h + n <= height = getNRows hs (h+n) (acc+1)
-        getNRows _ _ acc = acc
-        isQuadratic [] = True
-        isQuadratic (x:xs) = isQuadratic' xs (length x)
-        isQuadratic' (x:xs) n = length x == n && isQuadratic' xs n
-        isQuadratic' [] _ = True
-        applyToFirst f [] = []
-        applyToFirst f (x:xs) = f x : xs
-        applyToLast f [] = []
-        applyToLast f l = 
-            let (h, t) = (head $ reverse l, tail $ reverse l)
-                in reverse $ f h : t
-
-getCellInfo :: Pos -> Size -> TableWidget -> (Int,Int) -> (Pos, Size)
-getCellInfo pos@(y,x) sz tbw (row, col) = 
-    let info = tableWidgetDisplayInfo sz tbw
-        heights = tbwdisp_heights info
-        widths = tbwdisp_widths info
-        h = heights !! row
-        w = widths !! col
-        yoff = sum $ take row heights
-        xoff = sum $ take col widths
-        in ((y+yoff, x+xoff), (h, w))
-
-drawTableWidget :: Pos -> Size -> DrawingHint -> TableWidget -> IO ()
-drawTableWidget pos@(y, x) sz hint tbw = 
-    let info = tableWidgetDisplayInfo sz tbw
-        heights = tbwdisp_heights info
-        widths = tbwdisp_widths info
-        firstVis = tbwdisp_firstVis info
-        rows = tbwdisp_rows info
-        rightMargin = tbwdisp_rightMargin info
-        in do drawRows rows heights widths 0 firstVis hint
-              case rightMargin of
-                Nothing -> return ()
-                Just (xoff,s) -> draw (y,x+xoff) s hint (OpaqueWidget s)
-              Curses.refresh
-    where drawRows :: [Row] -> [Int] -> [Int] -> Int -> Int 
-                   -> DrawingHint -> IO ()
-          drawRows [] _ _ _ _ _ = return ()
-          drawRows (r:rs) (h:hs) widths yoffset rowIndex hint = 
-            do drawCols r h widths yoffset 0 (rowIndex, 0) hint
-               drawRows rs hs widths (yoffset + h) (rowIndex + 1) hint
-          drawCols :: Row -> Int -> [Int] -> Int -> Int -> (Int, Int) 
-                   -> DrawingHint -> IO ()
-          drawCols [] _ _ _ _ _ _ = return ()
-          drawCols (c:cs) h (w:ws) yoffset xoffset (rowIndex, colIndex) hint = 
-            let hint' = case tbw_pos tbw of
-                           Just (y, x) | y == rowIndex && x == colIndex
-                               -> DHFocus
-                           _ -> hint
-            in do draw (y+yoffset, x+xoffset) (h,w) hint' c
-                  drawCols cs h ws yoffset (xoffset + w) 
-                           (rowIndex, colIndex+1) hint
-
-
-tableWidgetScrollDown :: Size -> TableWidget -> TableWidget
-tableWidgetScrollDown (h, _) tbw =
-    let dataLen = length $ tbw_rows tbw
-        offset = tbw_colOffset tbw
-        newOffset = scrollForward dataLen offset h
-        newTbw = tbw { tbw_colOffset = newOffset }
-        in case tbw_pos newTbw of
-             Nothing -> newTbw
-             Just (y,x) -> newTbw { tbw_pos = Just (max newOffset y, x) }
-
-tableWidgetScrollUp :: Size -> TableWidget -> TableWidget
-tableWidgetScrollUp sz@(h,_) tbw =  
-    let dataLen = length $ tbw_rows tbw
-        offset = tbw_colOffset tbw
-        newOffset = scrollBackward dataLen offset h
-        newTbw = tbw { tbw_colOffset = newOffset }
-        newLastVis = tbwdisp_lastVis (tableWidgetDisplayInfo sz newTbw)
-        in case tbw_pos newTbw of
-             Nothing -> newTbw
-             Just (y,x) -> 
-                 newTbw { tbw_pos = Just (min newLastVis y, x) }
-
-tableWidgetActivateCurrent :: MonadExcIO m => m () -> Pos -> Size 
-                           -> DrawingHint -> TableWidget 
-                           -> m (TableWidget, Maybe String)
-tableWidgetActivateCurrent refresh pos@(y, x) sz hint tbw = 
-    case tbw_pos tbw of
-      Nothing -> do debug "tableWidgetActivateCurrent: pos=Nothing"
-                    return (tbw, Nothing)
-      Just p -> let w = getCellWidget tbw p
-                    in if not $ isActive w
-                       then do debug "tableWidgetActivateCurrent: not active"
-                               return (tbw, Nothing)
-                       else activate w p
-    where 
-    activate widget colyx@(coly, colx) =
-        let info = tableWidgetDisplayInfo sz tbw
-            vcol = colx
-            vrow = coly - tbwdisp_firstVis info
-            heights = tbwdisp_heights info
-            widths = tbwdisp_widths info
-            h = heights !! vrow
-            w = widths !! vcol
-            yoffset = sum (take vrow heights)
-            xoffset = sum (take vcol widths)
-        in do (new, res) <- _activateTableCell refresh (y+yoffset, x+xoffset) 
-                              (h, w) widget
-              return (setCellWidget tbw colyx new, Just res)
-
-tableWidgetGoLeft :: Size -> TableWidget -> TableWidget
-tableWidgetGoLeft =  tableWidgetMove DirLeft
-
-tableWidgetGoRight :: Size -> TableWidget -> TableWidget
-tableWidgetGoRight =  tableWidgetMove DirRight
-
-tableWidgetGoUp :: Size -> TableWidget -> TableWidget
-tableWidgetGoUp =  tableWidgetMove DirUp
-
-tableWidgetGoDown :: Size -> TableWidget -> TableWidget
-tableWidgetGoDown =  tableWidgetMove DirDown
-
-tableWidgetMove dir sz tbw = 
-    let pos = tbw_pos tbw
-        opts = tbw_options tbw
-        nrows = length (tbw_rows tbw)
-        in case pos of
-             Nothing -> tbw
-             Just p -> case findNextActiveCell opts nrows p dir of
-                         Nothing -> tbw
-                         newP@(Just (y, _)) ->
-                             tableWidgetMakeVisible (tbw {tbw_pos=newP}) sz y
-
-tableWidgetMakeVisible tbw sz@(height,_) y = 
-    let info = tableWidgetDisplayInfo sz tbw
-        firstVis = tbwdisp_firstVis info
-        lastVis = tbwdisp_lastVis info
-        in if y < firstVis
-              then tableWidgetMakeVisible (tableWidgetScrollUp sz tbw) sz y
-              else if y > lastVis
-                      then tableWidgetMakeVisible 
-                               (tableWidgetScrollDown sz tbw) sz y
-                      else tbw
-
-findFirstActiveCell :: [Row] -> TableWidgetOptions -> Maybe Pos
-findFirstActiveCell rows opts = 
-    let nrows = length rows
-        firstActiveCells = map (\y -> findNextActiveCell opts nrows 
-                                                         (y, -1) DirRight)
-                               [0..nrows-1]
-        in case catMaybes firstActiveCells of
-             [] -> Nothing
-             (x:_) -> Just x
-
-findNextActiveCell :: TableWidgetOptions -> Int  -> Pos -> Direction 
-                   -> Maybe Pos
-findNextActiveCell opts nrows pos@(y,x) dir = 
---    trace ("findNextActiveCell (opts=" ++ show opts ++ ", nrows=" ++ show nrows
---           ++ ", pos=" ++ show pos ++ ", dir=" ++ show dir) $
-    let rows = [0..(nrows - 1)]
-        cols = sort (tbwopt_activeCols opts)
-        horiz f = case f cols x rows y of
-                    Nothing -> Nothing
-                    Just x -> Just (y, x)
-        vert f = case f rows y cols x of
-                   Nothing -> Nothing
-                   Just y -> Just (y, x)
-        res = case dir of
-                DirLeft-> horiz goLeft
-                DirRight -> horiz goRight
-                DirUp -> vert goLeft
-                DirDown -> vert goRight
-        in --trace ("result of findNextActiveCell: " ++ show res) 
-           res
-    where goLeft _ _ rows y | not (y `elem` rows) = Nothing
-          goLeft cols x _ _ = 
-              case reverse (takeWhile (<x) cols) of
-                [] -> Nothing
-                (x:_) -> Just x
-          goRight _ _ rows y | not (y `elem` rows) = Nothing
-          goRight cols x _ _ = 
-              case dropWhile (x>=) cols of
-                [] -> Nothing
-                (x:_) -> Just x
-
-tableWidgetDeleteRow :: Int -> TableWidget -> TableWidget
-tableWidgetDeleteRow n tbw = 
-    let rows = tbw_rows tbw
-        rows' = deleteAt n rows
-        pos' = 
-           case tbw_pos tbw of
-             Nothing -> Nothing
-             Just (row,col) -> 
-                 let row' = min row (length rows' - 1)
-                     in if row' >= 0 then Just (row', col)
-                        else Nothing
-        in tbw { tbw_rows = rows', tbw_pos = pos' }
-
---
--- BorderWidget
---
-
-
---
--- Selection Widget
---
-
---
--- Utility functions
---
-
--- | Join a list by some delimiter
-joinLists :: [[a]] -> [a] -> [a]
-joinLists l s = if (null l) then [] else foldr1 (\x -> \y -> x ++ s ++ y) l
-
--- | Split a list by some delimiter
-splitList :: Eq a => [a] -> [a] -> [[a]]
-splitList d l =
-    unfoldr (\x -> if (null x) 
-                      then Nothing 
-                      else Just $ nextToken d [] (snd $ splitAt (length d) x))
-            (d++l)
-  where nextToken _ r [] = (r, [])
-        nextToken d r l@(h:t) | (d `isPrefixOf` l) = (r, l) 
-                              | otherwise = nextToken d (r++[h]) t
-
-listReplace :: [a] -> a -> Int -> [a]
-listReplace l a i = 
-    case splitAt i l of
-      (_, []) -> error ("listReplace: index to large. index="++show i++
-                        ", length="++show (length l))
-      ([], _) | i < 0 -> error ("listReplace: negative index. index="++
-                                show i)
-      (xs,(y:ys)) -> xs ++ (a:ys)
-
---alignRows :: [[String]] -> Char -> String -> [String]
-alignRows :: [[[a]]] -> a -> [a] -> [[a]]
-alignRows rows fill delim = 
-    let widths = foldr maxWidths (repeat 0) rows
-        in map (alignRow widths) rows
-    where
-    maxWidths ::  [[a]] -> [Int] -> [Int]
-    maxWidths row acc = map (uncurry max) (zip acc (map length row))
-    alignRow widths row = concatMap (uncurry alignCell) (zip widths row)
-    alignCell width cell = 
-        let diff = width - length cell
-            in cell ++ (take diff $ repeat fill) ++ delim
-
-        
-align :: HAlignment -> Int -> a -> [a] -> [a]
-align a w f l = 
-    let space = w - length l
-        in case a of
-             AlignLeft -> l ++ (fill space)
-             AlignRight -> (fill space) ++ l        
-             AlignCenter ->
-                 let left = space `div` 2
-                     right = left + (space `mod` 2)
-                     in fill left ++ l ++ fill right
-    where fill n = take n (repeat f)
-
-deleteAt :: Int -> [a] -> [a]
-deleteAt n l = if n >= 0 && n < length l 
-                  then let (a,b) = splitAt n l in a ++ (tail b)
-                  else error ("deleteAt: illegal index: " ++ show n)
diff --git a/Makefile b/Makefile
deleted file mode 100644
--- a/Makefile
+++ /dev/null
@@ -1,48 +0,0 @@
-TOPDIR = .
-
-# way = p
-# HCFLAGS = -D__DEBUG__
-
-include $(TOPDIR)/mk/config.mk
-
-# this rule must remain first
-default: boot lib
-
-ALL_DIRS = cbits HSCurses
-
-PKG      = hscurses
-LIBRARY  = libhscurses$(_way).a
-LIBOBJS  = $(OBJS)
-
-INSTALL_HEADERS = $(wildcard cbits/*.h)
-
-include $(TOPDIR)/mk/rules.mk
-
-.PHONY: srcdist
-srcdist:
-	@DIST=hscurses-ds-`date +%Y%m%d`; \
-	CHANGELOG=CHANGELOG.$$DIST; \
-	if [ -e $$DIST ] ; then echo "$$DIST already exists"; exit 1; fi; \
-	darcs dist -d $$DIST > /dev/null && \
-	gunzip $$DIST.tar.gz && \
-	tar --delete --file=$$DIST.tar $$DIST/boring && \
-	mkdir $$DIST && \
-	darcs changes | sed 's/[[:alnum:].]*@[[:alnum:].]*/(Email address hidden)/g' > $$DIST/$$CHANGELOG && \
-	tar --append --file=$$DIST.tar $$DIST/$$CHANGELOG && \
-	mv $$DIST/$$CHANGELOG $$CHANGELOG && \
-	rm -rf $$DIST && \
-	gzip $$DIST.tar && \
-	md5sum $$DIST.tar.gz > $$DIST.md5 && \
-	echo "created dist as $$DIST.tar.gz"
-
-CLEAN_FILES+=$(wildcard hscurses-ds-*.tar.gz hscurses-ds-*.md5 CHANGELOG.hscurses-ds-*)
-# Dependency orders
-ifeq ($(MAKECMDGOALS),clean)
-#empty
-else
-ifeq ($(MAKECMDGOALS),distclean)
-#empty
-else
-include $(TOPDIR)/depend
-endif
-endif
diff --git a/README b/README
--- a/README
+++ b/README
@@ -1,22 +1,21 @@
-               hscurses -- A Haskell Binding to NCurses
+               hscurses -- A Haskell Binding to ncurses
                =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
 
-hscurses is a Haskell binding to the NCurses library, a library of
+hscurses is a Haskell binding to the ncurses library, a library of
 functions that manage an application's display on character-cell
 terminals. hscurses also provides some basic widgets implemented on
 top of the ncurses binding, such as a text input widget and a table
 widget.
 
-The hscurses library has been reported to work on Linux x86 and on
-OpenBSD using GHC 6.2, 6.4, 6.6, 6.6.1, 6.8.2.
+The hscurses library has been reported to work on Linux x86 using GHC 6.8.2.
 
-Building and installing the hscurses library with GHC 6.6
+Building and installing the hscurses library with GHC 6.8
 ---------------------------------------------------------
 
 Requirements:
 
 - GNU m4
-- GHC >= 6.6
+- GHC >= 6.8
 - ncurses
 
 Build and installation steps:
@@ -30,34 +29,6 @@
 
   runhaskell Setup.hs haddock
 
-
-Building and installing the hscurses library with GHC 6.2 and 6.4
------------------------------------------------------------------
-
-Requirements:
-
-- GNU make
-- GNU m4
-- GHC >= 6.2
-- ncurses
-
-Build and installation steps:
-
-  sh configure
-  make
-  make doc          # if you want to build the API documentation
-  make install      # probably as root
-
-  make register     # probably as root
-OR
-  make user-register  # don't need to be root
-
-In order to generate the API documentation, you need haddock
-(http://www.haskell.org/haddock). The command is then:
-
-  make doc          # result goes to ./html
-
-
 Using the hscurses library:
 ---------------------------
 
@@ -65,15 +36,13 @@
 moment, user documentation is only available through Haddock API
 documentation.
 
-
 Copyright:
 ----------
 
-   John Meacham <john at repetae dot net>, 2002-2004.
-   Tuomo Valkonen <tuomov at iki.fi>, 2004.
+   John Meacham <john @ repetae . net>, 2002-2004.
+   Tuomo Valkonen <tuomov @ iki.fi>, 2004.
    Don Stewart <http://www.cse.unsw.edu.au/~dons>, 2004.
    Stefan Wehr <http://www.stefanwehr.de>, 2004-2005.
-
 
 History:
 --------
diff --git a/Setup.hs b/Setup.hs
--- a/Setup.hs
+++ b/Setup.hs
@@ -1,2 +1,2 @@
 import Distribution.Simple
-main = defaultMainWithHooks defaultUserHooks
+main = defaultMainWithHooks simpleUserHooks
diff --git a/UI/HSCurses/CWString.hsc b/UI/HSCurses/CWString.hsc
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/CWString.hsc
@@ -0,0 +1,387 @@
+-- Copyright (c) 2002-2004 John Meacham (john at repetae dot net)
+-- Copyright (c) 2004      Don Stewart - http://www.cse.unsw.edu.au/~dons
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+module UI.HSCurses.CWString (
+
+    -- * utf8 versions
+    withUTF8String,
+    withUTF8StringLen,
+    newUTF8String,
+    newUTF8StringLen,
+    peekUTF8String,
+    peekUTF8StringLen,
+
+    -- * WChar stuff
+#ifdef HAVE_WCHAR_H
+    withCWString,
+    withCWStringLen,
+    newCWString,
+    newCWStringLen,
+    peekCWString,
+    peekCWStringLen,
+    wcharIsUnicode,
+    CWChar,
+    CWString,
+    CWStringLen,
+#endif
+    -- * Locale versions
+    withLCString,
+    withLCStringLen,
+    newLCString,
+    newLCStringLen,
+    peekLCStringLen,
+    peekLCString,
+--  charIsRepresentable
+
+    ) where
+
+import Data.Char            ( ord, chr )
+import Data.Bits            ( Bits((.|.), (.&.), shift) )
+import Foreign.C.String
+
+#if __GLASGOW_HASKELL__ < 603
+import GHC.Exts
+#endif
+
+#ifdef HAVE_WCHAR_H
+
+import Foreign.C.Types
+
+#include <wchar.h>
+#include <limits.h>
+#include <stdlib.h>
+
+type CWChar = (#type wchar_t)
+type CWString = Ptr CWChar
+type CWStringLen = (CWString, Int)
+
+fi :: (Integral a, Num b) => a -> b
+fi x = fromIntegral x
+
+-------------------
+-- CWChar functions
+-------------------
+
+{-# INLINE wcharIsUnicode #-}
+wcharIsUnicode :: Bool
+
+#if defined(__STDC_ISO_10646__)
+
+wcharIsUnicode = True
+
+-- support functions
+wNUL :: CWChar
+wNUL = 0
+#ifndef __GLASGOW_HASKELL__
+pairLength :: String -> CString -> CStringLen
+pairLength  = flip (,) . length
+
+cwCharsToChars :: [CWChar] -> [Char]
+cwCharsToChars xs  = map castCWCharToChar xs
+charsToCWChars :: [Char] -> [CWChar]
+charsToCWChars xs  = map castCharToCWChar xs
+
+#endif
+-- __STDC_ISO_10646__
+
+castCWCharToChar :: CWChar -> Char
+castCWCharToChar ch = chr (fromIntegral ch )
+
+castCharToCWChar :: Char -> CWChar
+castCharToCWChar ch = fromIntegral (ord ch)
+
+-- exported functions
+peekCWString    :: CWString -> IO String
+#ifndef __GLASGOW_HASKELL__
+peekCString cp  = do cs <- peekArray0 wNUL cp; return (cwCharsToChars cs)
+#else
+peekCWString cp = loop 0
+  where
+    loop i = do
+        val <- peekElemOff cp i
+        if val == wNUL then return [] else do
+            rest <- loop (i+1)
+            return (castCWCharToChar val : rest)
+#endif
+
+peekCWStringLen           :: CWStringLen -> IO String
+#ifndef __GLASGOW_HASKELL__
+peekCWStringLen (cp, len)  = do cs <- peekArray len cp; return (cwCharsToChars cs)
+#else
+peekCWStringLen (cp, len) = loop 0
+  where
+    loop i | i == len  = return []
+           | otherwise = do
+                val <- peekElemOff cp i
+                rest <- loop (i+1)
+                return (castCWCharToChar val : rest)
+#endif
+
+newCWString :: String -> IO CWString
+#ifndef __GLASGOW_HASKELL__
+newCWString  = newArray0 wNUL . charsToCWChars
+#else
+newCWString str = do
+  ptr <- mallocArray0 (length str)
+  let
+        go [] n##   = pokeElemOff ptr (I## n##) wNUL
+        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
+  go str 0##
+  return ptr
+#endif
+
+newCWStringLen     :: String -> IO CWStringLen
+#ifndef __GLASGOW_HASKELL__
+newCWStringLen str  = do a <- newArray (charsToCWChars str)
+                        return (pairLength str a)
+#else
+newCWStringLen str = do
+  ptr <- mallocArray0 len
+  let
+        go [] _       = return ()
+        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
+  go str 0##
+  return (ptr, len)
+  where
+    len = length str
+#endif
+
+withCWString :: String -> (CWString -> IO a) -> IO a
+#ifndef __GLASGOW_HASKELL__
+withCWString  = withArray0 wNUL . charsToCWChars
+#else
+withCWString str f =
+  allocaArray0 (length str) $ \ptr ->
+      let
+        go [] n##     = pokeElemOff ptr (I## n##) wNUL
+        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
+      in do
+      go str 0##
+      f ptr
+#endif
+
+withCWStringLen         :: String -> (CWStringLen -> IO a) -> IO a
+#ifndef __GLASGOW_HASKELL__
+withCWStringLen str act  = withArray (charsToCWChars str) $ act . pairLength str
+#else
+withCWStringLen str f =
+  allocaArray len $ \ptr ->
+      let
+        go [] _       = return ()
+        go (c:cs) n## = do pokeElemOff ptr (I## n##) (castCharToCWChar c); go cs (n## +## 1##)
+      in do
+      go str 0##
+      f (ptr,len)
+  where
+    len = length str
+#endif
+
+
+#else
+-- no __STDC_ISO_10646__
+wcharIsUnicode = False
+#endif
+
+newtype MBState = MBState { _mbstate :: (Ptr MBState)}
+
+withMBState :: (MBState -> IO a) -> IO a
+withMBState act = allocaBytes (#const sizeof(mbstate_t)) (\mb -> c_memset mb 0 (#const sizeof(mbstate_t)) >> act (MBState mb))
+
+clearMBState :: MBState -> IO ()
+clearMBState (MBState mb) = c_memset mb 0 (#const sizeof(mbstate_t)) >> return ()
+
+wcsrtombs :: CWString -> (CString, CSize) -> IO CSize
+wcsrtombs wcs (cs,len) =
+    alloca (\p ->
+        poke p wcs >> withMBState (\mb ->
+            wcsrtombs' p cs len mb))
+    where
+        wcsrtombs'  p cs' len' mb = do
+            x <- c_wcsrtombs cs p len' mb
+            case x of
+                -1 -> do
+                    sp <- peek p
+                    poke sp ((fi (ord '?'))::CWChar)
+                    poke p wcs
+                    clearMBState mb
+                    wcsrtombs' p cs' len' mb
+                e | e >= 0 && e <= len' -> do
+                    let ep = advancePtr cs' (fi e)
+                    poke ep (fi (0::Int))
+                    return x
+                e -> error $ "HSCurses.CWString.wcsrtombs: impossible case: "++show e
+
+#def inline HsInt hs_get_mb_cur_max () { return MB_CUR_MAX; }
+foreign import ccall unsafe hs_get_mb_cur_max :: IO Int
+
+mb_cur_max :: Int
+mb_cur_max = unsafePerformIO hs_get_mb_cur_max
+
+{-
+charIsRepresentable :: Char -> IO Bool
+charIsRepresentable ch = fmap (/= -1) $ allocaBytes mb_cur_max (\cs -> c_wctomb cs (fi $ ord ch))
+-}
+
+{-
+foreign import ccall unsafe "stdlib.h wctomb" c_wctomb :: CString -> CWChar -> IO CInt
+-}
+
+foreign import ccall unsafe "stdlib.h wcsrtombs"
+        c_wcsrtombs :: CString -> (Ptr (Ptr CWChar)) -> CSize -> MBState -> IO CSize
+
+foreign import ccall unsafe "string.h memset"
+        c_memset :: Ptr a -> CInt -> CSize -> IO (Ptr a)
+
+foreign import ccall unsafe "stdlib.h mbstowcs"
+        c_mbstowcs :: CWString -> CString -> CSize -> IO CSize
+
+mbstowcs :: CWString
+         -> Foreign.C.String.CString
+         -> Foreign.C.Types.CSize -> IO Foreign.C.Types.CSize
+
+mbstowcs a b s = throwIf (== -1) (const "mbstowcs") $ c_mbstowcs a b s
+
+peekLCString    :: CString -> IO String
+peekLCString cp  = do
+    sz <- mbstowcs nullPtr cp 0
+    allocaArray (fi $ sz + 1) (\wcp -> mbstowcs wcp cp (sz + 1) >> peekCWString wcp)
+
+-- TODO fix for embeded NULs
+peekLCStringLen           :: CStringLen -> IO String
+peekLCStringLen (cp, len)  =  allocaBytes (len + 1) $ \ncp -> do
+    copyBytes ncp cp len
+    pokeElemOff ncp len 0
+    peekLCString ncp
+
+newLCString :: String -> IO CString
+newLCString s =
+    withCWString s $ \wcs -> do
+        cs <- mallocArray0 alen
+        wcsrtombs wcs (cs, fi alen)
+        return cs
+
+    where alen = mb_cur_max * length s
+
+newLCStringLen     :: String -> IO CStringLen
+newLCStringLen str  = newLCString str >>= \cs -> return (pairLength1 str cs)
+
+withLCString :: String -> (CString -> IO a) -> IO a
+withLCString s a =
+    withCWString s $ \wcs ->
+        allocaArray0 alen $ \cs ->
+            wcsrtombs wcs (cs,fi alen) >> a cs
+
+    where alen = mb_cur_max * length s
+
+withLCStringLen :: String -> (CStringLen -> IO a) -> IO a
+withLCStringLen s a =
+    withCWString s $ \wcs ->
+        allocaArray0 alen $ \cs -> do
+            sz <- wcsrtombs wcs (cs,fi alen)
+            a (cs,fi sz)
+
+    where alen = mb_cur_max * length s
+
+pairLength1 :: String -> CString -> CStringLen
+pairLength1  = flip (,) . length
+
+#else
+-- -----------------------------------------------------------
+-- no CF_WCHAR_SUPPORT (OpenBSD)
+
+{-
+charIsRepresentable :: Char -> IO Bool
+charIsRepresentable ch = return $ isLatin1 ch
+-}
+
+withLCString :: String -> (Foreign.C.String.CString -> IO a) -> IO a
+withLCString = withCString
+
+withLCStringLen  :: String -> (Foreign.C.String.CStringLen -> IO a) -> IO a
+withLCStringLen = withCStringLen
+
+newLCString :: String -> IO Foreign.C.String.CString
+newLCString = newCString
+
+newLCStringLen :: String -> IO Foreign.C.String.CStringLen
+newLCStringLen = newCStringLen
+
+peekLCString :: Foreign.C.String.CString -> IO String
+peekLCString = peekCString
+
+peekLCStringLen :: Foreign.C.String.CStringLen -> IO String
+peekLCStringLen = peekCStringLen
+
+#endif
+-- no CF_WCHAR_SUPPORT
+
+-----------------
+-- UTF8 versions
+-----------------
+
+withUTF8String :: String -> (CString -> IO a) -> IO a
+withUTF8String hsStr = withCString (toUTF hsStr)
+
+withUTF8StringLen :: String -> (CStringLen -> IO a) -> IO a
+withUTF8StringLen hsStr = withCStringLen (toUTF hsStr)
+
+newUTF8String :: String -> IO CString
+newUTF8String = newCString . toUTF
+
+newUTF8StringLen :: String -> IO CStringLen
+newUTF8StringLen = newCStringLen . toUTF
+
+peekUTF8String :: CString -> IO String
+peekUTF8String strPtr = fmap fromUTF $ peekCString strPtr
+
+peekUTF8StringLen :: CStringLen -> IO String
+peekUTF8StringLen strPtr = fmap fromUTF $ peekCStringLen strPtr
+
+-- these should read and write directly from/to memory.
+-- A first pass will be needed to determine the size of the allocated region
+
+toUTF :: String -> String
+toUTF [] = []
+toUTF (x:xs) | ord x<=0x007F = x:toUTF xs
+             | ord x<=0x07FF = chr (0xC0 .|. ((ord x `shift` (-6)) .&. 0x1F)):
+                               chr (0x80 .|. (ord x .&. 0x3F)):
+                               toUTF xs
+             | otherwise     = chr (0xE0 .|. ((ord x `shift` (-12)) .&. 0x0F)):
+                               chr (0x80 .|. ((ord x `shift` (-6)) .&. 0x3F)):
+                               chr (0x80 .|. (ord x .&. 0x3F)):
+                               toUTF xs
+
+fromUTF :: String -> String
+fromUTF [] = []
+fromUTF (al@(x:xs)) | ord x<=0x7F = x:fromUTF xs
+                     | ord x<=0xBF = err
+                     | ord x<=0xDF = twoBytes al
+                     | ord x<=0xEF = threeBytes al
+                     | otherwise   = err
+  where
+    twoBytes (x1:x2:xs') = chr (((ord x1 .&. 0x1F) `shift` 6) .|.
+                               (ord x2 .&. 0x3F)):fromUTF xs'
+    twoBytes _ = error "fromUTF: illegal two byte sequence"
+
+    threeBytes (x1:x2:x3:xs') = chr (((ord x1 .&. 0x0F) `shift` 12) .|.
+                                    ((ord x2 .&. 0x3F) `shift` 6) .|.
+                                    (ord x3 .&. 0x3F)):fromUTF xs'
+    threeBytes _ = error "fromUTF: illegal three byte sequence"
+
+    err = error "fromUTF: illegal UTF-8 character"
+
diff --git a/UI/HSCurses/Curses.hsc b/UI/HSCurses/Curses.hsc
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/Curses.hsc
@@ -0,0 +1,1450 @@
+{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}
+-- glaexts needed for newtype deriving
+
+-- Copyright (c) 2002-2004 John Meacham (john at repetae dot net)
+-- Copyright (c) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
+-- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+
+--
+-- | Binding to the [wn]curses library. From the ncurses man page:
+--
+-- >      The curses library routines give the user a terminal-inde-
+-- >      pendent method of updating character screens with  reason-
+-- >      able  optimization.
+--
+-- Sections of the quoted documentation are from the OpenBSD man pages, which
+-- are distributed under a BSD license.
+--
+-- A useful reference is:
+--        /Writing Programs with NCURSES/, by Eric S. Raymond and Zeyd
+--        M. Ben-Halim, <http://dickey.his.com/ncurses/>
+--
+-- N.B attrs don't work with Irix curses.h. This should be fixed.
+--
+
+module UI.HSCurses.Curses (
+
+    -- * Basic Functions
+    stdScr,             -- :: Window
+    initScr,            -- :: IO Window
+    initCurses,         -- :: IO ()
+    resetParams,
+    endWin,             -- :: IO ()
+    scrSize,            -- :: IO (Int, Int)
+
+    -- * Windows and Pads
+    Window,             -- data Window deriving Eq
+    touchWin,
+    newPad, pRefresh, delWin, newWin,
+
+    -- * Refresh Routines
+    refresh,            -- :: IO ()
+    update,
+    resizeTerminal,
+    timeout,            -- :: Int -> IO ()
+    noqiflush,           -- :: IO ()
+
+    -- * Navigation
+    move,               -- :: Int -> Int -> IO ()
+    getYX,
+
+    -- * Input
+    getCh, getch, decodeKey, ungetCh, keyResizeCode,
+
+    -- * Input Options
+    cBreak,             -- :: Bool -> IO ()
+    raw,                -- :: Bool -> IO ()
+    echo,               -- :: Bool -> IO ()
+    intrFlush,          -- :: Bool -> IO ()
+    keypad,             -- :: Window -> Bool -> IO ()
+    noDelay,            -- :: Window -> Bool -> IO ()
+
+    -- * Output
+    wAddStr,       -- :: Window -> String -> IO ()
+    addLn,         -- :: IO ()
+    mvWAddStr,
+    mvAddCh,       -- :: Int -> Int -> ChType -> IO ()
+    wMove,
+    bkgrndSet,     -- :: Attr -> Pair -> IO ()
+    erase,         -- :: IO ()
+    wclear,        -- :: Window -> IO ()
+    clrToEol,      -- :: IO ()
+    wClrToEol,
+    beep,
+    waddch,
+    waddchnstr,    -- :: Window -> CString -> CInt -> IO CInt
+
+    -- * Output Options
+    clearOk,
+    leaveOk,
+    nl,                 -- :: Bool -> IO ()
+
+    -- * Cursor Routines
+    CursorVisibility(..), cursSet,
+
+    -- * Color Support
+    hasColors,      -- :: IO Bool
+    startColor,     -- :: IO ()
+    useDefaultColors,   -- :: IO ()
+    Pair(..),       -- newtype Pair = Pair Int deriving (Eq, Ord, Ix)
+    colorPairs,     -- :: IO Int
+    Color(..),      -- newtype Color = Color Int deriving (Eq, Ord, Ix)
+    colors,         -- :: IO Int
+    color,          -- :: String -> Maybe Color
+--    black, red, green, yellow, blue, magenta, cyan, white, -- :: Color
+    initPair,       -- :: Pair -> Color -> Color -> IO ()
+    pairContent,    -- :: Pair -> IO (Color, Color)
+    canChangeColor, -- :: IO Bool
+    initColor,      -- :: Color -> (Int, Int, Int) -> IO ()
+    colorContent,   -- :: Color -> IO (Int, Int, Int)
+    defaultBackground, defaultForeground,
+
+    -- * Attributes
+    attrPlus,
+    Attr,
+    attr0, -- :: Attr
+
+    isAltCharset, isBlink, isBold, isDim, isHorizontal, isInvis,
+    isLeft, isLow, isProtect, isReverse, isRight, isStandout, isTop,
+    isUnderline, isVertical,
+        -- :: Attr -> Bool
+
+    setAltCharset, setBlink, setBold, setDim, setHorizontal, setInvis,
+    setLeft, setLow, setProtect, setReverse, setRight, setStandout,
+    setTop, setUnderline, setVertical,
+        -- :: Attr -> Bool -> Attr
+
+    attrSet, -- :: Attr -> Pair -> IO ()
+    attrOn, attrOff,
+
+    standout,standend,
+    attrDim, attrBold,
+    attrDimOn, attrDimOff,
+    attrBoldOn, attrBoldOff,
+    wAttrOn,
+    wAttrOff,
+    wAttrSet, wAttrGet,
+
+    -- * Mouse Routines
+    withMouseEventMask,
+    ButtonEvent(..),
+    MouseEvent(..),
+
+    -- * Keys
+    Key(..),
+    cERR,
+    cKEY_UP,
+    cKEY_DOWN,
+    cKEY_LEFT,
+    cKEY_RIGHT,
+    cTRUE,
+--    cACS_BLOCK,
+
+    -- * Lines
+    vline,
+    ulCorner, llCorner, urCorner, lrCorner, rTee, lTee, bTee, tTee, hLine,
+    vLine, plus, s1, s9, diamond, ckBoard, degree, plMinus, bullet,
+    lArrow, rArrow, dArrow, uArrow, board, lantern, block,
+    s3, s7, lEqual, gEqual, pi, nEqual, sterling,
+
+    -- * Signals
+    cursesSigWinch,
+
+    -- * Misc
+    cursesTest,
+    throwIfErr, throwIfErr_,
+    errI,       -- :: IO CInt -> IO ()
+    flushinp,
+    recognize,
+    ChType,
+    NBool
+
+  ) where
+
+#include <ghcconfig.h>
+#include <HSCurses.h>
+
+#if HAVE_SIGNAL_H
+# include <signal.h>
+#endif
+
+import UI.HSCurses.CWString       ( withLCStringLen )
+import UI.HSCurses.Logging
+
+import Prelude hiding           ( pi )
+import Data.Char
+import Data.List
+import Data.Ix                  ( Ix )
+
+import Control.Monad
+import Control.Monad.Trans
+import Control.Concurrent
+import Control.Concurrent.Chan
+
+import Foreign
+import Foreign.C.String
+import Foreign.C.Types
+import Foreign.C.Error
+import System.Posix.Signals
+
+#if __GLASGOW_HASKELL__ < 603
+import Data.Bits
+#endif
+
+
+------------------------------------------------------------------------
+--
+-- | @initCurses fn@ does all initialization necessary for a Curses
+--   application.
+--
+initCurses :: IO ()
+initCurses = do
+    initScr
+    b <- hasColors
+    when b $ startColor >> useDefaultColors
+
+resetParams :: IO ()
+resetParams = do
+    raw True    -- raw mode please
+    echo False
+    nl False
+    intrFlush True
+    leaveOk False
+    keypad stdScr True
+    defineKey (#const KEY_UP) "\x1b[1;2A"
+    defineKey (#const KEY_DOWN) "\x1b[1;2B"
+    defineKey (#const KEY_SLEFT) "\x1b[1;2D"
+    defineKey (#const KEY_SRIGHT) "\x1b[1;2C"
+
+------------------------------------------------------------------------
+
+fi :: (Integral a, Num b) => a -> b
+fi = fromIntegral
+
+throwIfErr :: Num a => String -> IO a -> IO a
+--throwIfErr name act = do
+--    res <- act
+--    if res == (cERR)
+--        then ioError (userError ("Curses: "++name++" failed"))
+--        else return res
+throwIfErr s = throwIf (== (#const ERR)) (\a -> "Curses[" ++ show a ++ "]:"  ++ s)
+
+throwIfErr_ :: Num a => String -> IO a -> IO ()
+throwIfErr_ name act = void $ throwIfErr name act
+
+errI :: IO CInt -> IO ()
+errI f = do r <- f
+            if r == cERR then do _ <- endwin
+                                 error "curses returned an error"
+             else return ()
+
+------------------------------------------------------------------------
+
+type WindowTag = ()
+type Window = Ptr WindowTag
+type ChType = #type chtype
+type NBool = #type bool
+
+
+--
+-- | The standard screen
+--
+stdScr :: Window
+stdScr = unsafePerformIO (peek stdscr)
+foreign import ccall "static HSCurses.h &stdscr"
+    stdscr :: Ptr Window
+
+--
+-- | initscr is normally the first curses routine to call when
+-- initializing a program. curs_initscr(3):
+--
+-- >     To initialize the routines, the routine initscr or newterm
+-- >     must be called before any of the other routines that  deal
+-- >     with  windows  and  screens  are used.
+--
+-- >     The initscr code determines the terminal type and initial-
+-- >     izes all curses data structures.  initscr also causes  the
+-- >     first  call  to  refresh  to  clear the screen.  If errors
+-- >     occur, initscr writes  an  appropriate  error  message  to
+-- >     standard error and exits; otherwise, a pointer is returned
+-- >     to stdscr.
+--
+initScr :: IO Window
+initScr = throwIfNull "initscr" initscr
+foreign import ccall unsafe "HSCurses.h initscr" initscr :: IO Window
+
+--
+-- | > The cbreak routine
+--   > disables line buffering and erase/kill  character-process-
+--   > ing  (interrupt  and  flow  control  characters  are unaf-
+--   > fected), making characters typed by the  user  immediately
+--   > available  to  the  program.  The nocbreak routine returns
+--   > the terminal to normal (cooked) mode.
+--
+cBreak :: Bool -> IO ()
+cBreak True  = throwIfErr_ "cbreak"   cbreak
+cBreak False = throwIfErr_ "nocbreak" nocbreak
+
+foreign import ccall unsafe "HSCurses.h cbreak"     cbreak :: IO CInt
+foreign import ccall unsafe "HSCurses.h nocbreak" nocbreak :: IO CInt
+
+--
+-- |>    The  raw and noraw routines place the terminal into or out
+-- >     of raw mode.  Raw mode is similar to cbreak mode, in  that
+-- >     characters  typed  are  immediately  passed through to the
+-- >     user program.  The differences are that in raw  mode,  the
+-- >     interrupt,  quit, suspend, and flow control characters are
+-- >     all passed through uninterpreted, instead of generating  a
+-- >     signal.   The  behavior  of the BREAK key depends on other
+-- >     bits in the tty driver that are not set by curses.
+--
+raw :: Bool -> IO ()
+raw False = throwIfErr_ "noraw" noraw
+raw True  = throwIfErr_ "raw"   raw_c
+
+foreign import ccall unsafe "HSCurses.h noraw" noraw :: IO CInt
+foreign import ccall unsafe "HSCurses.h raw"   raw_c :: IO CInt
+
+--
+-- |>      The  echo  and  noecho routines control whether characters
+-- >       typed by the user are echoed by getch as they  are  typed.
+-- >       Echoing  by  the  tty  driver is always disabled, but ini-
+-- >       tially getch is in echo  mode,  so  characters  typed  are
+-- >       echoed.  Authors of most interactive programs prefer to do
+-- >       their own echoing in a controlled area of the  screen,  or
+-- >       not  to  echo  at  all, so they disable echoing by calling
+-- >       noecho.  [See curs_getch(3) for a discussion of how  these
+-- >       routines interact with cbreak and nocbreak.]
+-- >
+--
+echo :: Bool -> IO ()
+echo False = throwIfErr_ "noecho" noecho
+echo True  = throwIfErr_ "echo"   echo_c
+
+foreign import ccall unsafe "HSCurses.h noecho" noecho :: IO CInt
+foreign import ccall unsafe "HSCurses.h echo" echo_c :: IO CInt
+
+--
+-- |>       The  nl  and  nonl routines control whether the underlying
+-- >        display device translates the return key into  newline  on
+-- >        input,  and  whether it translates newline into return and
+-- >        line-feed on output (in either case, the call  addch('\n')
+-- >        does the equivalent of return and line feed on the virtual
+-- >        screen).  Initially, these translations do occur.  If  you
+-- >        disable  them using nonl, curses will be able to make bet-
+-- >        ter use of the line-feed capability, resulting  in  faster
+-- >        cursor  motion.   Also, curses will then be able to detect
+-- >        the return key.
+-- >
+nl :: Bool -> IO ()
+nl True  = throwIfErr_ "nl"   nl_c
+nl False = throwIfErr_ "nonl" nonl
+
+foreign import ccall unsafe "HSCurses.h nl" nl_c :: IO CInt
+foreign import ccall unsafe "HSCurses.h nonl" nonl :: IO CInt
+
+-- |>       If  the intrflush option is enabled, (bf is TRUE), when an
+-- >        interrupt key  is  pressed  on  the  keyboard  (interrupt,
+-- >        break,  quit)  all  output in the tty driver queue will be
+-- >        flushed, giving the  effect  of  faster  response  to  the
+-- >        interrupt,  but  causing  curses to have the wrong idea of
+-- >        what is on the  screen.   Disabling  (bf  is  FALSE),  the
+-- >        option  prevents the flush.
+-- >
+intrFlush :: Bool -> IO ()
+intrFlush bf =
+    throwIfErr_ "intrflush" $ intrflush stdScr (if bf then 1 else 0)
+foreign import ccall unsafe "HSCurses.h intrflush" intrflush :: Window -> (#type bool) -> IO CInt
+
+--
+-- | Enable the keypad of the user's terminal.
+--
+keypad :: Window -> Bool -> IO ()
+keypad win bf = throwIfErr_ "keypad" $ keypad_c win (if bf then 1 else 0)
+foreign import ccall unsafe "HSCurses.h keypad"
+    keypad_c :: Window -> (#type bool) -> IO CInt
+
+noDelay :: Window -> Bool -> IO ()
+noDelay win bf =
+    throwIfErr_ "nodelay" $ nodelay win (if bf then 1 else 0)
+
+foreign import ccall unsafe "HSCurses.h nodelay"
+    nodelay :: Window -> (#type bool) -> IO CInt
+
+--
+-- |   Normally, the hardware cursor is left at the  location  of
+--     the  window  cursor  being  refreshed.  The leaveok option
+--     allows the cursor to be left wherever the  update  happens
+--     to leave it.  It is useful for applications where the cur-
+--     sor is not used, since it  reduces  the  need  for  cursor
+--     motions.   If  possible, the cursor is made invisible when
+--     this option is enabled.
+--
+leaveOk  :: Bool -> IO CInt
+leaveOk True  = leaveok_c stdScr 1
+leaveOk False = leaveok_c stdScr 0
+
+foreign import ccall unsafe "HSCurses.h leaveok"
+    leaveok_c :: Window -> (#type bool) -> IO CInt
+
+clearOk :: Bool -> IO CInt
+clearOk True  = clearok_c stdScr 1
+clearOk False = clearok_c stdScr 0
+
+foreign import ccall unsafe "HSCurses.h clearok"
+    clearok_c :: Window -> (#type bool) -> IO CInt
+
+------------------------------------------------------------------------
+
+foreign import ccall unsafe "HSCurses.h use_default_colors"
+    useDefaultColors :: IO ()
+
+defaultBackground, defaultForeground :: Color
+defaultBackground = Color (-1)
+defaultForeground = Color (-1)
+
+------------------------------------------------------------------------
+
+defineKey :: CInt -> String -> IO ()
+defineKey k s =  withCString s (\s' -> define_key s' k) >> return ()
+
+foreign import ccall unsafe "HSCurses.h define_key"
+    define_key :: Ptr CChar -> CInt -> IO ()
+
+--
+-- | >  The program must call endwin for each terminal being used before
+--   >  exiting from curses.
+--
+endWin :: IO ()
+endWin = throwIfErr_ "endwin" endwin
+foreign import ccall unsafe "HSCurses.h endwin" endwin :: IO CInt
+
+------------------------------------------------------------------------
+
+--
+-- | get the dimensions of the screen
+--
+scrSize :: IO (Int, Int)
+scrSize = do
+    lnes <- peek linesPtr
+    cols <- peek colsPtr
+    return (fromIntegral lnes, fromIntegral cols)
+
+foreign import ccall "HSCurses.h &LINES" linesPtr :: Ptr CInt
+foreign import ccall "HSCurses.h &COLS"  colsPtr  :: Ptr CInt
+
+--
+-- | refresh curses windows and lines. curs_refresh(3)
+--
+refresh :: IO ()
+refresh = throwIfErr_ "refresh" refresh_c
+
+foreign import ccall unsafe "HSCurses.h refresh"
+    refresh_c :: IO CInt
+
+--
+-- | Do an actual update. Used after endWin on linux to restore the terminal
+--
+update :: IO ()
+update = throwIfErr_ "update" update_c
+
+foreign import ccall unsafe "HSCurses.h doupdate" update_c :: IO CInt
+
+foreign import ccall unsafe "static curses.h timeout" timeout_c :: CInt -> IO ()
+
+-- | Set a delay in milliseconds.
+timeout :: Int -> IO ()
+timeout = timeout_c . fromIntegral
+
+------------------------------------------------------------------------
+
+hasColors :: IO Bool
+hasColors = liftM (/= 0) has_colors
+foreign import ccall unsafe "HSCurses.h has_colors" has_colors :: IO (#type bool)
+
+--
+-- | Initialise the color settings, also sets the screen to the
+-- default colors (white on black)
+--
+startColor :: IO ()
+startColor = throwIfErr_ "start_color" start_color
+foreign import ccall unsafe start_color :: IO CInt
+
+newtype Pair = Pair Int deriving (Eq, Ord, Ix, Show)
+
+--
+-- | colorPairs defines the maximum number of color-pairs the terminal
+-- can support).
+--
+colorPairs :: IO Int
+colorPairs = fmap fromIntegral $ peek colorPairsPtr
+
+foreign import ccall "HSCurses.h &COLOR_PAIRS"
+        colorPairsPtr :: Ptr CInt
+
+newtype Color = Color Int deriving (Eq, Ord, Ix)
+
+colors :: IO Int
+colors = liftM fromIntegral $ peek colorsPtr
+
+foreign import ccall "HSCurses.h &COLORS" colorsPtr :: Ptr CInt
+
+--black, red, green, yellow, blue, magenta, cyan, white :: Color
+
+color :: String -> Maybe Color
+color "default"  = Just $ Color (-1)
+color "black"    = Just $ Color (#const COLOR_BLACK)
+color "red"      = Just $ Color (#const COLOR_RED)
+color "green"    = Just $ Color (#const COLOR_GREEN)
+color "yellow"   = Just $ Color (#const COLOR_YELLOW)
+color "blue"     = Just $ Color (#const COLOR_BLUE)
+color "magenta"  = Just $ Color (#const COLOR_MAGENTA)
+color "cyan"     = Just $ Color (#const COLOR_CYAN)
+color "white"    = Just $ Color (#const COLOR_WHITE)
+color _ =  Nothing
+
+
+--
+-- |   curses support color attributes  on  terminals  with  that
+--     capability.   To  use  these  routines start_color must be
+--     called, usually right after initscr.   Colors  are  always
+--     used  in pairs (referred to as color-pairs).  A color-pair
+--     consists of a foreground  color  (for  characters)  and  a
+--     background color (for the blank field on which the charac-
+--     ters are displayed).  A programmer  initializes  a  color-
+--     pair  with  the routine init_pair.  After it has been ini-
+--     tialized, COLOR_PAIR(n), a macro  defined  in  <curses.h>,
+--     can be used as a new video attribute.
+--
+--     If  a  terminal  is capable of redefining colors, the pro-
+--     grammer can use the routine init_color to change the defi-
+--     nition   of   a   color.
+--
+--     The init_pair routine changes the definition of  a  color-
+--     pair.   It takes three arguments: the number of the color-
+--     pair to be changed, the foreground color number,  and  the
+--     background color number.  For portable applications:
+--
+--     -    The value of the first argument must be between 1 and
+--          COLOR_PAIRS-1.
+--
+--     -    The value of the second and third arguments  must  be
+--          between  0  and  COLORS (the 0 color pair is wired to
+--          white on black and cannot be changed).
+--
+--
+initPair :: Pair -> Color -> Color -> IO ()
+initPair (Pair p) (Color f) (Color b) =
+    throwIfErr_ "init_pair" $
+        init_pair (fromIntegral p) (fromIntegral f) (fromIntegral b)
+
+foreign import ccall unsafe
+    init_pair :: CShort -> CShort -> CShort -> IO CInt
+
+
+pairContent :: Pair -> IO (Color, Color)
+pairContent (Pair p) =
+    alloca $ \fPtr ->
+    alloca $ \bPtr -> do
+        throwIfErr "pair_content" $ pair_content (fromIntegral p) fPtr bPtr
+        f <- peek fPtr
+        b <- peek bPtr
+        return (Color (fromIntegral f), Color (fromIntegral b))
+
+foreign import ccall unsafe pair_content :: CShort -> Ptr CShort -> Ptr CShort -> IO CInt
+
+canChangeColor :: IO Bool
+canChangeColor = liftM (/= 0) can_change_color
+
+foreign import ccall unsafe can_change_color :: IO (#type bool)
+
+initColor :: Color -> (Int, Int, Int) -> IO ()
+initColor (Color c) (r, g, b) =
+    throwIfErr_ "init_color" $
+        init_color (fromIntegral c) (fromIntegral r) (fromIntegral g) (fromIntegral b)
+foreign import ccall unsafe init_color :: CShort -> CShort -> CShort -> CShort -> IO CInt
+
+colorContent :: Color -> IO (Int, Int, Int)
+colorContent (Color c) =
+    alloca $ \rPtr ->
+    alloca $ \gPtr ->
+    alloca $ \bPtr -> do
+        throwIfErr "color_content" $ color_content (fromIntegral c) rPtr gPtr bPtr
+        r <- peek rPtr
+        g <- peek gPtr
+        b <- peek bPtr
+        return (fromIntegral r, fromIntegral g, fromIntegral b)
+
+foreign import ccall unsafe
+    color_content :: CShort -> Ptr CShort -> Ptr CShort -> Ptr CShort -> IO CInt
+
+foreign import ccall unsafe "HSCurses.h hs_curses_color_pair" colorPair :: Pair -> ChType
+#def inline chtype hs_curses_color_pair (HsInt pair) {return COLOR_PAIR (pair);}
+
+-------------
+-- Attributes
+-------------
+
+foreign import ccall unsafe "HSCurses.h attr_set"
+    attr_set :: Attr -> CShort -> Ptr a -> IO Int
+
+-- foreign import ccall unsafe "HSCurses.h attr_get" :: Attr -> CShort -> Ptr a -> IO Int
+
+foreign import ccall unsafe "HSCurses.h wattr_set"
+    wattr_set :: Window -> Attr -> CInt -> Ptr a -> IO CInt
+
+foreign import ccall unsafe "HSCurses.h wattr_get"
+    wattr_get :: Window -> Ptr Attr -> Ptr CShort -> Ptr a -> IO CInt
+
+foreign import ccall "HSCurses.h attr_on" attr_on :: (#type attr_t) -> Ptr a -> IO Int
+foreign import ccall "HSCurses.h attr_off" attr_off :: (#type attr_t) -> Ptr a -> IO Int
+foreign import ccall "HSCurses.h attron" attron :: Int -> IO Int
+foreign import ccall "HSCurses.h attroff" attroff :: Int -> IO Int
+foreign import ccall unsafe "HSCurses.h wattron" wattron :: Window -> CInt -> IO CInt
+foreign import ccall unsafe "HSCurses.h wattroff" wattroff :: Window -> CInt -> IO CInt
+foreign import ccall standout :: IO Int
+foreign import ccall standend :: IO Int
+
+--
+-- |
+--
+wAttrSet :: Window -> (Attr,Pair) -> IO ()
+wAttrSet w (a,(Pair p)) = throwIfErr_ "wattr_set" $
+    wattr_set w a (fromIntegral p) nullPtr
+
+--
+-- | manipulate the current attributes of the named window. see curs_attr(3)
+--
+wAttrGet :: Window -> IO (Attr,Pair)
+wAttrGet w =
+    alloca $ \pa ->
+        alloca $ \pp -> do
+            throwIfErr_ "wattr_get" $ wattr_get w pa pp nullPtr
+            a <- peek pa
+            p <- peek pp
+            return (a,Pair $ fromIntegral p)
+
+
+newtype Attr = Attr (#type attr_t) deriving (Eq,Storable,Bits, Num, Show)
+
+--
+-- | Normal display (no highlight)
+--
+attr0 :: Attr
+attr0 = Attr (#const WA_NORMAL)
+
+isAltCharset, isBlink, isBold, isDim, isHorizontal, isInvis, isLeft,
+    isLow, isProtect, isReverse, isRight, isStandout, isTop,
+    isUnderline, isVertical :: Attr -> Bool
+
+isAltCharset = isAttr (#const WA_ALTCHARSET)
+isBlink      = isAttr (#const WA_BLINK)
+isBold       = isAttr (#const WA_BOLD)
+isDim        = isAttr (#const WA_DIM)
+isHorizontal = isAttr (#const WA_HORIZONTAL)
+isInvis      = isAttr (#const WA_INVIS)
+isLeft       = isAttr (#const WA_LEFT)
+isLow        = isAttr (#const WA_LOW)
+isProtect    = isAttr (#const WA_PROTECT)
+isReverse    = isAttr (#const WA_REVERSE)
+isRight      = isAttr (#const WA_RIGHT)
+isStandout   = isAttr (#const WA_STANDOUT)
+isTop        = isAttr (#const WA_TOP)
+isUnderline  = isAttr (#const WA_UNDERLINE)
+isVertical   = isAttr (#const WA_VERTICAL)
+
+isAttr :: (#type attr_t) -> Attr -> Bool
+isAttr b (Attr a) = a .&. b /= 0
+
+--
+-- | Setting attributes
+--
+setAltCharset, setBlink, setBold, setDim, setHorizontal, setInvis,
+    setLeft, setLow, setProtect, setReverse, setRight, setStandout,
+    setTop, setUnderline, setVertical :: Attr -> Bool -> Attr
+
+setAltCharset = setAttr (#const WA_ALTCHARSET)
+setBlink      = setAttr (#const WA_BLINK)
+setBold       = setAttr (#const WA_BOLD)
+setDim        = setAttr (#const WA_DIM)
+setHorizontal = setAttr (#const WA_HORIZONTAL)
+setInvis      = setAttr (#const WA_INVIS)
+setLeft       = setAttr (#const WA_LEFT)
+setLow        = setAttr (#const WA_LOW)
+setProtect    = setAttr (#const WA_PROTECT)
+setReverse    = setAttr (#const WA_REVERSE)
+setRight      = setAttr (#const WA_RIGHT)
+setStandout   = setAttr (#const WA_STANDOUT)
+setTop        = setAttr (#const WA_TOP)
+setUnderline  = setAttr (#const WA_UNDERLINE)
+setVertical   = setAttr (#const WA_VERTICAL)
+
+setAttr :: (#type attr_t) -> Attr -> Bool -> Attr
+setAttr b (Attr a) False = Attr (a .&. complement b)
+setAttr b (Attr a) True  = Attr (a .|.            b)
+
+attrPlus :: Attr -> Attr -> Attr
+attrPlus (Attr a) (Attr b) = Attr (a .|. b)
+
+attrSet :: Attr -> Pair -> IO ()
+attrSet attr (Pair p) = throwIfErr_ "attrset" $
+    attr_set attr (fromIntegral p) nullPtr
+
+attrOn :: Attr -> IO ()
+attrOn (Attr attr) = throwIfErr_ "attr_on" $
+    attr_on attr nullPtr
+
+
+attrOff :: Attr -> IO ()
+attrOff (Attr attr) = throwIfErr_ "attr_off" $
+    attr_off attr nullPtr
+
+
+
+wAttrOn :: Window -> Int -> IO ()
+wAttrOn w x = throwIfErr_ "wattron" $ wattron w (fi x)
+
+wAttrOff :: Window -> Int -> IO ()
+wAttrOff w x = throwIfErr_ "wattroff" $ wattroff w (fi x)
+
+attrDimOn :: IO ()
+attrDimOn  = throwIfErr_ "attron A_DIM" $
+    attron (#const A_DIM)
+
+attrDimOff :: IO ()
+attrDimOff = throwIfErr_ "attroff A_DIM" $
+    attroff (#const A_DIM)
+
+attrBoldOn :: IO ()
+attrBoldOn  = throwIfErr_ "attron A_BOLD" $
+    attron (#const A_BOLD)
+
+attrBoldOff :: IO ()
+attrBoldOff = throwIfErr_ "attroff A_BOLD" $
+    attroff (#const A_BOLD)
+
+
+attrDim :: Int
+attrDim = (#const A_DIM)
+attrBold :: Int
+attrBold = (#const A_BOLD)
+
+------------------------------------------------------------------------
+
+mvWAddStr :: Window -> Int -> Int -> String -> IO ()
+mvWAddStr w y x str = wMove w y x >> wAddStr w str
+
+mvAddCh :: Int -> Int -> ChType -> IO ()
+mvAddCh l m n = mvaddch_c (fromIntegral l) (fromIntegral m) (fromIntegral n)
+
+addLn :: IO ()
+addLn = wAddStr stdScr "\n"
+
+--
+-- | normalise the string, stripping \\r and making control chars
+-- printable. Called over all output(?)
+
+{-
+normalise :: String -> String
+normalise []        = []
+normalise ('\r':cs) = normalise cs
+normalise (c:cs) | isControl c   = '@' : normalise cs
+                 | otherwise     = c   : normalise cs
+{-# INLINE normalise #-}
+-}
+
+{-
+normalise s = map f . filter (/= '\r') s
+    where
+        f c | isPrint c  = c
+        f c = '@'
+-}
+
+------------------------------------------------------------------------
+
+#if defined(HAVE_WCHAR_H) && defined(HAVE_LIBNCURSESW)
+
+--wAddStr :: Window -> String -> IO ()
+--wAddStr w str = throwIfErr_ ("waddnwstr: " ++ show str) $ withCWStringLen (normalise str) (\(ws,len) -> waddnwstr w ws (fi len))
+
+foreign import ccall unsafe
+    waddnwstr :: Window -> CWString -> CInt -> IO CInt
+
+foreign import ccall unsafe
+    waddch :: Window -> ChType -> IO CInt
+
+wAddStr :: Window -> String -> IO ()
+wAddStr win str = do
+    let
+        convStr f = case f [] of
+            [] -> return ()
+            s  -> throwIfErr_ "waddnstr" $
+                withCWStringLen  (s) (\(ws,len) ->  (waddnwstr win ws (fi len)))
+        loop []        acc = convStr acc
+        loop (ch:str') acc = recognize
+            ch
+            (loop str' (acc . (ch:)))
+            (\ch' -> do
+                convStr acc
+                throwIfErr "waddch" $ waddch win ch'
+                loop str' id)
+    loop str id
+
+#else
+
+--
+-- This is heavily called, and does a lot of allocs.  We walk over all
+-- the string accumulating a list of characters to be drawn.
+--
+-- Got it down to:
+--
+--      wAddStr Yi.Curses 20.0   38.1
+--      wAddStr Yi.Curses 10.0   32.5
+--
+-- TODO make this way less expensive. That accum sucks.
+-- use difference lists for O(1) append
+--
+wAddStr :: Window -> [Char] -> IO ()
+wAddStr _   [] = return ()
+wAddStr win s  = throwIfErr_ ("waddnstr: <" ++ s ++ ">") $
+    withLCStringLen (s) (\(ws,len) -> waddnstr win ws (fi len))
+
+foreign import ccall threadsafe
+    waddnstr :: Window -> CString -> CInt -> IO CInt
+
+foreign import ccall threadsafe
+    waddch :: Window -> ChType -> IO CInt
+
+foreign import ccall threadsafe
+    waddchnstr :: Window -> CString -> CInt -> IO CInt
+
+foreign import ccall threadsafe "static curses.h mvaddch" mvaddch_c :: CInt -> CInt -> ChType -> IO ()
+
+#endif
+
+foreign import ccall threadsafe
+    vline  :: Char -> Int -> IO ()
+
+------------------------------------------------------------------------
+
+--
+-- what ?
+--
+
+#let translate_attr attr =                              \
+    "(if a .&. %lu /= 0 then %lu else 0) .|.",          \
+    (unsigned long) WA_##attr, (unsigned long) A_##attr
+
+bkgrndSet :: Attr -> Pair -> IO ()
+bkgrndSet (Attr a) p = bkgdset $
+    fromIntegral (ord ' ') .|.
+    #translate_attr ALTCHARSET
+    #translate_attr BLINK
+    #translate_attr BOLD
+    #translate_attr DIM
+    #translate_attr INVIS
+    #translate_attr PROTECT
+    #translate_attr REVERSE
+    #translate_attr STANDOUT
+    #translate_attr UNDERLINE
+    colorPair p
+
+foreign import ccall unsafe bkgdset :: ChType -> IO ()
+
+erase :: IO ()
+erase = throwIfErr_ "erase" $ werase_c  stdScr
+foreign import ccall unsafe "werase" werase_c :: Window -> IO CInt
+
+wclear :: Window -> IO ()
+wclear w = throwIfErr_ "wclear" $ wclear_c  w
+foreign import ccall unsafe "wclear" wclear_c :: Window -> IO CInt
+
+clrToEol :: IO ()
+clrToEol = throwIfErr_ "clrtoeol" clrtoeol
+foreign import ccall unsafe clrtoeol :: IO CInt
+
+--
+-- | >    move the cursor associated with the window
+--   >    to line y and column x.  This routine does  not  move  the
+--   >    physical  cursor  of the terminal until refresh is called.
+--   >    The position specified is relative to the upper  left-hand
+--   >    corner of the window, which is (0,0).
+--
+-- Note that 'move_c' may be a macro.
+--
+move :: Int -> Int -> IO ()
+move y x = throwIfErr_ "move" $ move_c (fromIntegral y) (fromIntegral x)
+
+foreign import ccall unsafe "move"
+    move_c :: CInt -> CInt -> IO CInt
+
+--
+-- | >    move the cursor associated with the window
+--   >    to line y and column x.  This routine does  not  move  the
+--   >    physical  cursor  of the terminal until refresh is called.
+--   >    The position specified is relative to the upper  left-hand
+--   >    corner of the window, which is (0,0).
+--
+wMove :: Window -> Int -> Int -> IO ()
+wMove w y x = throwIfErr_ "wmove" $ wmove w (fi y) (fi x)
+
+foreign import ccall unsafe
+    wmove :: Window -> CInt -> CInt -> IO CInt
+
+------------------
+-- Cursor routines
+------------------
+
+data CursorVisibility = CursorInvisible | CursorVisible | CursorVeryVisible
+
+vis_c :: CursorVisibility -> CInt
+vis_c vis = case vis of
+    CursorInvisible   -> 0
+    CursorVisible     -> 1
+    CursorVeryVisible -> 2
+
+c_vis :: CInt -> CursorVisibility
+c_vis 0 = CursorInvisible
+c_vis 1 = CursorVisible
+c_vis 2 = CursorVeryVisible
+c_vis n = error ("Illegal C value for cursor visibility: " ++ show n)
+
+--
+-- | Set the cursor state
+--
+-- >       The curs_set routine sets  the  cursor  state  is  set  to
+-- >       invisible, normal, or very visible for visibility equal to
+-- >       0, 1, or 2 respectively.  If  the  terminal  supports  the
+-- >       visibility   requested,   the  previous  cursor  state  is
+-- >       returned; otherwise, ERR is returned.
+--
+cursSet :: CursorVisibility -> IO CursorVisibility
+cursSet CursorInvisible =
+    do leaveOk True
+       old <- curs_set 0
+       return $ c_vis old
+cursSet v =
+    do leaveOk False
+       old <- curs_set (vis_c v)
+       return $ c_vis old
+
+foreign import ccall unsafe "HSCurses.h curs_set"
+    curs_set :: CInt -> IO CInt
+
+--
+-- | Get the current cursor coordinates
+--
+getYX :: Window -> IO (Int, Int)
+getYX w =
+    alloca $ \py ->                 -- allocate two ints on the stack
+        alloca $ \px -> do
+            nomacro_getyx w py px   -- writes current cursor coords
+            y <- peek py
+            x <- peek px
+            return (fromIntegral y, fromIntegral x)
+
+--
+-- | Get the current cursor coords, written into the two argument ints.
+--
+-- >    The getyx macro places the current cursor position of the given
+-- >    window in the two integer variables y and x.
+--
+--      void getyx(WINDOW *win, int y, int x);
+--
+foreign import ccall unsafe "HSCursesUtils.h hscurses_nomacro_getyx"
+        nomacro_getyx :: Window -> Ptr CInt -> Ptr CInt -> IO ()
+
+------------------------------------------------------------------------
+
+
+touchWin :: Window -> IO ()
+touchWin w = throwIfErr_ "touchwin" $ touchwin w
+foreign import ccall touchwin :: Window -> IO CInt
+
+newPad :: Int -> Int -> IO Window
+newPad nlines ncols = throwIfNull "newpad" $
+    newpad (fromIntegral nlines) (fromIntegral ncols)
+
+pRefresh :: Window -> Int -> Int -> Int -> Int -> Int -> Int -> IO ()
+pRefresh pad pminrow pmincol sminrow smincol smaxrow smaxcol =
+    throwIfErr_ "prefresh" $
+        prefresh pad (fromIntegral pminrow)
+                     (fromIntegral pmincol)
+                     (fromIntegral sminrow)
+                     (fromIntegral smincol)
+                     (fromIntegral smaxrow)
+                     (fromIntegral smaxcol)
+
+delWin :: Window -> IO ()
+delWin w = throwIfErr_ "delwin" $ delwin w
+
+foreign import ccall unsafe
+    prefresh :: Window -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt
+
+foreign import ccall unsafe
+    newpad :: CInt -> CInt -> IO Window
+
+foreign import ccall unsafe
+    delwin :: Window -> IO CInt
+
+newWin :: Int -> Int -> Int -> Int -> IO Window
+newWin nlines ncolumn begin_y begin_x = throwIfNull "newwin" $
+    newwin (fi nlines) (fi ncolumn) (fi begin_y) (fi begin_x)
+
+foreign import ccall unsafe
+    newwin :: CInt -> CInt -> CInt -> CInt -> IO Window
+
+wClrToEol :: Window -> IO ()
+wClrToEol w = throwIfErr_ "wclrtoeol" $ wclrtoeol w
+
+foreign import ccall unsafe wclrtoeol :: Window -> IO CInt
+
+--
+-- | >      The getch, wgetch, mvgetch and mvwgetch, routines read a
+--   >      character  from the window.
+--
+foreign import ccall unsafe getch :: IO CInt
+
+--foreign import ccall unsafe def_prog_mode :: IO CInt
+--foreign import ccall unsafe reset_prog_mode :: IO CInt
+foreign import ccall unsafe flushinp :: IO CInt
+
+foreign import ccall unsafe "HSCurses.h noqiflush" noqiflush :: IO ()
+
+foreign import ccall unsafe "HSCurses.h beep" c_beep :: IO CInt
+foreign import ccall unsafe "HSCurses.h flash" c_flash :: IO CInt
+
+beep :: IO ()
+beep = do
+    br <- c_beep
+    when (br /= (#const OK)) (c_flash >> return ())
+
+------------------------------------------------------------------------
+--
+-- | Map curses keys to key abstraction
+--
+
+data Key
+    = KeyChar Char | KeyBreak | KeyDown | KeyUp | KeyLeft | KeyRight
+    | KeyHome | KeyBackspace | KeyF Int | KeyDL | KeyIL | KeyDC
+    | KeyIC | KeyEIC | KeyClear | KeyEOS | KeyEOL | KeySF | KeySR
+    | KeyNPage | KeyPPage | KeySTab | KeyCTab | KeyCATab | KeyEnter
+    | KeySReset | KeyReset | KeyPrint | KeyLL | KeyA1 | KeyA3
+    | KeyB2 | KeyC1 | KeyC3 | KeyBTab | KeyBeg | KeyCancel | KeyClose
+    | KeyCommand | KeyCopy | KeyCreate | KeyEnd | KeyExit | KeyFind
+    | KeyHelp | KeyMark | KeyMessage | KeyMove | KeyNext | KeyOpen
+    | KeyOptions | KeyPrevious | KeyRedo | KeyReference | KeyRefresh
+    | KeyReplace | KeyRestart | KeyResume | KeySave | KeySBeg
+    | KeySCancel | KeySCommand | KeySCopy | KeySCreate | KeySDC
+    | KeySDL | KeySelect | KeySEnd | KeySEOL | KeySExit | KeySFind
+    | KeySHelp | KeySHome | KeySIC | KeySLeft | KeySMessage | KeySMove
+    | KeySNext | KeySOptions | KeySPrevious | KeySPrint | KeySRedo
+    | KeySReplace | KeySRight | KeySRsume | KeySSave | KeySSuspend
+    | KeySUndo | KeySuspend | KeyUndo | KeyResize | KeyMouse | KeyUnknown Int
+    deriving (Eq,Show)
+
+decodeKey :: CInt -> Key
+decodeKey key = case key of
+    _ | key >= 0 && key <= 255 -> KeyChar (chr (fromIntegral key))
+    (#const KEY_BREAK)         -> KeyBreak
+    (#const KEY_DOWN)          -> KeyDown
+    (#const KEY_UP)            -> KeyUp
+    (#const KEY_LEFT)          -> KeyLeft
+    (#const KEY_RIGHT)         -> KeyRight
+    (#const KEY_HOME)          -> KeyHome
+    (#const KEY_BACKSPACE)     -> KeyBackspace
+    _ | key >= (#const KEY_F0) && key <= (#const KEY_F(63))
+                               -> KeyF (fromIntegral (key - #const KEY_F0))
+    (#const KEY_DL)            -> KeyDL
+    (#const KEY_IL)            -> KeyIL
+    (#const KEY_DC)            -> KeyDC
+    (#const KEY_IC)            -> KeyIC
+    (#const KEY_EIC)           -> KeyEIC
+    (#const KEY_CLEAR)         -> KeyClear
+    (#const KEY_EOS)           -> KeyEOS
+    (#const KEY_EOL)           -> KeyEOL
+    (#const KEY_SF)            -> KeySF
+    (#const KEY_SR)            -> KeySR
+    (#const KEY_NPAGE)         -> KeyNPage
+    (#const KEY_PPAGE)         -> KeyPPage
+    (#const KEY_STAB)          -> KeySTab
+    (#const KEY_CTAB)          -> KeyCTab
+    (#const KEY_CATAB)         -> KeyCATab
+    (#const KEY_ENTER)         -> KeyEnter
+    (#const KEY_SRESET)        -> KeySReset
+    (#const KEY_RESET)         -> KeyReset
+    (#const KEY_PRINT)         -> KeyPrint
+    (#const KEY_LL)            -> KeyLL
+    (#const KEY_A1)            -> KeyA1
+    (#const KEY_A3)            -> KeyA3
+    (#const KEY_B2)            -> KeyB2
+    (#const KEY_C1)            -> KeyC1
+    (#const KEY_C3)            -> KeyC3
+    (#const KEY_BTAB)          -> KeyBTab
+    (#const KEY_BEG)           -> KeyBeg
+    (#const KEY_CANCEL)        -> KeyCancel
+    (#const KEY_CLOSE)         -> KeyClose
+    (#const KEY_COMMAND)       -> KeyCommand
+    (#const KEY_COPY)          -> KeyCopy
+    (#const KEY_CREATE)        -> KeyCreate
+    (#const KEY_END)           -> KeyEnd
+    (#const KEY_EXIT)          -> KeyExit
+    (#const KEY_FIND)          -> KeyFind
+    (#const KEY_HELP)          -> KeyHelp
+    (#const KEY_MARK)          -> KeyMark
+    (#const KEY_MESSAGE)       -> KeyMessage
+    (#const KEY_MOVE)          -> KeyMove
+    (#const KEY_NEXT)          -> KeyNext
+    (#const KEY_OPEN)          -> KeyOpen
+    (#const KEY_OPTIONS)       -> KeyOptions
+    (#const KEY_PREVIOUS)      -> KeyPrevious
+    (#const KEY_REDO)          -> KeyRedo
+    (#const KEY_REFERENCE)     -> KeyReference
+    (#const KEY_REFRESH)       -> KeyRefresh
+    (#const KEY_REPLACE)       -> KeyReplace
+    (#const KEY_RESTART)       -> KeyRestart
+    (#const KEY_RESUME)        -> KeyResume
+    (#const KEY_SAVE)          -> KeySave
+    (#const KEY_SBEG)          -> KeySBeg
+    (#const KEY_SCANCEL)       -> KeySCancel
+    (#const KEY_SCOMMAND)      -> KeySCommand
+    (#const KEY_SCOPY)         -> KeySCopy
+    (#const KEY_SCREATE)       -> KeySCreate
+    (#const KEY_SDC)           -> KeySDC
+    (#const KEY_SDL)           -> KeySDL
+    (#const KEY_SELECT)        -> KeySelect
+    (#const KEY_SEND)          -> KeySEnd
+    (#const KEY_SEOL)          -> KeySEOL
+    (#const KEY_SEXIT)         -> KeySExit
+    (#const KEY_SFIND)         -> KeySFind
+    (#const KEY_SHELP)         -> KeySHelp
+    (#const KEY_SHOME)         -> KeySHome
+    (#const KEY_SIC)           -> KeySIC
+    (#const KEY_SLEFT)         -> KeySLeft
+    (#const KEY_SMESSAGE)      -> KeySMessage
+    (#const KEY_SMOVE)         -> KeySMove
+    (#const KEY_SNEXT)         -> KeySNext
+    (#const KEY_SOPTIONS)      -> KeySOptions
+    (#const KEY_SPREVIOUS)     -> KeySPrevious
+    (#const KEY_SPRINT)        -> KeySPrint
+    (#const KEY_SREDO)         -> KeySRedo
+    (#const KEY_SREPLACE)      -> KeySReplace
+    (#const KEY_SRIGHT)        -> KeySRight
+    (#const KEY_SRSUME)        -> KeySRsume
+    (#const KEY_SSAVE)         -> KeySSave
+    (#const KEY_SSUSPEND)      -> KeySSuspend
+    (#const KEY_SUNDO)         -> KeySUndo
+    (#const KEY_SUSPEND)       -> KeySuspend
+    (#const KEY_UNDO)          -> KeyUndo
+#ifdef KEY_RESIZE
+    (#const KEY_RESIZE)        -> KeyResize
+#endif
+#ifdef KEY_MOUSE
+    (#const KEY_MOUSE)         -> KeyMouse
+#endif
+    _                          -> KeyUnknown (fromIntegral key)
+
+keyResizeCode :: Maybe CInt
+#ifdef KEY_RESIZE
+keyResizeCode = Just (#const KEY_RESIZE)
+#else
+keyResizeCode = Nothing
+#endif
+
+cERR :: CInt
+cERR = #const ERR
+
+cKEY_UP, cKEY_DOWN, cKEY_LEFT, cKEY_RIGHT :: ChType
+cKEY_UP = #const KEY_UP
+cKEY_DOWN = #const KEY_DOWN
+cKEY_LEFT = #const KEY_LEFT
+cKEY_RIGHT = #const KEY_RIGHT
+
+-- cACS_BLOCK :: ChType
+-- cACS_BLOCK = #const ACS_BLOCK
+
+cTRUE :: NBool
+cTRUE = #const TRUE
+
+
+-- ---------------------------------------------------------------------
+-- get char
+--
+
+-- ncurses ungetch and Haskell's threadWaitRead do not work together well.
+-- So I decided to implement my own input queue.
+ungetCh :: (Integral a) => a -> IO ()
+ungetCh i =
+    do debug "ungetCh called"
+       writeChan inputBuf (BufDirect (fi i))
+
+data BufData = BufDirect CInt  -- data directly available
+             | DataViaGetch    -- data can be obtained by calling getch
+
+inputBuf :: Chan BufData
+inputBuf = unsafePerformIO newChan
+{-# NOINLINE inputBuf #-}
+
+getchToInputBuf :: IO ()
+getchToInputBuf =
+    do threadWaitRead (fi (0::Int))
+       {- From the (n)curses manpage:
+       Programmers  concerned  about portability should be prepared for either
+       of two cases: (a) signal receipt does not interrupt getch;  (b)  signal
+       receipt  interrupts getch and causes it to return ERR with errno set to
+       EINTR.  Under the ncurses implementation, handled signals never  inter$B!>(B
+       rupt getch.
+       -}
+       -- we only signalize that getch can now called without getting blocked.
+       -- directly calling `getch' might result in losing the character just
+       -- read (race condition).
+       debug "now input available on stdin"
+       writeChan inputBuf DataViaGetch
+--
+-- | read a character from the window
+--
+getCh :: IO Key
+getCh =
+    do debug "getCh called"
+       tid <- forkIO getchToInputBuf
+       d <- readChan inputBuf
+       killThread tid  -- we can kill the thread savely, because the thread does
+                       -- not read any data via getch
+       v <- case d of
+              BufDirect x ->
+                do debug "getCh: getting data directly from buffer"
+                   return x
+              DataViaGetch ->
+                do debug "getCh: getting data via getch"
+                   getch -- won't block!
+       case v of
+         (#const ERR) -> -- NO CODE IN THIS LINE
+             do e <- getErrno
+                if e `elem` [eAGAIN, eINTR]
+                   then do debug "Curses.getCh returned eAGAIN or eINTR"
+                           getCh
+                   else throwErrno "HSCurses.Curses.getch"
+         k -> let k' = decodeKey k
+                  in do debug ("getCh: result = " ++ show k')
+                        return k'
+
+
+resizeTerminal :: Int -> Int -> IO ()
+
+#ifdef HAVE_RESIZETERM
+resizeTerminal a b = throwIfErr_ "resizeterm"  $ resizeterm (fi a) (fi b)
+
+foreign import ccall unsafe "HSCurses.h resizeterm"
+    resizeterm :: CInt -> CInt -> IO CInt
+#else
+resizeTerminal _ _ = return ()
+#endif
+
+--
+-- | The SIGWINCH signal is sent whenever the terminal size changes.
+-- This signal is not available on all platforms, so it is a |Maybe| value.
+--
+cursesSigWinch :: Maybe Signal
+#ifdef SIGWINCH
+cursesSigWinch = Just (#const SIGWINCH)
+#else
+cursesSigWinch = Nothing
+#endif
+
+------------
+-- Test case
+------------
+
+cursesTest :: IO ()
+cursesTest = do
+    initScr
+    hc <- hasColors
+    when hc startColor
+    ccc <- canChangeColor
+    (ys,xs) <- scrSize
+    cp <- colorPairs
+    cs <- colors
+    endWin
+    putStrLn $ "ScreenSize: " ++ show (xs,ys)
+    putStrLn $ "hasColors: " ++ show hc
+    putStrLn $ "canChangeColor: " ++ show ccc
+    putStrLn $ "colorPairs: " ++ show cp
+    putStrLn $ "colors: " ++ show cs
+
+
+
+
+-----------------
+-- Mouse Routines
+-----------------
+
+data MouseEvent = MouseEvent {
+    mouseEventId :: Int,
+    mouseEventX :: Int,
+    mouseEventY :: Int,
+    mouseEventZ :: Int,
+    mouseEventButton :: [ButtonEvent]
+   } deriving(Show)
+
+data ButtonEvent = ButtonPressed Int | ButtonReleased Int | ButtonClicked Int |
+    ButtonDoubleClicked Int | ButtonTripleClicked Int | ButtonShift | ButtonControl | ButtonAlt
+                deriving(Eq,Show)
+
+withMouseEventMask :: MonadIO m => [ButtonEvent] -> m a -> m a
+
+#ifdef KEY_MOUSE
+
+foreign import ccall unsafe "HSCurses.h mousemask"
+    mousemask :: (#type mmask_t) -> Ptr (#type mmask_t) -> IO (#type mmask_t)
+
+withMouseEventMask bes action = do
+    ov <- liftIO $ alloca (\a ->  mousemask (besToMouseMask bes) a >> peek a)
+    r <- action
+    liftIO $ mousemask ov nullPtr
+    return r
+
+besToMouseMask :: [ButtonEvent] -> (#type mmask_t)
+besToMouseMask bes = foldl' (.|.) 0 (map cb bes) where
+    cb (ButtonPressed 1) = (#const BUTTON1_PRESSED)
+    cb (ButtonPressed 2) = (#const BUTTON2_PRESSED)
+    cb (ButtonPressed 3) = (#const BUTTON3_PRESSED)
+    cb (ButtonPressed 4) = (#const BUTTON4_PRESSED)
+    cb (ButtonReleased 1) = (#const BUTTON1_RELEASED)
+    cb (ButtonReleased 2) = (#const BUTTON2_RELEASED)
+    cb (ButtonReleased 3) = (#const BUTTON3_RELEASED)
+    cb (ButtonReleased 4) = (#const BUTTON4_RELEASED)
+    cb (ButtonClicked 1) = (#const BUTTON1_CLICKED)
+    cb (ButtonClicked 2) = (#const BUTTON2_CLICKED)
+    cb (ButtonClicked 3) = (#const BUTTON3_CLICKED)
+    cb (ButtonClicked 4) = (#const BUTTON4_CLICKED)
+    cb ButtonShift = (#const BUTTON_SHIFT)
+    cb ButtonAlt = (#const BUTTON_ALT)
+    cb ButtonControl = (#const BUTTON_CTRL)
+    cb _ = 0
+
+
+#else
+withMouseEventMask _ a = a
+
+#endif
+
+
+
+
+ulCorner, llCorner, urCorner, lrCorner, rTee, lTee, bTee, tTee, hLine,
+    vLine, plus, s1, s9, diamond, ckBoard, degree, plMinus, bullet,
+    lArrow, rArrow, dArrow, uArrow, board, lantern, block,
+    s3, s7, lEqual, gEqual, pi, nEqual, sterling
+    :: Char
+
+ulCorner = chr 0x250C
+llCorner = chr 0x2514
+urCorner = chr 0x2510
+lrCorner = chr 0x2518
+rTee     = chr 0x2524
+lTee     = chr 0x251C
+bTee     = chr 0x2534
+tTee     = chr 0x252C
+hLine    = chr 0x2500
+vLine    = chr 0x2502
+plus     = chr 0x253C
+s1       = chr 0x23BA -- was: 0xF800
+s9       = chr 0x23BD -- was: 0xF804
+diamond  = chr 0x25C6
+ckBoard  = chr 0x2592
+degree   = chr 0x00B0
+plMinus  = chr 0x00B1
+bullet   = chr 0x00B7
+lArrow   = chr 0x2190
+rArrow   = chr 0x2192
+dArrow   = chr 0x2193
+uArrow   = chr 0x2191
+board    = chr 0x2591
+lantern  = chr 0x256C
+block    = chr 0x2588
+s3       = chr 0x23BB -- was: 0xF801
+s7       = chr 0x23BC -- was: 0xF803
+lEqual   = chr 0x2264
+gEqual   = chr 0x2265
+pi       = chr 0x03C0
+nEqual   = chr 0x2260
+sterling = chr 0x00A3
+
+{-
+-- haddock doesn't like these commented out with --
+   #if defined(__STDC_ISO_10646__)  && defined(HAVE_WADDNWSTR)
+   #else
+-}
+
+recognize :: Char -> IO a -> (ChType -> IO a) -> IO a
+recognize _ch noConvert _convert = noConvert -- Handle the most common case first.
+
+
+
+
+-- ---------------------------------------------------------------------
+-- code graveyard
+--
+
+{-
+
+addStr :: String -> IO ()
+addStr str =
+    throwIfErr_ "addstr" $
+    withCStringConv (readIORef cursesOutConv) str addstr
+foreign import ccall unsafe addstr :: Ptr CChar -> IO CInt
+
+addStrLn :: String -> IO ()
+addStrLn str = addStr str >> addLn
+
+--
+-- | add a string of characters to a curses window and advance cursor
+-- curs_addstr(3)
+--
+wAddStr :: Window -> String -> IO ()
+wAddStr w str = throwIfErr_ "waddstr" $
+    withCStringConv (readIORef cursesOutConv) str (waddstr w)
+
+foreign import ccall unsafe waddstr :: Window -> Ptr CChar -> IO CInt
+
+
+addGraphStr :: String -> IO ()
+addGraphStr str = do
+    conv <- readIORef cursesOutConv
+    let
+        convStr f = case f [] of
+            [] -> return ()
+            s  -> throwIfErr_ "addstr" $
+                withCStringConv (return conv) s addstr
+        loop []        acc = convStr acc
+        loop (ch:str') acc = recognize
+            ch
+            (loop str' (acc . (ch:)))
+            (\ch' -> do
+                convStr acc
+                throwIfErr "addch" $ addch ch'
+                loop str' id)
+    loop str id
+
+addGraphStrLn :: String -> IO ()
+addGraphStrLn str = do addGraphStr str; addLn
+
+-}
+
+-- vim: sw=4 ts=4
diff --git a/UI/HSCurses/CursesHelper.hs b/UI/HSCurses/CursesHelper.hs
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/CursesHelper.hs
@@ -0,0 +1,474 @@
+{-# LANGUAGE CPP #-}
+{-# OPTIONS -#include HSCursesUtils.h -#include <signal.h> #-}
+
+--
+-- Copyright (C) 2005 Stefan Wehr
+--
+-- Derived from: yi/Curses/UI.hs
+--      Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
+--      Released under the same license.
+--
+-- Derived from: riot/UI.hs
+--      Copyright (c) Tuomo Valkonen 2004.
+--      Released under the same license.
+--
+-- This program is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU General Public License as
+-- published by the Free Software Foundation; either version 2 of
+-- the License, or (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+-- General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program; if not, write to the Free Software
+-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+-- 02111-1307, USA.
+--
+--
+
+module UI.HSCurses.CursesHelper (
+
+        -- * UI initialisation
+        start, end, suspend, resizeui,
+
+        -- * Input
+        getKey,
+
+        -- * Drawing
+        drawLine, drawCursor,
+
+        -- * Navigation
+        gotoTop,
+
+        -- * Colors
+        ForegroundColor(..), BackgroundColor(..),
+        defaultColor, black, red, green, yellow, blue, magenta, cyan, white,
+
+        -- * Attributes
+        Attribute(..), convertAttributes,
+
+        -- * Style
+        Style(..), CursesStyle, mkCursesStyle, changeCursesStyle,
+        setStyle, resetStyle, convertStyles,
+        defaultStyle, defaultCursesStyle, withStyle,
+
+        -- * Keys
+        displayKey,
+
+        -- * Helpers
+        withCursor, withProgram
+  )   where
+
+import UI.HSCurses.Curses hiding ( refresh, Window )
+import UI.HSCurses.Logging
+import UI.HSCurses.MonadException
+import qualified UI.HSCurses.Curses as Curses
+
+import Data.Char
+import Data.Maybe
+import Data.List
+import Control.Monad.Trans
+import System.Posix.Signals
+
+--
+--
+
+--
+-- | @start@ initializes the UI and grabs the keyboard.
+--
+-- This function installs a handler for the SIGWINCH signal
+-- which writes the KEY_RESIZE key to the input queue (if KEY_RESIZE and
+-- and SIGWINCH are both available).
+--
+start :: IO ()
+start = do
+    Curses.initCurses                   -- initialise the screen
+    Curses.resetParams
+    Curses.keypad Curses.stdScr True    -- grab the keyboard
+    case (Curses.cursesSigWinch, Curses.keyResizeCode) of
+      (Just sig, Just key) ->
+          do installHandler sig (Catch $ sigwinch sig key) Nothing
+             return ()
+      _ -> debug ("cannot install SIGWINCH handler: signal=" ++
+                  show Curses.cursesSigWinch ++ ", KEY_RESIZE=" ++
+                  show Curses.keyResizeCode)
+    where sigwinch sig key =
+              do debug "SIGWINCH signal received"
+                 Curses.ungetCh key
+                 installHandler sig (Catch $ sigwinch sig key) Nothing
+                 return ()
+
+
+
+--
+-- | Clean up and go home.
+--
+end :: IO ()
+end = do Curses.endWin
+-- Refresh is needed on linux. grr.
+#if NCURSES_UPDATE_AFTER_END
+         Curses.update
+#endif
+
+--
+-- | Suspend the program.
+--
+suspend :: IO ()
+suspend = raiseSignal sigTSTP
+
+--
+-- | @getKey refresh@ reads a key.
+--
+-- The @refresh@ function is used to redraw the screen when the terminal size
+-- changes (see the documentatio of @start@ for a discussion of the problem).
+--
+getKey :: MonadIO m => m () -> m Key
+getKey refresh = do
+    k <- liftIO $ Curses.getCh
+    debug ("getKey: " ++ show k)
+    case k of
+      KeyResize ->
+          do refresh
+             getKey refresh
+      _ -> return k
+
+
+--
+-- | @drawLine n s@ draws @n@ characters of string @s@.
+--
+drawLine :: Int -> String -> IO ()
+-- lazy version is faster than calculating length of s
+drawLine w s = Curses.wAddStr Curses.stdScr $! take w (s ++ repeat ' ')
+
+--
+-- | Draw the cursor at the given position.
+--
+drawCursor :: (Int,Int) -> (Int, Int) -> IO ()
+drawCursor (o_y,o_x) (y,x) = withCursor Curses.CursorVisible $ do
+    gotoTop
+    (h,w) <- scrSize
+    Curses.wMove Curses.stdScr (min (h-1) (o_y + y)) (min (w-1) (o_x + x))
+
+--
+-- | Move cursor to origin of stdScr.
+--
+gotoTop :: IO ()
+gotoTop = Curses.wMove Curses.stdScr 0 0
+
+
+--
+-- | Resize the window
+-- From "Writing Programs with NCURSES", by Eric S. Raymond and
+-- Zeyd M. Ben-Halim
+--
+--
+resizeui :: IO (Int,Int)
+resizeui = do
+    Curses.endWin
+    Curses.refresh
+    Curses.scrSize
+
+
+
+------------------------------------------------------------------------
+--
+-- | Basic colors.
+--
+defaultColor :: Curses.Color
+defaultColor = fromJust $ Curses.color "default"
+
+black, red, green, yellow, blue, magenta, cyan, white :: Curses.Color
+black     = fromJust $ Curses.color "black"
+red       = fromJust $ Curses.color "red"
+green     = fromJust $ Curses.color "green"
+yellow    = fromJust $ Curses.color "yellow"
+blue      = fromJust $ Curses.color "blue"
+magenta   = fromJust $ Curses.color "magenta"
+cyan      = fromJust $ Curses.color "cyan"
+white     = fromJust $ Curses.color "white"
+
+--
+-- | Converts a list of 'Curses.Color' pairs (foreground color and
+--   background color) into the curses representation 'Curses.Pair'.
+--
+--   You should call this function exactly once, at application startup.
+--
+-- (not visible outside this module)
+colorsToPairs :: [(Curses.Color, Curses.Color)] -> IO [Curses.Pair]
+colorsToPairs cs =
+    do p <- Curses.colorPairs
+       let nColors = length cs
+           blackWhite = p < nColors
+       if blackWhite
+          then trace ("Terminal does not support enough colors. Number of " ++
+                      " colors requested: " ++ show nColors ++
+                      ". Number of colors supported: " ++ show p)
+                 return $ take nColors (repeat (Curses.Pair 0))
+          else mapM toPairs (zip [1..] cs)
+     where toPairs (n, (fg, bg)) =
+               let p = Curses.Pair n
+               in do Curses.initPair p fg bg
+                     return p
+
+------------------------------------------------------------------------
+-- Nicer, user-visible color defs.
+--
+-- We separate colors into dark and bright colors, to prevent users
+-- from erroneously constructing bright colors for dark backgrounds,
+-- which doesn't work.
+
+--
+-- | Foreground colors.
+--
+data ForegroundColor
+    = BlackF
+    | GreyF
+    | DarkRedF
+    | RedF
+    | DarkGreenF
+    | GreenF
+    | BrownF
+    | YellowF
+    | DarkBlueF
+    | BlueF
+    | PurpleF
+    | MagentaF
+    | DarkCyanF
+    | CyanF
+    | WhiteF
+    | BrightWhiteF
+    | DefaultF
+    deriving (Eq, Show)
+
+--
+-- | Background colors.
+--
+data BackgroundColor
+    = BlackB
+    | DarkRedB
+    | DarkGreenB
+    | BrownB
+    | DarkBlueB
+    | PurpleB
+    | DarkCyanB
+    | WhiteB
+    | DefaultB
+    deriving (Eq, Show)
+
+--
+-- | Mapping abstract colours to ncurses attributes and colours
+--
+-- (not visible outside this module)
+
+convertBg :: BackgroundColor -> ([Attribute], Curses.Color)
+convertBg c = case c of
+    BlackB      -> ([], black)
+    DarkRedB    -> ([], red)
+    DarkGreenB  -> ([], green)
+    BrownB      -> ([], yellow)
+    DarkBlueB   -> ([], blue)
+    PurpleB     -> ([], magenta)
+    DarkCyanB   -> ([], cyan)
+    WhiteB      -> ([], white)
+    DefaultB    -> ([], defaultColor)
+
+convertFg :: ForegroundColor -> ([Attribute], Curses.Color)
+convertFg c = case c of
+    BlackF       -> ([], black)
+    GreyF        -> ([Bold], black)
+    DarkRedF     -> ([], red)
+    RedF         -> ([Bold], red)
+    DarkGreenF   -> ([], green)
+    GreenF       -> ([Bold], green)
+    BrownF       -> ([], yellow)
+    YellowF      -> ([Bold], yellow)
+    DarkBlueF    -> ([], blue)
+    BlueF        -> ([Bold], blue)
+    PurpleF      -> ([], magenta)
+    MagentaF     -> ([Bold], magenta)
+    DarkCyanF    -> ([], cyan)
+    CyanF        -> ([Bold], cyan)
+    WhiteF       -> ([], white)
+    BrightWhiteF -> ([Bold], white)
+    DefaultF     -> ([], defaultColor)
+
+
+------------------------------------------------------------------------
+--
+-- | Abstractions for some commonly used attributes.
+--
+data Attribute = Bold
+               | Underline
+               | Dim
+               | Reverse
+               | Blink
+               deriving (Eq, Show)
+
+--
+-- | Converts an abstract attribute list into its curses representation.
+--
+convertAttributes :: [Attribute] -> Curses.Attr
+convertAttributes =
+    foldr setAttrs Curses.attr0
+    where setAttrs Bold = setBoldA
+          setAttrs Underline = setUnderlineA
+          setAttrs Dim = setDimA
+          setAttrs Reverse = setReverseA
+          setAttrs Blink = setBlinkA
+
+setBoldA, setUnderlineA, setDimA,
+  setReverseA, setBlinkA :: Curses.Attr -> Curses.Attr
+setBoldA = flip Curses.setBold True
+setUnderlineA = flip Curses.setUnderline True
+setDimA = flip Curses.setDim True
+setReverseA = flip Curses.setReverse   True
+setBlinkA = flip Curses.setBlink True
+
+------------------------------------------------------------------------
+--
+-- | A humand-readable style.
+--
+data Style = Style ForegroundColor BackgroundColor
+           | AttributeStyle [Attribute] ForegroundColor BackgroundColor
+           | ColorlessStyle [Attribute]
+           deriving (Eq, Show)
+
+defaultStyle :: Style
+defaultStyle = Style DefaultF DefaultB
+
+--
+-- | A style which uses the internal curses representations for
+--   attributes and colors.
+--
+data CursesStyle = CursesStyle Curses.Attr Curses.Pair
+                 | ColorlessCursesStyle Curses.Attr
+                 deriving (Eq, Show)
+
+{-
+instance Show CursesStyle where
+    show (CursesStyle _ _) = "CursesStyle"
+    show (ColorlessCursesStyle _) = "ColorlessCursesStyle"
+-}
+
+mkCursesStyle :: [Attribute] -> CursesStyle
+mkCursesStyle attrs = ColorlessCursesStyle (convertAttributes attrs)
+
+--
+-- | Changes the attributes of the given CursesStyle.
+--
+changeCursesStyle :: CursesStyle -> [Attribute] -> CursesStyle
+changeCursesStyle (CursesStyle _ p) attrs =
+    CursesStyle (convertAttributes attrs) p
+changeCursesStyle _ attrs = ColorlessCursesStyle (convertAttributes attrs)
+
+defaultCursesStyle :: CursesStyle
+defaultCursesStyle = CursesStyle Curses.attr0 (Curses.Pair 0)
+
+--
+-- | Reset the screen to normal values
+--
+resetStyle :: IO ()
+resetStyle = setStyle defaultCursesStyle
+
+--
+-- | Manipulate the current style of the standard screen
+--
+setStyle :: CursesStyle -> IO ()
+setStyle (CursesStyle a p) = Curses.wAttrSet Curses.stdScr (a, p)
+setStyle (ColorlessCursesStyle a) =
+    do (_, p) <- Curses.wAttrGet Curses.stdScr
+       Curses.wAttrSet Curses.stdScr (a, p)
+
+withStyle :: MonadExcIO m => CursesStyle -> m a -> m a
+withStyle style action =
+    bracketM
+        (liftIO $ do old <- Curses.wAttrGet Curses.stdScr    -- before
+                     setStyle style
+                     return old)
+        (\old -> liftIO $ Curses.wAttrSet Curses.stdScr old) -- after
+        (\_ -> action)                                       -- do this
+
+--
+-- | Converts a list of human-readable styles into the corresponding
+--   curses representation.
+--
+--   This function should be called exactly once at application startup
+--   for all styles of the application.
+convertStyles :: [Style] -> IO [CursesStyle]
+convertStyles styleList =
+    do let (attrs, cs) = unzip $ map convertStyle styleList
+           cursesAttrs = map convertAttributes attrs
+       cursesPairs <- colorsToPairs' cs
+       let res = zipWith toCursesStyle cursesAttrs cursesPairs
+       trace ("convertStyles: " ++ show (zip styleList res)) (return res)
+    where convertStyle (Style fg bg) = convertStyle (AttributeStyle [] fg bg)
+          convertStyle (AttributeStyle attrs fg bg) =
+              let (afg, cfg) = convertFg fg
+                  (abg, cbg) = convertBg bg
+              in (afg ++ abg ++ attrs, Just (cfg, cbg))
+          convertStyle (ColorlessStyle attrs) = (attrs, Nothing)
+          colorsToPairs' cs =
+              do pairs <- colorsToPairs (catMaybes cs)
+                 return $ mergeNothing cs pairs
+          mergeNothing (Just _:crest) (p:prest) = Just p
+                                                  : mergeNothing crest prest
+          mergeNothing (Nothing:crest) ps = Nothing : mergeNothing crest ps
+          mergeNothing [] [] = []
+          toCursesStyle cursesAttrs Nothing =
+              ColorlessCursesStyle cursesAttrs
+          toCursesStyle cursesAttrs (Just cursesPair) =
+              CursesStyle cursesAttrs cursesPair
+
+------------------------------------------------------------------------
+--
+-- | Converting keys to humand-readable strings
+--
+
+displayKey :: Key -> String
+displayKey (KeyChar ' ') = "<Space>"
+displayKey (KeyChar '\t') = "<Tab>"
+displayKey (KeyChar '\r') = "<Enter>"
+displayKey (KeyChar c)
+    | isPrint c = [c]
+displayKey (KeyChar c)  -- Control
+    | ord '\^A' <= ord c && ord c <= ord '\^Z'
+        = let c' = chr $ ord c - ord '\^A' + ord 'a'
+              in '^':[toUpper c']
+displayKey (KeyChar c) = show c
+displayKey KeyDown = "<Down>"
+displayKey KeyUp = "<Up>"
+displayKey KeyLeft = "<Left>"
+displayKey KeyRight = "<Right>"
+displayKey KeyHome = "<Home>"
+displayKey KeyBackspace = "<BS>"
+displayKey (KeyF i) = 'F' : show i
+displayKey KeyNPage = "<NPage>"
+displayKey KeyPPage = "<PPage>"
+displayKey KeyEnter = "<Return>"
+displayKey KeyEnd = "<End>"
+displayKey KeyIC = "<Insert>"
+displayKey KeyDC = "<Delete>"
+displayKey k = show k
+
+
+------------------------------------------------------------------------
+--
+-- | Other helpers
+--
+
+--
+-- | set the cursor, and do action
+--
+withCursor :: MonadExcIO m => CursorVisibility -> m a -> m a
+withCursor nv action =
+    bracketM
+        (liftIO $ Curses.cursSet nv)             -- before
+        (\vis -> liftIO $ Curses.cursSet vis)    -- after
+        (\_ -> action)                           -- do this
+
+withProgram :: MonadExcIO m => m a -> m a
+withProgram action = withCursor CursorVisible $
+    bracketM_ (liftIO endWin) (liftIO flushinp) action
diff --git a/UI/HSCurses/IConv.hsc b/UI/HSCurses/IConv.hsc
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/IConv.hsc
@@ -0,0 +1,205 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+
+--
+-- Copyright (c) 2004 Tuomo Valkonen <tuomov at iki dot fi>
+-- Copyright (c) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
+-- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+-- | Iconv binding
+
+#if HAVE_ICONV_H
+# include <iconv.h>
+#endif
+
+module UI.HSCurses.IConv {-(
+    IConv,
+    iconv,
+    iconv_,
+    with_iconv,
+    to_unicode,
+    from_unicode,
+    to_unicode_,
+    from_unicode_
+  )-} where
+
+import UI.HSCurses.CWString          ( peekUTF8StringLen, withUTF8StringLen )
+
+import Foreign
+import Foreign.C
+import Foreign.C.String
+import Control.Exception    ( Exception, try, bracket )
+
+type IConv = Ptr () --(#type iconv_t)
+
+err_ptr :: Ptr b -> Bool
+err_ptr p = p == (plusPtr nullPtr (-1))
+
+throw_if_not_2_big :: String -> IO CSize -> IO CSize
+throw_if_not_2_big s r_ = do
+    r <- r_
+    if r == fromIntegral (-1 :: Int) then do
+        errno <- getErrno
+        if errno /= e2BIG then
+	    throwErrno s
+	  else
+	    return r
+      else
+        return r
+
+iconv_open :: String -> String -> IO IConv
+iconv_open to from =
+    withCString to $
+        \cto -> withCString from $
+            \cfrom -> do
+	        throwErrnoIf err_ptr "iconv_open"
+		    $ c_iconv_open cto cfrom
+
+
+iconv_close :: IConv -> IO ()
+iconv_close ic =
+    throwErrnoIfMinus1_ "iconv_close" $ c_iconv_close ic
+
+outbuf_size :: Int
+outbuf_size = 1024
+
+do_iconv :: ((Ptr a, Int) -> IO String) -> IConv -> (Ptr b, Int) -> IO String
+do_iconv get_string_fn ic (inbuf, inbuf_bytes) =
+    alloca $ \inbuf_ptr ->
+        alloca $ \inbytesleft_ptr ->
+            alloca $ \outbuf_ptr ->
+                alloca $ \outbytesleft_ptr ->
+                    allocaBytes outbuf_size $ \outbuf -> do
+      poke (inbytesleft_ptr :: Ptr CSize) (fromIntegral inbuf_bytes)
+      poke inbuf_ptr inbuf
+      let loop acc = do
+          poke (outbytesleft_ptr :: Ptr CSize) (fromIntegral outbuf_size)
+          poke outbuf_ptr outbuf
+          ret <- throw_if_not_2_big "c_iconv" $
+              c_iconv ic inbuf_ptr inbytesleft_ptr
+                         outbuf_ptr outbytesleft_ptr
+          left <- peek outbytesleft_ptr
+          res <- get_string_fn (castPtr outbuf, outbuf_size - fromIntegral left)
+          if ret == fromIntegral (-1 :: Int) then
+              loop (acc++res)
+            else
+              return (acc++res)
+      loop []
+
+
+with_iconv :: String -> String -> (IConv -> IO a) -> IO a
+with_iconv to from fn =
+    bracket (iconv_open to from) iconv_close fn
+
+iconv_ :: String -> IConv -> IO String
+iconv_ str ic =
+    withCStringLen str $ do_iconv peekCStringLen ic
+
+-- between 8-bit encodings only
+iconv :: String -> String -> String -> Either Exception String
+iconv to from str =
+    unsafePerformIO $ try $ with_iconv to from (iconv_ str)
+
+
+#ifdef HAVE_WCHAR_H
+{-
+type CUni = (#type wchar_t)
+cuni_size = (#size wchar_t)
+unicode_charset = "WCHAR_T"
+
+chartocuni :: Char -> CUni
+chartocuni = fromIntegral . ord
+
+cunitochar :: CUni -> Char
+cunitochar = chr . fromIntegral
+-}
+
+cuni_charset :: [Char]
+cuni_charset = "WCHAR_T"
+
+peek_cuni :: (Ptr (#type wchar_t), Int) -> IO String
+peek_cuni (buf, bytes) = do
+    let (chars, rembytes) = bytes `divMod` (#size wchar_t)
+    if rembytes /= 0 then
+        error "Conversion result contains remainder bytes."
+      else
+        peekCWStringLen (buf, chars)
+        --liftM (map cunitochar) $ peekArray chars buf
+
+with_cuni :: String -> ((Ptr (#type wchar_t), Int) -> IO String) -> IO String
+with_cuni str f =
+    withCWStringLen str $ \(s, l) -> f (s, l*(#size wchar_t))
+    --withArray (map chartocuni str) $ \s -> f (s, l*cuni_size)
+
+#else
+-- no CF_WCHAR_SUPPORT
+
+-- Due to endianness problems, it is easiest to do this through UTF-8
+
+cuni_charset :: [Char]
+cuni_charset = "UTF-8"
+
+peek_cuni :: CStringLen -> IO String
+peek_cuni = peekUTF8StringLen
+
+with_cuni :: [Char] -> (CStringLen -> IO a) -> IO a
+with_cuni = withUTF8StringLen
+
+#endif
+
+to_unicode_ :: String -> String -> IO String
+to_unicode_ from str =
+     with_iconv cuni_charset from $
+      \ic -> withCStringLen str $ do_iconv peek_cuni ic
+
+to_unicode :: String -> String -> Either Exception String
+to_unicode from str =
+    unsafePerformIO $ try $ to_unicode_ from str
+
+from_unicode_ :: String -> String -> IO String
+from_unicode_ to str =
+     with_iconv to cuni_charset $
+      \ic -> with_cuni str $ do_iconv peekCStringLen ic
+
+from_unicode :: String -> String -> Either Exception String
+from_unicode from str =
+    unsafePerformIO $ try $ from_unicode_ from str
+
+
+#ifndef ICONV_LIB_PREFIX
+
+foreign import ccall unsafe "iconv.h iconv_open" c_iconv_open
+    :: CString -> CString -> IO IConv
+
+foreign import ccall unsafe "iconv.h iconv_close" c_iconv_close
+    :: IConv -> IO CInt
+
+foreign import ccall unsafe "iconv.h iconv" c_iconv
+    :: IConv -> Ptr a -> Ptr CSize -> Ptr b -> Ptr CSize -> IO CSize
+
+#else
+
+foreign import ccall unsafe "iconv.h libiconv_open" c_iconv_open
+    :: CString -> CString -> IO IConv
+
+foreign import ccall unsafe "iconv.h libiconv_close" c_iconv_close
+    :: IConv -> IO CInt
+
+foreign import ccall unsafe "iconv.h libiconv" c_iconv
+    :: IConv -> Ptr a -> Ptr CSize -> Ptr b -> Ptr CSize -> IO CSize
+
+#endif
diff --git a/UI/HSCurses/Logging.hs b/UI/HSCurses/Logging.hs
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/Logging.hs
@@ -0,0 +1,75 @@
+{-# LANGUAGE CPP #-}
+
+-- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+module UI.HSCurses.Logging (trace,debug) where
+
+import Control.Monad.Trans
+
+#ifdef __DEBUG__
+
+import Data.IORef
+import System.IO
+import System.IO.Unsafe (unsafePerformIO)
+import System.Locale
+import System.Time
+
+#endif
+
+
+trace :: String -> a -> a
+debug :: MonadIO m => String -> m ()
+
+#ifdef __DEBUG__
+
+logFile :: Handle
+logFile = unsafePerformIO $ do h <- openFile ".hscurses.log" AppendMode
+                               debug_ h "logging initialized"
+                               return h
+{-# NOINLINE logFile #-}
+
+formatTime :: IO String
+formatTime =
+    do let fmt = "%Y-%m-%d %H:%M:%S"
+       clockT <- getClockTime
+       calTime <- toCalendarTime clockT
+       let maxSdecLen = 5
+           sdec' = show $ ctPicosec calTime
+           sdec = if length sdec' > maxSdecLen
+                     then take maxSdecLen sdec'
+                     else sdec'
+       return (formatCalendarTime defaultTimeLocale fmt calTime
+               ++ ":" ++ sdec)
+
+trace s x =
+    unsafePerformIO $ do debug s
+                         return x
+
+debug s = liftIO $ debug_ logFile s
+
+debug_ f s =
+    do ts <- formatTime
+       hPutStrLn f ("[" ++ ts ++ "] " ++ s)
+       hFlush f
+
+#else
+
+trace _ x = x
+
+debug _ = return ()
+
+#endif
diff --git a/UI/HSCurses/MonadException.hs b/UI/HSCurses/MonadException.hs
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/MonadException.hs
@@ -0,0 +1,145 @@
+-- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+module UI.HSCurses.MonadException where
+
+import Prelude hiding (catch)
+import Control.Exception
+import Control.Monad.State
+import Data.Dynamic
+
+class Monad m => MonadExc m where
+    catchM      :: m a -> (Exception -> m a) -> m a
+    blockM      :: m a -> m a
+    unblockM    :: m a -> m a
+
+
+class (MonadIO m, MonadExc m) => MonadExcIO m
+
+--
+-- Operations implemented in term of catchM, blockM and unblockM
+-- (taken from Control.Exception).
+--
+
+catchJustM :: MonadExc m =>
+       (Exception -> Maybe b) -- ^ Predicate to select exceptions
+    -> m a                    -- ^ Computation to run
+    -> (b -> m a)             -- ^ Handler
+    -> m a
+catchJustM p a handler = catchM a handler'
+  where handler' e = case p e of
+            Nothing -> throw e
+            Just b  -> handler b
+
+handleM :: MonadExc m => (Exception -> m a) -> m a -> m a
+handleM = flip catchM
+
+handleJustM :: MonadExc m =>
+              (Exception -> Maybe b) -> (b -> m a) -> m a -> m a
+handleJustM p = flip (catchJustM p)
+
+tryM :: MonadExc m => m a -> m (Either Exception a)
+tryM a = catchM (a >>= \ v -> return (Right v)) (\e -> return (Left e))
+
+tryJustM :: MonadExc m => (Exception -> Maybe b) -> m a -> m (Either b a)
+tryJustM p a = do
+  r <- tryM a
+  case r of
+    Right v -> return (Right v)
+    Left  e -> case p e of
+            Nothing -> throw e
+            Just b  -> return (Left b)
+
+catchDynM :: (MonadExc m, Typeable exc) =>
+             m a -> (exc -> m a) -> m a
+catchDynM m k = catchM m handl
+  where handl ex = case ex of
+               (DynException dyn) ->
+                case fromDynamic dyn of
+                    Just exception  -> k exception
+                    Nothing -> throw ex
+               _ -> throw ex
+
+bracketM :: MonadExc m =>
+       m a         -- ^ computation to run first (\"acquire resource\")
+    -> (a -> m b)  -- ^ computation to run last (\"release resource\")
+    -> (a -> m c)  -- ^ computation to run in-between
+    -> m c         -- returns the value from the in-between computation
+bracketM before after thing =
+  blockM (do
+    a <- before
+    r <- catchM
+       (unblockM (thing a))
+       (\e -> do { after a; throw e })
+    after a
+    return r
+  )
+
+bracketM_ :: MonadExc m => m a -> m b -> m c -> m c
+bracketM_ before after thing = bracketM before (const after) (const thing)
+
+finally :: IO a -- ^ computation to run first
+    -> IO b     -- ^ computation to run afterward (even if an exception
+                --   was raised)
+    -> IO a     -- returns the value from the first computation
+a `finally` sequel =
+  blockM (do
+    r <- catchM
+         (unblockM a)
+         (\e -> do { sequel; throw e })
+    sequel
+    return r
+  )
+
+
+--
+-- Instance declarations
+--
+
+instance MonadExc IO where
+    catchM       = catch
+    blockM       = block
+    unblockM     = unblock
+
+instance MonadExcIO IO
+
+instance MonadExc m => MonadExc (StateT s m) where
+    catchM   = catchState
+    blockM   = blockState
+    unblockM = unblockState
+
+instance (MonadExc m, MonadIO m) => MonadExcIO (StateT s m)
+
+modifyState :: MonadExc m => (s -> m (a, s)) -> StateT s m a
+modifyState f =
+    do oldState <- get
+       (x, newState) <- lift $ f oldState
+       put newState
+       return x
+
+catchState :: (MonadExc m) => StateT s m a -> (Exception -> StateT s m a)
+           -> StateT s m a
+catchState run handler =
+    modifyState (\oldState -> runStateT run oldState `catchM`
+                              (\e -> runStateT (handler e) oldState))
+
+blockState, unblockState :: (MonadExc m) => StateT s m a -> StateT s m a
+blockState run =
+    modifyState (\oldState -> blockM (runStateT run oldState))
+
+unblockState run =
+    modifyState (\oldState -> unblockM (runStateT run oldState))
+
diff --git a/UI/HSCurses/Widgets.hs b/UI/HSCurses/Widgets.hs
new file mode 100644
--- /dev/null
+++ b/UI/HSCurses/Widgets.hs
@@ -0,0 +1,951 @@
+{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification #-}
+-- glasgow-exts needed for existentials and multi-parameter type classes.
+
+-- Copyright (c) 2005 Stefan Wehr - http://www.stefanwehr.de
+--
+-- This library is free software; you can redistribute it and/or
+-- modify it under the terms of the GNU Lesser General Public
+-- License as published by the Free Software Foundation; either
+-- version 2.1 of the License, or (at your option) any later version.
+--
+-- This library is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+-- Lesser General Public License for more details.
+--
+-- You should have received a copy of the GNU Lesser General Public
+-- License along with this library; if not, write to the Free Software
+-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+module UI.HSCurses.Widgets where
+
+import Control.Exception (assert)
+import Control.Monad.Trans
+import Data.Char
+import Data.List
+import Data.Maybe
+
+import UI.HSCurses.Logging
+import UI.HSCurses.MonadException
+import qualified UI.HSCurses.Curses as Curses
+import qualified UI.HSCurses.CursesHelper as CursesH
+
+type Pos = (Int, Int)
+type Offset = (Int, Int)
+
+type Size = (Int, -- height
+             Int  -- width
+            )
+
+getHeight :: Size -> Int
+getHeight = fst
+
+getWidth :: Size -> Int
+getWidth = snd
+
+getYOffset :: Offset -> Int
+getYOffset = fst
+
+getXOffset :: Offset -> Int
+getXOffset = snd
+
+getYPos :: Pos -> Int
+getYPos = fst
+
+getXPos :: Pos -> Int
+getXPos = snd
+
+data Direction = DirLeft | DirRight | DirUp | DirDown
+               deriving (Eq, Show, Ord)
+
+data HAlignment = AlignLeft | AlignCenter | AlignRight
+               deriving (Eq, Show)
+
+data Cont a = Cont a | Done a
+
+class Widget a where
+    draw      :: Pos -> Size -> DrawingHint -> a -> IO ()
+    minSize   :: a -> Size
+
+class Widget a => ActiveWidget a where
+    activate  :: MonadExcIO m => m () -> Pos -> Size -> a -> m (a, String)
+
+type KeyHandler a = Pos -> Size -> a -> IO (Cont a)
+
+mkKeyHandler :: (Pos -> Size -> a -> a)
+                -> KeyHandler a
+mkKeyHandler f pos sz w = return (Cont (f pos sz w))
+
+--
+-- Drawing
+--
+
+data DrawingHint = DHNormal
+                 | DHFocus
+                 | DHActive
+                   deriving (Eq, Show, Ord)
+
+data DrawingStyle = DStyle
+    { dstyle_normal      :: CursesH.CursesStyle
+    , dstyle_focus       :: CursesH.CursesStyle
+    , dstyle_active      :: CursesH.CursesStyle
+    } deriving (Eq, Show)
+
+
+mkDrawingStyle :: CursesH.CursesStyle -> DrawingStyle
+mkDrawingStyle defStyle =
+    let revStyle = CursesH.changeCursesStyle defStyle [CursesH.Reverse]
+        in DStyle { dstyle_normal = defStyle
+                  , dstyle_focus = revStyle
+                  , dstyle_active = revStyle
+                  }
+
+defaultDrawingStyle :: DrawingStyle
+defaultDrawingStyle = mkDrawingStyle CursesH.defaultCursesStyle
+_draw :: DrawingHint -> DrawingStyle -> IO a -> IO a
+_draw DHActive sty io = CursesH.withStyle (dstyle_active sty) io
+_draw DHNormal sty io = CursesH.withStyle (dstyle_normal sty) io
+_draw DHFocus sty io = CursesH.withStyle (dstyle_focus sty) io
+
+--
+-- Helper functions for scrolling
+--
+
+scrollFactor :: Double
+scrollFactor = 0.8
+
+scrollBy :: Int -> Int
+scrollBy displayLen =
+    let amount = floor ((fromInteger . toInteger) displayLen * scrollFactor)
+    in max (displayLen - 1) (min 1 amount)
+
+-- returns the new offset for scrolling in forward direction
+-- dataLen: total number of data items
+-- offset: the index of the first data item shown on the current page
+-- displayLen: the number of data items that is shown in one page
+scrollForward :: Int -> Int -> Int -> Int
+scrollForward dataLen offset displayLen =
+    if offset + displayLen >= dataLen
+       then offset
+       else min (offset + scrollBy displayLen) (dataLen - displayLen)
+
+-- returns the new offset for scrolling in backward direction.
+-- parameters as for scrollForward
+scrollBackward :: t -> Int -> Int -> Int
+scrollBackward _ offset displayLen =
+    if offset == 0
+       then offset
+       else max (offset - scrollBy displayLen) 0
+
+
+--
+-- EmptyWidget
+--
+
+data EmptyWidget = EmptyWidget Size
+
+instance Widget EmptyWidget where
+    draw _ _ _ _ = return ()
+    minSize (EmptyWidget sz) = sz
+
+
+--
+-- An opaque widget
+--
+
+data OpaqueWidget = OpaqueWidget Size
+
+instance Widget OpaqueWidget where
+    draw (y,x) (h,w) _ _ =
+        let draw' n =
+                do Curses.wMove Curses.stdScr (y+n) x
+                   CursesH.drawLine w ""
+        in do mapM draw' (take h [0..])
+              Curses.refresh
+    minSize (OpaqueWidget sz) = sz
+
+--
+-- Widget for text input
+--
+
+data EditWidget = EditWidget
+    { ew_content       :: String,
+      ew_xoffset       :: Int, -- content!!xoffset is the 1st char shown
+      ew_xcursor       :: Int, -- cursor position
+      ew_history       :: [String],
+      ew_historyIndex  :: Int,
+      ew_historySavedContent :: Maybe String,
+      ew_options       :: EditWidgetOptions
+    }
+
+ew_contentPos :: EditWidget -> Int
+ew_contentPos ew = ew_xcursor ew + ew_xoffset ew
+
+instance Widget EditWidget where
+    draw = drawEditWidget
+    minSize ew = (1, ewopt_minWidth $ ew_options ew)
+
+instance ActiveWidget EditWidget where
+    activate = activateEditWidget
+
+data EditWidgetOptions = EWOptions
+    { ewopt_keyHandlers    :: [(Curses.Key, KeyHandler EditWidget)],
+      ewopt_minWidth       :: Int,
+      ewopt_style          :: DrawingStyle
+    }
+
+defaultEWOptions :: EditWidgetOptions
+defaultEWOptions = EWOptions
+                   { ewopt_keyHandlers = editWidgetKeyHandlers,
+                     ewopt_minWidth = 8,
+                     ewopt_style = defaultDrawingStyle
+                   }
+
+newEditWidget :: EditWidgetOptions -> String -> EditWidget
+newEditWidget opts =
+    editWidgetSetContent
+      (EditWidget
+       { ew_content = "",
+         ew_xoffset = 0,
+         ew_xcursor = 0,
+         ew_history = [],
+         ew_historyIndex = -1,
+         ew_historySavedContent = Nothing,
+         ew_options = opts
+       })
+
+
+
+editWidgetGoLeft :: Pos
+                                                -> Size
+                                                -> EditWidget
+                                                -> IO (Cont EditWidget)
+editWidgetGoLeft = mkKeyHandler editWidgetGoLeft'
+editWidgetGoRight :: Pos
+                                                 -> Size
+                                                 -> EditWidget
+                                                 -> IO (Cont EditWidget)
+editWidgetGoRight = mkKeyHandler editWidgetGoRight'
+editWidgetDeleteLeft :: Pos
+                                                    -> Size
+                                                    -> EditWidget
+                                                    -> IO (Cont EditWidget)
+editWidgetDeleteLeft = mkKeyHandler editWidgetDeleteLeft'
+editWidgetDeleteUnderCursor :: Pos
+                                                           -> Size
+                                                           -> EditWidget
+                                                           -> IO (Cont EditWidget)
+editWidgetDeleteUnderCursor = mkKeyHandler editWidgetDeleteUnderCursor'
+editWidgetDeleteToEnd :: Pos
+                                                     -> Size
+                                                     -> EditWidget
+                                                     -> IO (Cont EditWidget)
+editWidgetDeleteToEnd = mkKeyHandler editWidgetDeleteToEnd'
+editWidgetGoHome :: Pos
+                                                -> Size
+                                                -> EditWidget
+                                                -> IO (Cont EditWidget)
+editWidgetGoHome = mkKeyHandler editWidgetGoHome'
+editWidgetGoEnd :: Pos
+                                               -> Size
+                                               -> EditWidget
+                                               -> IO (Cont EditWidget)
+editWidgetGoEnd = mkKeyHandler editWidgetGoEnd'
+editWidgetHistoryUp :: Pos
+                                                   -> Size
+                                                   -> EditWidget
+                                                   -> IO (Cont EditWidget)
+editWidgetHistoryUp = mkKeyHandler editWidgetHistoryUp'
+editWidgetHistoryDown :: Pos
+                                                     -> Size
+                                                     -> EditWidget
+                                                     -> IO (Cont EditWidget)
+editWidgetHistoryDown = mkKeyHandler editWidgetHistoryDown'
+
+editWidgetKeyHandlers :: [(Curses.Key,
+                                                       Pos
+                                                       -> Size
+                                                       -> EditWidget
+                                                       -> IO (Cont EditWidget))]
+editWidgetKeyHandlers =
+    [(Curses.KeyLeft, editWidgetGoLeft),
+     (Curses.KeyRight, editWidgetGoRight),
+     (Curses.KeyBackspace, editWidgetDeleteLeft),
+     (Curses.KeyChar '\^D', editWidgetDeleteUnderCursor),
+     (Curses.KeyDC, editWidgetDeleteUnderCursor),
+     (Curses.KeyChar '\^K', editWidgetDeleteToEnd),
+     (Curses.KeyHome, editWidgetGoHome),
+     (Curses.KeyChar '\^A', editWidgetGoHome),
+     (Curses.KeyEnd, editWidgetGoEnd),
+     (Curses.KeyChar '\^E', editWidgetGoEnd),
+     (Curses.KeyChar '\r', editWidgetFinish),
+     (Curses.KeyChar '\t', editWidgetFinish),
+     (Curses.KeyUp, editWidgetHistoryUp),
+     (Curses.KeyDown, editWidgetHistoryDown)
+    ]
+
+editWidgetGetContent :: EditWidget -> String
+editWidgetGetContent ew = ew_content ew
+editWidgetSetContent :: EditWidget
+                                                    -> String
+                                                    -> EditWidget
+editWidgetSetContent ew s =
+    addToHistory (ew { ew_content = s, ew_xoffset = 0, ew_xcursor = 0 }) s
+
+editWidgetGetOptions :: EditWidget
+                                                    -> EditWidgetOptions
+editWidgetGetOptions ew = ew_options ew
+editWidgetSetOptions :: EditWidget
+                                                    -> EditWidgetOptions
+                                                    -> EditWidget
+editWidgetSetOptions ew opts = ew { ew_options = opts }
+
+drawEditWidget :: Pos -> Size -> DrawingHint -> EditWidget -> IO ()
+drawEditWidget (y, x) (_, width) hint ew =
+    _draw hint (ewopt_style . ew_options $ ew) $
+    do Curses.wMove Curses.stdScr y x
+       CursesH.drawLine width (drop (ew_xoffset ew) $ ew_content ew)
+       Curses.refresh
+
+activateEditWidget :: MonadExcIO m => m () -> Pos -> Size
+                   -> EditWidget -> m (EditWidget, String)
+activateEditWidget refresh pos@(y, x) sz@(_, width) ew =
+    CursesH.withCursor Curses.CursorVisible $ processKey ew
+    where
+    processKey ex =
+        do liftIO $ drawLocal ex
+           k <- CursesH.getKey refresh
+           case lookup k (ewopt_keyHandlers $ ew_options ex) of
+             Nothing ->
+                 case k of
+                   Curses.KeyChar c | isAscii c && isPrint c
+                       -> processKey $ insertChar ex c
+                   _   -> processKey ex
+             Just f  ->
+                 do x' <- liftIO $ f pos sz ex
+                    case x' of
+                      Cont ex' -> processKey ex'
+                      Done ex' -> do liftIO $ drawEditWidget pos sz DHActive ex'
+                                     return (ex', editWidgetGetContent ex')
+    insertChar ew' c =
+        let pos' = ew_contentPos ew'
+            oldContent = ew_content ew'
+            newContent = take pos' oldContent ++ (c : drop pos' oldContent)
+            in editWidgetGoRight' pos' sz (ew' { ew_content = newContent })
+    drawLocal ew' = _draw DHActive  (ewopt_style . ew_options $ ew') $
+        do Curses.wMove Curses.stdScr y x
+           CursesH.drawLine width (drop (ew_xoffset ew') $ ew_content ew')
+           Curses.wMove Curses.stdScr y (x + ew_xcursor ew')
+           Curses.refresh
+
+editWidgetGoLeft' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetGoLeft' _ _ ew =
+    let newXcursor = max (ew_xcursor ew - 1) 0
+        newXoffset = if ew_xcursor ew == 0
+                        then max (ew_xoffset ew - 1) 0
+                        else ew_xoffset ew
+        in ew { ew_xoffset = newXoffset,
+                ew_xcursor = newXcursor }
+
+editWidgetGoRight' :: t -> (t1, Int) -> EditWidget -> EditWidget
+editWidgetGoRight' _ (_, width) ew =
+    let len = length (ew_content ew)
+        lastChar = len - ew_xoffset ew - 1
+        newXcursor = minimum [ew_xcursor ew + 1, lastChar + 1, width - 1]
+        newXoffset = if ew_xcursor ew == width - 1
+                        then min (ew_xoffset ew + 1) (len - width + 1)
+                        else ew_xoffset ew
+        in ew { ew_xoffset = newXoffset,
+                ew_xcursor = newXcursor }
+
+editWidgetDeleteLeft' :: Pos -> Size -> EditWidget -> EditWidget
+editWidgetDeleteLeft' pos sz ew =
+    let cpos = ew_contentPos ew - 1
+        oldContent = ew_content ew
+        newContent = take cpos oldContent ++ drop (cpos+1) oldContent
+        ew' = editWidgetGoLeft' pos sz (ew { ew_content = newContent })
+        in if ew_xcursor ew == 0 && ew_xoffset ew /= 0
+              then editWidgetGoRight' pos sz (editWidgetGoLeft' pos sz ew')
+              else ew'
+
+editWidgetDeleteUnderCursor' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetDeleteUnderCursor' _ _ ew =
+    let pos = ew_contentPos ew
+        oldContent = ew_content ew
+        newContent = take pos oldContent ++ drop (pos+1) oldContent
+        in ew { ew_content = newContent }
+
+editWidgetDeleteToEnd' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetDeleteToEnd' _ _ ew =
+    let pos = ew_contentPos ew
+        oldContent = ew_content ew
+        newContent = take pos oldContent
+        in ew { ew_content = newContent }
+
+editWidgetGoHome' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetGoHome' _ _ ew =
+    ew { ew_xcursor = 0,
+         ew_xoffset = 0 }
+
+editWidgetGoEnd' :: Pos -> Size -> EditWidget -> EditWidget
+editWidgetGoEnd' pos sz ew =
+    let cpos = ew_contentPos ew
+        len = length (ew_content ew)
+        in if cpos == len
+              then ew
+              else editWidgetGoEnd' pos sz (editWidgetGoRight' pos sz ew)
+
+editWidgetFinish :: (Monad m) => t -> t1 -> EditWidget -> m (Cont EditWidget)
+editWidgetFinish _ _ ew =  return (Done (addToHistory ew (ew_content ew)))
+
+maxHistoryLength :: Int
+maxHistoryLength = 50
+
+addToHistory :: EditWidget -> [Char] -> EditWidget
+addToHistory ew s =
+    let newHist = if not (null s)
+                     then take maxHistoryLength (s : ew_history ew)
+                     else ew_history ew
+        in ew { ew_history = newHist, ew_historyIndex = -1,
+                ew_historySavedContent = Nothing }
+
+editWidgetHistoryUp' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetHistoryUp' _ _ ew = editWidgetHistory (+) ew
+
+editWidgetHistoryDown' :: t -> t1 -> EditWidget -> EditWidget
+editWidgetHistoryDown' _ _ ew = editWidgetHistory (-) ew
+
+-- ew_historyList: list of history items, i.e. non-null strings which were
+--   entered into the widget and confirmed with ENTER or which were added
+--   via editWidgetSetContent.
+-- ew_historyIndex: the index of the history item shown in the widget. The
+--   value -1 means that the value saved in ew_historySavedContent should
+--   be shown.
+editWidgetHistory :: (Num t) => (Int -> t -> Int) -> EditWidget -> EditWidget
+editWidgetHistory op ew =
+    let i = ew_historyIndex ew
+        l = ew_history ew
+        j =  i `op` 1
+        in if j >= 0 && j < length l
+              then let savedContent =
+                           case ew_historySavedContent ew of
+                             Nothing -> Just (ew_content ew)
+                             x -> x
+                       in ew { ew_historyIndex = j, ew_content = l!!j,
+                               ew_historySavedContent = savedContent,
+                               ew_xcursor = 0, ew_xoffset = 0 }
+              else if j == -1
+                      then case ew_historySavedContent ew of
+                             Nothing -> ew
+                             Just x -> ew { ew_content = x,
+                                            ew_historyIndex = j,
+                                            ew_xcursor = 0,
+                                            ew_xoffset = 0  }
+                   else ew
+
+
+
+--
+-- Text widget
+--
+
+data TextWidget = TextWidget
+    { tw_text           :: String,
+      tw_yoffset        :: Int,
+      tw_xoffset        :: Int,
+      tw_options        :: TextWidgetOptions
+    }
+    deriving (Eq, Show)
+
+instance Widget TextWidget where
+    draw = drawTextWidget
+    minSize tw =
+        case twopt_size $ tw_options tw of
+          TWSizeDefault -> let l = lines (tw_text tw)
+                           in (length l, if null l then 0 else maximum (map length l))
+          TWSizeFixed sz -> sz
+
+data TextWidgetSize = TWSizeDefault    -- minimal size determined by content
+                    | TWSizeFixed Size -- minimal size is fixed, content is
+                                       -- possibly cut off
+                      deriving (Eq, Show)
+                                 {-
+                    | Autowrap   -- minimal width determined by content,
+                                 -- but lines are wrapped if necessary
+                                 -}
+
+data TextWidgetOptions = TWOptions
+    { twopt_size   :: TextWidgetSize,
+      twopt_style  :: DrawingStyle,
+      twopt_halign :: HAlignment }
+    deriving (Eq, Show)
+
+defaultTWOptions :: TextWidgetOptions
+defaultTWOptions = TWOptions
+                { twopt_size = TWSizeDefault,
+                  twopt_style = defaultDrawingStyle,
+                  twopt_halign = AlignLeft }
+
+newTextWidget :: TextWidgetOptions -> String -> TextWidget
+newTextWidget opts s = TextWidget
+                       { tw_text = s,
+                         tw_yoffset = 0,
+                         tw_xoffset = 0,
+                         tw_options = opts
+                       }
+
+drawTextWidget :: Pos -> Size -> DrawingHint -> TextWidget -> IO ()
+drawTextWidget (y, x) (height, width) hint tw =
+    let ly = take height $ drop (tw_yoffset tw) (lines (tw_text tw))
+        l = take height $ (map (drop (tw_xoffset tw)) ly ++ repeat [])
+        l' = map (align (twopt_halign $ tw_options tw) width ' ') l
+    in --trace ("drawing text widget at " ++ show pos ++ " with size " ++ show sz) $
+       do _draw hint (twopt_style . tw_options $ tw)
+                      (mapM drawLine $ zip l' [0..])
+          Curses.refresh
+    where drawLine (s, i) =
+              do Curses.wMove Curses.stdScr (y + i) x
+                 CursesH.drawLine width s
+
+textWidgetGetText :: TextWidget -> String
+textWidgetGetText = tw_text
+
+textWidgetSetText :: TextWidget -> String -> TextWidget
+textWidgetSetText tw s = tw { tw_text = s }
+
+textWidgetScrollDown :: Size -> TextWidget -> TextWidget
+textWidgetScrollDown (h, _) tw =
+    let dataLen = length $ lines (tw_text tw)
+        offset = tw_yoffset tw
+        in tw { tw_yoffset = scrollForward dataLen offset h }
+
+textWidgetScrollUp :: Size -> TextWidget -> TextWidget
+textWidgetScrollUp (h, _) tw =
+    let dataLen = length $ lines (tw_text tw)
+        offset = tw_yoffset tw
+        in tw { tw_yoffset = scrollBackward dataLen offset h }
+
+textWidgetScrollLeft :: Size -> TextWidget -> TextWidget
+textWidgetScrollLeft (_, w) tw =
+    let dataLen = length $ lines (tw_text tw)
+        offset = tw_xoffset tw
+        in tw { tw_xoffset = scrollBackward dataLen offset w }
+
+textWidgetScrollRight :: Size -> TextWidget -> TextWidget
+textWidgetScrollRight (_, w) tw =
+    let dataLen = length $ lines (tw_text tw)
+        offset = tw_xoffset tw
+        in tw { tw_xoffset = scrollForward dataLen offset w }
+
+
+--
+-- Table widget
+--
+
+data TableCell = forall w. Widget w => TableCell w
+               | forall w. ActiveWidget w => ActiveTableCell w
+
+isActive :: TableCell -> Bool
+isActive (TableCell _) = False
+isActive (ActiveTableCell _) = True
+
+instance Widget TableCell where
+    draw pos sz hint (TableCell w) = draw pos sz hint w
+    draw pos sz hint (ActiveTableCell w) = draw pos sz hint w
+    minSize (TableCell w) = minSize w
+    minSize (ActiveTableCell w) = minSize w
+
+_activateTableCell :: MonadExcIO m => m () -> Pos -> Size
+                   -> TableCell -> m (TableCell, String)
+_activateTableCell _ _ _ (TableCell _) =
+    error "_activateTableCell: cannot activate non-active cell!"
+_activateTableCell refresh pos sz (ActiveTableCell w) =
+    do (new, res) <- activate refresh pos sz w
+       return (ActiveTableCell new, res)
+
+type Row = [TableCell]
+
+singletonRow :: TableCell -> Row
+singletonRow tc = [tc]
+
+getCellWidget :: TableWidget -> (Int, Int) -> TableCell
+getCellWidget tbw (row, col) = (tbw_rows tbw) !! row !! col
+
+setCellWidget :: TableWidget -> (Int, Int) -> TableCell -> TableWidget
+setCellWidget tbw (rowIndex, colIndex) w =
+    let rows = tbw_rows tbw
+        row = rows !! rowIndex
+        newRow = listReplace row w colIndex
+        newRows = listReplace rows newRow rowIndex
+        in tbw { tbw_rows = newRows }
+
+data TableWidget = TableWidget
+    { tbw_rows     :: [Row],
+      tbw_colOffset  :: Int,
+      tbw_pos      :: Maybe Pos,
+      tbw_options  :: TableWidgetOptions }
+
+data FillRow = First | Last | None deriving (Eq,Show)
+
+data TableWidgetOptions = TBWOptions
+    { tbwopt_fillCol    :: Maybe Int,
+      tbwopt_fillRow    :: FillRow,
+      tbwopt_activeCols :: [Int],
+      tbwopt_minSize    :: Size }
+    deriving (Eq, Show)
+
+defaultTBWOptions :: TableWidgetOptions
+defaultTBWOptions = TBWOptions
+                    { tbwopt_fillCol = Nothing,
+                      tbwopt_fillRow = None,
+                      tbwopt_activeCols = [],
+                      tbwopt_minSize = (4, 10) }
+
+instance Widget TableWidget where
+    draw      = drawTableWidget
+    minSize   = tbwopt_minSize . tbw_options
+
+newTableWidget :: TableWidgetOptions -> [Row] -> TableWidget
+newTableWidget opts rows = TableWidget
+                              { tbw_rows = rows,
+                                tbw_colOffset = 0,
+                                tbw_pos = findFirstActiveCell rows opts,
+                                tbw_options = opts }
+
+data TableWidgetDisplayInfo =
+    TBWDisplayInfo
+    { tbwdisp_height     :: Int   -- height of the display area
+    , tbwdisp_width      :: Int   -- width of the display area
+    , tbwdisp_firstVis   :: Int   -- index of the first row visible
+    , tbwdisp_lastVis    :: Int   -- index of the last row visible
+    , tbwdisp_rows       :: [Row] -- the rows which are visible
+    , tbwdisp_nrows      :: Int   -- the number of rows visible
+    , tbwdisp_heights    :: [Int] -- the heights of the visible rows
+    , tbwdisp_widths     :: [Int] -- the widths of the visible rows
+      -- free space at the right side (xoffset, size)
+    , tbwdisp_rightMargin :: Maybe (Int, Size)
+    }
+
+tableWidgetDisplayInfo :: Size -> TableWidget -> TableWidgetDisplayInfo
+tableWidgetDisplayInfo (height, width) tbw =
+    assert (isQuadratic (tbw_rows tbw)) $
+    let allRows = tbw_rows tbw
+        ncols = length (allRows!!0)
+        colOffset = tbw_colOffset tbw
+        allHeights = minSpaces getHeight allRows
+        heights' = drop colOffset allHeights
+        nrows = getNRows heights' 0 0
+        rows = take nrows $ drop colOffset allRows
+        (heights, heightDummy) =
+            let hs = take nrows heights'
+                s = sum hs
+                d = height - s
+                in case tbwopt_fillRow $ tbw_options tbw of
+                     First -> (applyToFirst (+d) hs, 0)
+                     Last -> (applyToLast (+d) hs, 0)
+                     None -> (hs, d)
+        widths' = minSpaces getWidth (transpose $ tbw_rows tbw)
+        (widths, rightMargin) =
+            if sum widths' > width
+               then error ("table to wide: width=" ++ show (sum widths') ++
+                           ", available width=" ++ show width)
+               else case tbwopt_fillCol $ tbw_options tbw of
+                      Just i | i >= 0 && i < ncols
+                                 -> (take i widths' ++
+                                     let rest = drop i widths'
+                                     in (head rest + width - sum widths') : tail rest
+                                    , Nothing)
+                      _ -> let diff = width - sum widths'
+                               msz = (height, diff)
+                               m = if diff > 0 then Just (sum widths', msz)
+                                   else Nothing
+                           in (widths', m)
+        dummyHeights = if heightDummy == 0 then [] else [heightDummy]
+        dummyRows = if heightDummy == 0 then []
+                    else [map (\w -> TableCell (OpaqueWidget (heightDummy, w)))
+                          widths]
+        in TBWDisplayInfo
+               { tbwdisp_height = height
+               , tbwdisp_width = width
+               , tbwdisp_firstVis = colOffset
+               , tbwdisp_lastVis = colOffset + nrows - 1
+               , tbwdisp_rows = rows ++ dummyRows
+               , tbwdisp_nrows = nrows + length dummyRows
+               , tbwdisp_heights = heights ++ dummyHeights
+               , tbwdisp_widths = widths
+               , tbwdisp_rightMargin = rightMargin
+               }
+    where
+        minSpaces f ls =
+            snd $ mapAccumL
+                    (\acc ws ->
+                       (acc, acc + maximum (map (f . minSize) ws)))
+                    0 ls
+        getNRows (h:hs) n acc | h + n <= height = getNRows hs (h+n) (acc+1)
+        getNRows _ _ acc = acc
+        isQuadratic [] = True
+        isQuadratic (x:xs) = isQuadratic' xs (length x)
+        isQuadratic' (x:xs) n = length x == n && isQuadratic' xs n
+        isQuadratic' [] _ = True
+        applyToFirst _ [] = []
+        applyToFirst f (x:xs) = f x : xs
+        applyToLast _ [] = []
+        applyToLast f l =
+            let (h, t) = (head $ reverse l, tail $ reverse l)
+                in reverse $ f h : t
+
+getCellInfo :: Pos -> Size -> TableWidget -> (Int,Int) -> (Pos, Size)
+getCellInfo (y,x) sz tbw (row, col) =
+    let info = tableWidgetDisplayInfo sz tbw
+        heights = tbwdisp_heights info
+        widths = tbwdisp_widths info
+        h = heights !! row
+        w = widths !! col
+        yoff = sum $ take row heights
+        xoff = sum $ take col widths
+        in ((y+yoff, x+xoff), (h, w))
+
+drawTableWidget :: Pos -> Size -> DrawingHint -> TableWidget -> IO ()
+drawTableWidget (y, x) sz hint tbw =
+    let info = tableWidgetDisplayInfo sz tbw
+        heights = tbwdisp_heights info
+        widths = tbwdisp_widths info
+        firstVis = tbwdisp_firstVis info
+        rows = tbwdisp_rows info
+        rightMargin = tbwdisp_rightMargin info
+        in do drawRows rows heights widths 0 firstVis hint
+              case rightMargin of
+                Nothing -> return ()
+                Just (xoff,s) -> draw (y,x+xoff) s hint (OpaqueWidget s)
+              Curses.refresh
+    where drawRows :: [Row] -> [Int] -> [Int] -> Int -> Int
+                   -> DrawingHint -> IO ()
+          drawRows [] _ _ _ _ _ = return ()
+          drawRows (r:rs) (h:hs) widths yoffset rowIndex hint' =
+            do drawCols r h widths yoffset 0 (rowIndex, 0) hint'
+               drawRows rs hs widths (yoffset + h) (rowIndex + 1) hint'
+          drawCols :: Row -> Int -> [Int] -> Int -> Int -> (Int, Int)
+                   -> DrawingHint -> IO ()
+          drawCols [] _ _ _ _ _ _ = return ()
+          drawCols (c:cs) h (w:ws) yoffset xoffset (rowIndex, colIndex) hint' =
+            let hint'' = case tbw_pos tbw of
+                           Just (z, a) | z == rowIndex && a == colIndex
+                               -> DHFocus
+                           _ -> hint'
+            in do draw (y+yoffset, x+xoffset) (h,w) hint'' c
+                  drawCols cs h ws yoffset (xoffset + w)
+                           (rowIndex, colIndex+1) hint'
+
+
+tableWidgetScrollDown :: Size -> TableWidget -> TableWidget
+tableWidgetScrollDown (h, _) tbw =
+    let dataLen = length $ tbw_rows tbw
+        offset = tbw_colOffset tbw
+        newOffset = scrollForward dataLen offset h
+        newTbw = tbw { tbw_colOffset = newOffset }
+        in case tbw_pos newTbw of
+             Nothing -> newTbw
+             Just (y,x) -> newTbw { tbw_pos = Just (max newOffset y, x) }
+
+tableWidgetScrollUp :: Size -> TableWidget -> TableWidget
+tableWidgetScrollUp sz@(h,_) tbw =
+    let dataLen = length $ tbw_rows tbw
+        offset = tbw_colOffset tbw
+        newOffset = scrollBackward dataLen offset h
+        newTbw = tbw { tbw_colOffset = newOffset }
+        newLastVis = tbwdisp_lastVis (tableWidgetDisplayInfo sz newTbw)
+        in case tbw_pos newTbw of
+             Nothing -> newTbw
+             Just (y,x) ->
+                 newTbw { tbw_pos = Just (min newLastVis y, x) }
+
+tableWidgetActivateCurrent :: MonadExcIO m => m () -> Pos -> Size
+                           -> DrawingHint -> TableWidget
+                           -> m (TableWidget, Maybe String)
+tableWidgetActivateCurrent refresh (y, x) sz _ tbw =
+    case tbw_pos tbw of
+      Nothing -> do debug "tableWidgetActivateCurrent: pos=Nothing"
+                    return (tbw, Nothing)
+      Just p -> let w = getCellWidget tbw p
+                    in if not $ isActive w
+                       then do debug "tableWidgetActivateCurrent: not active"
+                               return (tbw, Nothing)
+                       else activate' w p
+    where
+    activate' widget colyx@(coly, colx) =
+        let info = tableWidgetDisplayInfo sz tbw
+            vcol = colx
+            vrow = coly - tbwdisp_firstVis info
+            heights = tbwdisp_heights info
+            widths = tbwdisp_widths info
+            h = heights !! vrow
+            w = widths !! vcol
+            yoffset = sum (take vrow heights)
+            xoffset = sum (take vcol widths)
+        in do (new, res) <- _activateTableCell refresh (y+yoffset, x+xoffset)
+                              (h, w) widget
+              return (setCellWidget tbw colyx new, Just res)
+
+tableWidgetGoLeft :: Size -> TableWidget -> TableWidget
+tableWidgetGoLeft =  tableWidgetMove DirLeft
+
+tableWidgetGoRight :: Size -> TableWidget -> TableWidget
+tableWidgetGoRight =  tableWidgetMove DirRight
+
+tableWidgetGoUp :: Size -> TableWidget -> TableWidget
+tableWidgetGoUp =  tableWidgetMove DirUp
+
+tableWidgetGoDown :: Size -> TableWidget -> TableWidget
+tableWidgetGoDown =  tableWidgetMove DirDown
+
+tableWidgetMove :: Direction
+                                               -> (Int, Int)
+                                               -> TableWidget
+                                               -> TableWidget
+tableWidgetMove dir sz tbw =
+    let pos = tbw_pos tbw
+        opts = tbw_options tbw
+        nrows = length (tbw_rows tbw)
+        in case pos of
+             Nothing -> tbw
+             Just p -> case findNextActiveCell opts nrows p dir of
+                         Nothing -> tbw
+                         newP@(Just (y, _)) ->
+                             tableWidgetMakeVisible (tbw {tbw_pos=newP}) sz y
+
+tableWidgetMakeVisible :: TableWidget
+                                                      -> (Int, Int)
+                                                      -> Int
+                                                      -> TableWidget
+tableWidgetMakeVisible tbw sz@(_,_) y =
+    let info = tableWidgetDisplayInfo sz tbw
+        firstVis = tbwdisp_firstVis info
+        lastVis = tbwdisp_lastVis info
+        in if y < firstVis
+              then tableWidgetMakeVisible (tableWidgetScrollUp sz tbw) sz y
+              else if y > lastVis
+                      then tableWidgetMakeVisible
+                               (tableWidgetScrollDown sz tbw) sz y
+                      else tbw
+
+findFirstActiveCell :: [Row] -> TableWidgetOptions -> Maybe Pos
+findFirstActiveCell rows opts =
+    let nrows = length rows
+        firstActiveCells = map (\y -> findNextActiveCell opts nrows
+                                                         (y, -1) DirRight)
+                               [0..nrows-1]
+        in case catMaybes firstActiveCells of
+             [] -> Nothing
+             (x:_) -> Just x
+
+findNextActiveCell :: TableWidgetOptions -> Int  -> Pos -> Direction
+                   -> Maybe Pos
+findNextActiveCell opts nrows (y,x) dir =
+--    trace ("findNextActiveCell (opts=" ++ show opts ++ ", nrows=" ++ show nrows
+--           ++ ", pos=" ++ show pos ++ ", dir=" ++ show dir) $
+    let rows = [0..(nrows - 1)]
+        cols = sort (tbwopt_activeCols opts)
+        horiz f = case f cols x rows y of
+                    Nothing -> Nothing
+                    Just z -> Just (y, z)
+        vert f = case f rows y cols x of
+                   Nothing -> Nothing
+                   Just z -> Just (y, z)
+        res = case dir of
+                DirLeft-> horiz goLeft
+                DirRight -> horiz goRight
+                DirUp -> vert goLeft
+                DirDown -> vert goRight
+        in --trace ("result of findNextActiveCell: " ++ show res)
+           res
+    where goLeft _ _ rows a | not (a `elem` rows) = Nothing
+          goLeft cols b _ _ =
+              case reverse (takeWhile (<b) cols) of
+                [] -> Nothing
+                (c:_) -> Just c
+          goRight _ _ rows a | not (a `elem` rows) = Nothing
+          goRight cols a _ _ =
+              case dropWhile (a>=) cols of
+                [] -> Nothing
+                (b:_) -> Just b
+
+tableWidgetDeleteRow :: Int -> TableWidget -> TableWidget
+tableWidgetDeleteRow n tbw =
+    let rows = tbw_rows tbw
+        rows' = deleteAt n rows
+        pos' =
+           case tbw_pos tbw of
+             Nothing -> Nothing
+             Just (row,col) ->
+                 let row' = min row (length rows' - 1)
+                     in if row' >= 0 then Just (row', col)
+                        else Nothing
+        in tbw { tbw_rows = rows', tbw_pos = pos' }
+
+--
+-- BorderWidget
+--
+
+
+--
+-- Selection Widget
+--
+
+--
+-- Utility functions
+--
+
+-- | Join a list by some delimiter
+joinLists :: [[a]] -> [a] -> [a]
+joinLists l s = if (null l) then [] else foldr1 (\x -> \y -> x ++ s ++ y) l
+
+-- | Split a list by some delimiter
+splitList :: Eq a => [a] -> [a] -> [[a]]
+splitList d l =
+    unfoldr (\x -> if (null x)
+                      then Nothing
+                      else Just $ nextToken d [] (snd $ splitAt (length d) x))
+            (d++l)
+  where nextToken _ r [] = (r, [])
+        nextToken e r m@(h:t) | (e `isPrefixOf` m) = (r, m)
+                              | otherwise = nextToken e (r++[h]) t
+
+listReplace :: [a] -> a -> Int -> [a]
+listReplace l a i =
+    case splitAt i l of
+      (_, []) -> error ("listReplace: index to large. index="++show i++
+                        ", length="++show (length l))
+      ([], _) | i < 0 -> error ("listReplace: negative index. index="++
+                                show i)
+      (xs,(_:ys)) -> xs ++ (a:ys)
+
+--alignRows :: [[String]] -> Char -> String -> [String]
+alignRows :: [[[a]]] -> a -> [a] -> [[a]]
+alignRows rows fill delim =
+    let widths = foldr maxWidths (repeat 0) rows
+        in map (alignRow widths) rows
+    where
+    maxWidths ::  [[a]] -> [Int] -> [Int]
+    maxWidths row acc = map (uncurry max) (zip acc (map length row))
+    alignRow widths row = concatMap (uncurry alignCell) (zip widths row)
+    alignCell width cell =
+        let diff = width - length cell
+            in cell ++ (take diff $ repeat fill) ++ delim
+
+
+align :: HAlignment -> Int -> a -> [a] -> [a]
+align a w f l =
+    let space = w - length l
+        in case a of
+             AlignLeft -> l ++ (fill space)
+             AlignRight -> (fill space) ++ l
+             AlignCenter ->
+                 let left = space `div` 2
+                     right = left + (space `mod` 2)
+                     in fill left ++ l ++ fill right
+    where fill n = take n (repeat f)
+
+deleteAt :: Int -> [a] -> [a]
+deleteAt n l = if n >= 0 && n < length l
+                  then let (a,b) = splitAt n l in a ++ (tail b)
+                  else error ("deleteAt: illegal index: " ++ show n)
diff --git a/cbits/HSCurses.h b/cbits/HSCurses.h
--- a/cbits/HSCurses.h
+++ b/cbits/HSCurses.h
@@ -7,7 +7,7 @@
 #undef PACKAGE_STRING
 #undef PACKAGE_TARNAME
 #undef PACKAGE_VERSION
-# include "config.h"
+# include "ghcconfig.h"
 #endif
 
 #if HAVE_NCURSESW_NCURSES_H
diff --git a/cbits/HSCursesUtils.c b/cbits/HSCursesUtils.c
--- a/cbits/HSCursesUtils.c
+++ b/cbits/HSCursesUtils.c
@@ -3,7 +3,7 @@
 
 /*
  * A non-macro version of getyx(3), to make writing a Haskell binding
- * easier.  Called in HSCurses/Curses.hsc
+ * easier.  Called in UI/HSCurses/Curses.hsc
  */
 void hscurses_nomacro_getyx(WINDOW *win, int *y, int *x)
 {
diff --git a/configure b/configure
deleted file mode 100644
--- a/configure
+++ /dev/null
@@ -1,5006 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.59.
-#
-# Copyright (C) 2003 Free Software Foundation, Inc.
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
-
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
-fi
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
-fi
-
-
-# Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
-  else
-    $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-
-# Name of the executable.
-as_me=`$as_basename "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)$' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\/\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-
-
-# PATH needs CR, and LINENO needs CR and PATH.
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
-
-
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-	 case $as_dir in
-	 /*)
-	   if ("$as_dir/$as_base" -c '
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-	     CONFIG_SHELL=$as_dir/$as_base
-	     export CONFIG_SHELL
-	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-	   fi;;
-	 esac
-       done
-done
-;;
-  esac
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
-    sed '
-      N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
-      t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
-    ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
-   { (exit 1); exit 1; }; }
-
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
-  # Exit status is that of the last command.
-  exit
-}
-
-
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='	' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
-esac
-
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
-    as_ln_s='cp -p'
-  else
-    as_ln_s='ln -s'
-  fi
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
-else
-  as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.file
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-as_executable_p="test -f"
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS=" 	$as_nl"
-
-# CDPATH.
-$as_unset CDPATH
-
-
-# Name of the host.
-# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-exec 6>&1
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_config_libobj_dir=.
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-
-# Maximum number of lines to put in a shell here document.
-# This variable seems obsolete.  It should probably be removed, and
-# only ac_max_sed_lines should be used.
-: ${ac_max_here_lines=38}
-
-# Identity of this package.
-PACKAGE_NAME=
-PACKAGE_TARNAME=
-PACKAGE_VERSION=
-PACKAGE_STRING=
-PACKAGE_BUGREPORT=
-
-ac_unique_file="HSCurses/Curses.hsc"
-# Factoring default headers for most tests.
-ac_includes_default="\
-#include <stdio.h>
-#if HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#if HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#if STDC_HEADERS
-# include <stdlib.h>
-# include <stddef.h>
-#else
-# if HAVE_STDLIB_H
-#  include <stdlib.h>
-# endif
-#endif
-#if HAVE_STRING_H
-# if !STDC_HEADERS && HAVE_MEMORY_H
-#  include <memory.h>
-# endif
-# include <string.h>
-#endif
-#if HAVE_STRINGS_H
-# include <strings.h>
-#endif
-#if HAVE_INTTYPES_H
-# include <inttypes.h>
-#else
-# if HAVE_STDINT_H
-#  include <stdint.h>
-# endif
-#endif
-#if HAVE_UNISTD_H
-# include <unistd.h>
-#endif"
-
-ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS GHC WithGhc GhcCodegen GhcPkgCmd Hsc2hsCmd GccCmd HaddockCmd STRIP LdCmd LdXFlag RANLIB ac_ct_RANLIB CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT ICONV CURSES CPP EGREP SYMS current_directory LIBOBJS LTLIBOBJS'
-ac_subst_files=''
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-ac_prev=
-for ac_option
-do
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
-    ac_prev=
-    continue
-  fi
-
-  ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'`
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case $ac_option in
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir=$ac_optarg ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build_alias ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build_alias=$ac_optarg ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file=$ac_optarg ;;
-
-  --config-cache | -C)
-    cache_file=config.cache ;;
-
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir=$ac_optarg ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    eval "enable_$ac_feature=no" ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_$ac_feature='$ac_optarg'" ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix=$ac_optarg ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he | -h)
-    ac_init_help=long ;;
-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
-    ac_init_help=recursive ;;
-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
-    ac_init_help=short ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host_alias ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host_alias=$ac_optarg ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir=$ac_optarg ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir=$ac_optarg ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir=$ac_optarg ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir=$ac_optarg ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir=$ac_optarg ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir=$ac_optarg ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c | -n)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir=$ac_optarg ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix=$ac_optarg ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix=$ac_optarg ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix=$ac_optarg ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name=$ac_optarg ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir=$ac_optarg ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir=$ac_optarg ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site=$ac_optarg ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir=$ac_optarg ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir=$ac_optarg ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target_alias ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target_alias=$ac_optarg ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers | -V)
-    ac_init_version=: ;;
-
-  -with-* | --with-*)
-    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_$ac_package='$ac_optarg'" ;;
-
-  -without-* | --without-*)
-    ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/-/_/g'`
-    eval "with_$ac_package=no" ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes=$ac_optarg ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries=$ac_optarg ;;
-
-  -*) { echo "$as_me: error: unrecognized option: $ac_option
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; }
-    ;;
-
-  *=*)
-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
-   { (exit 1); exit 1; }; }
-    ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`
-    eval "$ac_envvar='$ac_optarg'"
-    export $ac_envvar ;;
-
-  *)
-    # FIXME: should be removed in autoconf 3.0.
-    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  { echo "$as_me: error: missing argument to $ac_option" >&2
-   { (exit 1); exit 1; }; }
-fi
-
-# Be sure to have absolute paths.
-for ac_var in exec_prefix prefix
-do
-  eval ac_val=$`echo $ac_var`
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* | NONE | '' ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
-  esac
-done
-
-# Be sure to have absolute paths.
-for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \
-	      localstatedir libdir includedir oldincludedir infodir mandir
-do
-  eval ac_val=$`echo $ac_var`
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
-  esac
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
-  if test "x$build_alias" = x; then
-    cross_compiling=maybe
-    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
-    If a cross compiler is detected then cross compile mode will be used." >&2
-  elif test "x$build_alias" != "x$host_alias"; then
-    cross_compiling=yes
-  fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_confdir=`(dirname "$0") 2>/dev/null ||
-$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$0" : 'X\(//\)[^/]' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$0" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-  srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2
-   { (exit 1); exit 1; }; }
-  else
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
-   { (exit 1); exit 1; }; }
-  fi
-fi
-(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null ||
-  { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2
-   { (exit 1); exit 1; }; }
-srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'`
-ac_env_build_alias_set=${build_alias+set}
-ac_env_build_alias_value=$build_alias
-ac_cv_env_build_alias_set=${build_alias+set}
-ac_cv_env_build_alias_value=$build_alias
-ac_env_host_alias_set=${host_alias+set}
-ac_env_host_alias_value=$host_alias
-ac_cv_env_host_alias_set=${host_alias+set}
-ac_cv_env_host_alias_value=$host_alias
-ac_env_target_alias_set=${target_alias+set}
-ac_env_target_alias_value=$target_alias
-ac_cv_env_target_alias_set=${target_alias+set}
-ac_cv_env_target_alias_value=$target_alias
-ac_env_CC_set=${CC+set}
-ac_env_CC_value=$CC
-ac_cv_env_CC_set=${CC+set}
-ac_cv_env_CC_value=$CC
-ac_env_CFLAGS_set=${CFLAGS+set}
-ac_env_CFLAGS_value=$CFLAGS
-ac_cv_env_CFLAGS_set=${CFLAGS+set}
-ac_cv_env_CFLAGS_value=$CFLAGS
-ac_env_LDFLAGS_set=${LDFLAGS+set}
-ac_env_LDFLAGS_value=$LDFLAGS
-ac_cv_env_LDFLAGS_set=${LDFLAGS+set}
-ac_cv_env_LDFLAGS_value=$LDFLAGS
-ac_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_env_CPPFLAGS_value=$CPPFLAGS
-ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_cv_env_CPPFLAGS_value=$CPPFLAGS
-ac_env_CPP_set=${CPP+set}
-ac_env_CPP_value=$CPP
-ac_cv_env_CPP_set=${CPP+set}
-ac_cv_env_CPP_value=$CPP
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
-  # Omit some internal or obsolete options to make the list less imposing.
-  # This message is too long to be a string in the A/UX 3.1 sh.
-  cat <<_ACEOF
-\`configure' configures this package to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE.  See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
-  -h, --help              display this help and exit
-      --help=short        display options specific to this package
-      --help=recursive    display the short help of all the included packages
-  -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking...' messages
-      --cache-file=FILE   cache test results in FILE [disabled]
-  -C, --config-cache      alias for \`--cache-file=config.cache'
-  -n, --no-create         do not create output files
-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
-
-_ACEOF
-
-  cat <<_ACEOF
-Installation directories:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-			  [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-			  [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
-  --bindir=DIR           user executables [EPREFIX/bin]
-  --sbindir=DIR          system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR       program executables [EPREFIX/libexec]
-  --datadir=DIR          read-only architecture-independent data [PREFIX/share]
-  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
-  --libdir=DIR           object code libraries [EPREFIX/lib]
-  --includedir=DIR       C header files [PREFIX/include]
-  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
-  --infodir=DIR          info documentation [PREFIX/info]
-  --mandir=DIR           man documentation [PREFIX/man]
-_ACEOF
-
-  cat <<\_ACEOF
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-
-  cat <<\_ACEOF
-
-Optional Packages:
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --with-hc=ARG           Use ARG as the path to a Haskell compiler
-                          [default=autodetect]
-
-Some influential environment variables:
-  CC          C compiler command
-  CFLAGS      C compiler flags
-  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
-              nonstandard directory <lib dir>
-  CPPFLAGS    C/C++ preprocessor flags, e.g. -I<include dir> if you have
-              headers in a nonstandard directory <include dir>
-  CPP         C preprocessor
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-_ACEOF
-fi
-
-if test "$ac_init_help" = "recursive"; then
-  # If there are subdirs, report their specific --help.
-  ac_popdir=`pwd`
-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d $ac_dir || continue
-    ac_builddir=.
-
-if test "$ac_dir" != .; then
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
-
-case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
-    ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
-
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
-
-    cd $ac_dir
-    # Check for guested configure; otherwise get Cygnus style configure.
-    if test -f $ac_srcdir/configure.gnu; then
-      echo
-      $SHELL $ac_srcdir/configure.gnu  --help=recursive
-    elif test -f $ac_srcdir/configure; then
-      echo
-      $SHELL $ac_srcdir/configure  --help=recursive
-    elif test -f $ac_srcdir/configure.ac ||
-	   test -f $ac_srcdir/configure.in; then
-      echo
-      $ac_configure --help
-    else
-      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi
-    cd "$ac_popdir"
-  done
-fi
-
-test -n "$ac_init_help" && exit 0
-if $ac_init_version; then
-  cat <<\_ACEOF
-
-Copyright (C) 2003 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
-  exit 0
-fi
-exec 5>config.log
-cat >&5 <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by $as_me, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
-
-  $ $0 $@
-
-_ACEOF
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
-
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-hostinfo               = `(hostinfo) 2>/dev/null               || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  echo "PATH: $as_dir"
-done
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_sep=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
-  for ac_arg
-  do
-    case $ac_arg in
-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-    | -silent | --silent | --silen | --sile | --sil)
-      continue ;;
-    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
-      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    case $ac_pass in
-    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
-    2)
-      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
-      if test $ac_must_keep_next = true; then
-	ac_must_keep_next=false # Got value, back to normal.
-      else
-	case $ac_arg in
-	  *=* | --config-cache | -C | -disable-* | --disable-* \
-	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
-	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
-	  | -with-* | --with-* | -without-* | --without-* | --x)
-	    case "$ac_configure_args0 " in
-	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
-	    esac
-	    ;;
-	  -* ) ac_must_keep_next=true ;;
-	esac
-      fi
-      ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'"
-      # Get rid of the leading space.
-      ac_sep=" "
-      ;;
-    esac
-  done
-done
-$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
-$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log.  We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Be sure not to use single quotes in there, as some shells,
-# such as our DU 5.0 friend, will then `close' the trap.
-trap 'exit_status=$?
-  # Save into config.log some information that might help in debugging.
-  {
-    echo
-
-    cat <<\_ASBOX
-## ---------------- ##
-## Cache variables. ##
-## ---------------- ##
-_ASBOX
-    echo
-    # The following way of writing the cache mishandles newlines in values,
-{
-  (set) 2>&1 |
-    case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
-      sed -n \
-	"s/'"'"'/'"'"'\\\\'"'"''"'"'/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p"
-      ;;
-    *)
-      sed -n \
-	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
-      ;;
-    esac;
-}
-    echo
-
-    cat <<\_ASBOX
-## ----------------- ##
-## Output variables. ##
-## ----------------- ##
-_ASBOX
-    echo
-    for ac_var in $ac_subst_vars
-    do
-      eval ac_val=$`echo $ac_var`
-      echo "$ac_var='"'"'$ac_val'"'"'"
-    done | sort
-    echo
-
-    if test -n "$ac_subst_files"; then
-      cat <<\_ASBOX
-## ------------- ##
-## Output files. ##
-## ------------- ##
-_ASBOX
-      echo
-      for ac_var in $ac_subst_files
-      do
-	eval ac_val=$`echo $ac_var`
-	echo "$ac_var='"'"'$ac_val'"'"'"
-      done | sort
-      echo
-    fi
-
-    if test -s confdefs.h; then
-      cat <<\_ASBOX
-## ----------- ##
-## confdefs.h. ##
-## ----------- ##
-_ASBOX
-      echo
-      sed "/^$/d" confdefs.h | sort
-      echo
-    fi
-    test "$ac_signal" != 0 &&
-      echo "$as_me: caught signal $ac_signal"
-    echo "$as_me: exit $exit_status"
-  } >&5
-  rm -f core *.core &&
-  rm -rf conftest* confdefs* conf$$* $ac_clean_files &&
-    exit $exit_status
-     ' 0
-for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo >confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
-fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
-echo "$as_me: loading site script $ac_site_file" >&6;}
-    sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special
-  # files actually), so we avoid doing that.
-  if test -f "$cache_file"; then
-    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
-echo "$as_me: loading cache $cache_file" >&6;}
-    case $cache_file in
-      [\\/]* | ?:[\\/]* ) . $cache_file;;
-      *)                      . ./$cache_file;;
-    esac
-  fi
-else
-  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
-echo "$as_me: creating cache $cache_file" >&6;}
-  >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in `(set) 2>&1 |
-	       sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do
-  eval ac_old_set=\$ac_cv_env_${ac_var}_set
-  eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val="\$ac_cv_env_${ac_var}_value"
-  eval ac_new_val="\$ac_env_${ac_var}_value"
-  case $ac_old_set,$ac_new_set in
-    set,)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,set)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,);;
-    *)
-      if test "x$ac_old_val" != "x$ac_new_val"; then
-	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
-echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
-echo "$as_me:   former value:  $ac_old_val" >&2;}
-	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
-echo "$as_me:   current value: $ac_new_val" >&2;}
-	ac_cache_corrupted=:
-      fi;;
-  esac
-  # Pass precious variables to config.status.
-  if test "$ac_new_set" = set; then
-    case $ac_new_val in
-    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
-      ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
-    *) ac_arg=$ac_var=$ac_new_val ;;
-    esac
-    case " $ac_configure_args " in
-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-    esac
-  fi
-done
-if $ac_cache_corrupted; then
-  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
-echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
-echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-# Prepare to generate the config.h.in file
-          ac_config_headers="$ac_config_headers cbits/config.h"
-
-
-# this is arbitrary
-
-
-#
-# Looking for HC, stolen from $fptools
-#
-
-# Check whether --with-hc or --without-hc was given.
-if test "${with_hc+set}" = set; then
-  withval="$with_hc"
-   WithGhc="$withval"
-  if test "$WithGhc" = "nhc98"; then
-
-cat >>confdefs.h <<\_ACEOF
-#define __NHC__
-_ACEOF
-
-    SYMS="$SYMS -D__NHC__"
-  fi
-
-else
-
-  if test "$GHC" = ""; then
-    for ac_prog in ghc
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_GHC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$GHC"; then
-  ac_cv_prog_GHC="$GHC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_GHC="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-GHC=$ac_cv_prog_GHC
-if test -n "$GHC"; then
-  echo "$as_me:$LINENO: result: $GHC" >&5
-echo "${ECHO_T}$GHC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  test -n "$GHC" && break
-done
-
-  fi
-  if test "$GHC" = ""; then
-    for ac_prog in nhc98
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_GHC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$GHC"; then
-  ac_cv_prog_GHC="$GHC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_GHC="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-GHC=$ac_cv_prog_GHC
-if test -n "$GHC"; then
-  echo "$as_me:$LINENO: result: $GHC" >&5
-echo "${ECHO_T}$GHC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  test -n "$GHC" && break
-done
-
-  fi
-  if test "$GHC" = "nhc98"; then
-
-cat >>confdefs.h <<\_ACEOF
-#define __NHC__
-_ACEOF
-
-    SYMS="$SYMS -D__NHC__"
-  fi
-  WithGhc=`which $GHC`
-
-fi;
-
-
-# code generation option for GHC (normally, we want to use `-fvia-C', however,
-# with ghc-6.4 -fvia-C produces a buggy binary, dying with:
-#       user error (Curses[-1]:keypad))
-if test `$WithGhc --numeric-version 2> /dev/null` = "6.4"; then
-  GhcCodegen="-fasm"
-else
-  GhcCodegen="-fvia-C"
-fi
-
-
-#
-# Look for a ghc-pkg that matches our ghc version.
-#
-ghc_pkg_guess=`dirname $WithGhc`/ghc-pkg-`$WithGhc --numeric-version`
-if "$ghc_pkg_guess" -l > /dev/null 2>&1; then
-      matching_ghc_pkg=$ghc_pkg_guess
-else
-      matching_ghc_pkg=no
-fi
-if test x"$matching_ghc_pkg" = xno; then
-    # Extract the first word of "ghc-pkg", so it can be a program name with args.
-set dummy ghc-pkg; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_GhcPkgCmd+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$GhcPkgCmd"; then
-  ac_cv_prog_GhcPkgCmd="$GhcPkgCmd" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_GhcPkgCmd="ghc-pkg"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-GhcPkgCmd=$ac_cv_prog_GhcPkgCmd
-if test -n "$GhcPkgCmd"; then
-  echo "$as_me:$LINENO: result: $GhcPkgCmd" >&5
-echo "${ECHO_T}$GhcPkgCmd" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-else
-    GhcPkgCmd=$matching_ghc_pkg
-fi
-
-
-# check if ghc-pkg has version >= or < 6.4
-ghcPkgVersion=`$GhcPkgCmd --version | sed 's/GHC package manager version //'`
-echo -e "$ghcPkgVersion\n6.3" | sort -c > /dev/null 2>&1
-sorted=$?
-if test $sorted -eq 0; then
-  cp ./hscurses.conf.m4.in.before64 ./hscurses.conf.m4.in
-else
-  cp ./hscurses.conf.m4.in.64 ./hscurses.conf.m4.in
-fi
-
-#
-# Look for a hsc2hs that matches our ghc version.
-#
-hsc2hs_guess=`dirname $WithGhc`/hsc2hs
-if "$hsc2hs_guess" -V > /dev/null 2>&1; then
-  Hsc2hsCmd=$hsc2hs_guess
-else
-  # Extract the first word of "hsc2hs", so it can be a program name with args.
-set dummy hsc2hs; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_Hsc2hsCmd+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$Hsc2hsCmd"; then
-  ac_cv_prog_Hsc2hsCmd="$Hsc2hsCmd" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_Hsc2hsCmd="hsc2hs"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-Hsc2hsCmd=$ac_cv_prog_Hsc2hsCmd
-if test -n "$Hsc2hsCmd"; then
-  echo "$as_me:$LINENO: result: $Hsc2hsCmd" >&5
-echo "${ECHO_T}$Hsc2hsCmd" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-
-
-
-#
-# And some other tools
-#
-# AC_CHECK_PROG(AlexCmd,alex,alex)
-# AC_CHECK_PROG(HappyCmd,happy,happy)
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_GccCmd+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$GccCmd"; then
-  ac_cv_prog_GccCmd="$GccCmd" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_GccCmd="gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-GccCmd=$ac_cv_prog_GccCmd
-if test -n "$GccCmd"; then
-  echo "$as_me:$LINENO: result: $GccCmd" >&5
-echo "${ECHO_T}$GccCmd" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-# Extract the first word of "haddock", so it can be a program name with args.
-set dummy haddock; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_HaddockCmd+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$HaddockCmd"; then
-  ac_cv_prog_HaddockCmd="$HaddockCmd" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_HaddockCmd="haddock"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-HaddockCmd=$ac_cv_prog_HaddockCmd
-if test -n "$HaddockCmd"; then
-  echo "$as_me:$LINENO: result: $HaddockCmd" >&5
-echo "${ECHO_T}$HaddockCmd" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-
-# Extract the first word of "strip", so it can be a program name with args.
-set dummy strip; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_STRIP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_STRIP="strip"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-STRIP=$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  echo "$as_me:$LINENO: result: $STRIP" >&5
-echo "${ECHO_T}$STRIP" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-# Extract the first word of "ld", so it can be a program name with args.
-set dummy ld; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_LdCmd+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $LdCmd in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_LdCmd="$LdCmd" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_LdCmd="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-  ;;
-esac
-fi
-LdCmd=$ac_cv_path_LdCmd
-
-if test -n "$LdCmd"; then
-  echo "$as_me:$LINENO: result: $LdCmd" >&5
-echo "${ECHO_T}$LdCmd" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-
-# check for -x flag to ld. stolen from $fptools
-
-
-echo "$as_me:$LINENO: checking whether ld understands -x" >&5
-echo $ECHO_N "checking whether ld understands -x... $ECHO_C" >&6
-if test "${fptools_cv_ld_x+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-echo 'foo() {}' > conftest.c
-${CC-cc} -c conftest.c
-if ${LdCmd} -r -x -o foo.o conftest.o; then
-   fptools_cv_ld_x=yes
-else
-   fptools_cv_ld_x=no
-fi
-rm -rf conftest.c conftest.o foo.o
-
-fi
-echo "$as_me:$LINENO: result: $fptools_cv_ld_x" >&5
-echo "${ECHO_T}$fptools_cv_ld_x" >&6
-if test "$fptools_cv_ld_x" = yes; then
-    LdXFlag=-x
-else
-    LdXFlag=
-fi
-
-
-
-#
-# May as well check for this
-#
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_RANLIB+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  echo "$as_me:$LINENO: result: $RANLIB" >&5
-echo "${ECHO_T}$RANLIB" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-  test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":"
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
-echo "${ECHO_T}$ac_ct_RANLIB" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  RANLIB=$ac_ct_RANLIB
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-
-#
-# Curses. If you don't have wchar_t-aware ncurses (Debian package:
-# libncursesw5-dev),  uncomment the first line and comment-out the
-# two later.
-#
-# The shell variables should be added to, e.g., $LIBS
-#
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  CC=$ac_ct_CC
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  CC=$ac_ct_CC
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-fi
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
-       ac_prog_rejected=yes
-       continue
-     fi
-    ac_cv_prog_CC="cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# != 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
-  fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-    test -n "$CC" && break
-  done
-fi
-if test -z "$CC"; then
-  ac_ct_CC=$CC
-  for ac_prog in cl
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  test -n "$ac_ct_CC" && break
-done
-
-  CC=$ac_ct_CC
-fi
-
-fi
-
-
-test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
-See \`config.log' for more details." >&5
-echo "$as_me: error: no acceptable C compiler found in \$PATH
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-
-# Provide some information about the compiler.
-echo "$as_me:$LINENO:" \
-     "checking for C compiler version" >&5
-ac_compiler=`set X $ac_compile; echo $2`
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
-  (eval $ac_compiler --version </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
-  (eval $ac_compiler -v </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
-  (eval $ac_compiler -V </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
-echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6
-ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5
-  (eval $ac_link_default) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-  # Find the output, starting from the most likely.  This scheme is
-# not robust to junk in `.', hence go to wildcards (a.*) only as a last
-# resort.
-
-# Be careful to initialize this variable, since it used to be cached.
-# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile.
-ac_cv_exeext=
-# b.out is created by i960 compilers.
-for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out
-do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj )
-	;;
-    conftest.$ac_ext )
-	# This is the source file.
-	;;
-    [ab].out )
-	# We found the default executable, but exeext='' is most
-	# certainly right.
-	break;;
-    *.* )
-	ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	# FIXME: I believe we export ac_cv_exeext for Libtool,
-	# but it would be cool to find out if it's true.  Does anybody
-	# maintain Libtool? --akim.
-	export ac_cv_exeext
-	break;;
-    * )
-	break;;
-  esac
-done
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
-See \`config.log' for more details." >&5
-echo "$as_me: error: C compiler cannot create executables
-See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-fi
-
-ac_exeext=$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_file" >&5
-echo "${ECHO_T}$ac_file" >&6
-
-# Check the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether the C compiler works" >&5
-echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6
-# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
-# If not cross compiling, check that we can run a simple program.
-if test "$cross_compiling" != yes; then
-  if { ac_try='./$ac_file'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-    cross_compiling=no
-  else
-    if test "$cross_compiling" = maybe; then
-	cross_compiling=yes
-    else
-	{ { echo "$as_me:$LINENO: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-  fi
-fi
-echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-
-rm -f a.out a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-# Check the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
-echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6
-echo "$as_me:$LINENO: result: $cross_compiling" >&5
-echo "${ECHO_T}$cross_compiling" >&6
-
-echo "$as_me:$LINENO: checking for suffix of executables" >&5
-echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-  # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;;
-    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	  export ac_cv_exeext
-	  break;;
-    * ) break;;
-  esac
-done
-else
-  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-rm -f conftest$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
-echo "${ECHO_T}$ac_cv_exeext" >&6
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-echo "$as_me:$LINENO: checking for suffix of object files" >&5
-echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6
-if test "${ac_cv_objext+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-  for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;;
-    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
-       break;;
-  esac
-done
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of object files: cannot compile
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
-echo "${ECHO_T}$ac_cv_objext" >&6
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6
-if test "${ac_cv_c_compiler_gnu+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_compiler_gnu=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_compiler_gnu=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6
-GCC=`test $ac_compiler_gnu = yes && echo yes`
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-CFLAGS="-g"
-echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
-echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6
-if test "${ac_cv_prog_cc_g+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_cc_g=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_prog_cc_g=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_g" >&6
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5
-echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6
-if test "${ac_cv_prog_cc_stdc+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_cv_prog_cc_stdc=no
-ac_save_CC=$CC
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
-     char **p;
-     int i;
-{
-  return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
-  char *s;
-  va_list v;
-  va_start (v,p);
-  s = g (p, va_arg (v,int));
-  va_end (v);
-  return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
-   function prototypes and stuff, but not '\xHH' hex character constants.
-   These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std1 is added to get
-   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
-   array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std1.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
-  ;
-  return 0;
-}
-_ACEOF
-# Don't try gcc -ansi; that turns off useful extensions and
-# breaks some systems' header files.
-# AIX			-qlanglvl=ansi
-# Ultrix and OSF/1	-std1
-# HP-UX 10.20 and later	-Ae
-# HP-UX older versions	-Aa -D_HPUX_SOURCE
-# SVR4			-Xc -D__EXTENSIONS__
-for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
-  CC="$ac_save_CC $ac_arg"
-  rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_cc_stdc=$ac_arg
-break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-fi
-rm -f conftest.err conftest.$ac_objext
-done
-rm -f conftest.$ac_ext conftest.$ac_objext
-CC=$ac_save_CC
-
-fi
-
-case "x$ac_cv_prog_cc_stdc" in
-  x|xno)
-    echo "$as_me:$LINENO: result: none needed" >&5
-echo "${ECHO_T}none needed" >&6 ;;
-  *)
-    echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6
-    CC="$CC $ac_cv_prog_cc_stdc" ;;
-esac
-
-# Some people use a C++ compiler to compile C.  Since we use `exit',
-# in C++ we need to declare it.  In case someone uses the same compiler
-# for both compiling C and C++ we need to have the C++ compiler decide
-# the declaration of exit, since it's the most demanding environment.
-cat >conftest.$ac_ext <<_ACEOF
-#ifndef __cplusplus
-  choke me
-#endif
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  for ac_declaration in \
-   '' \
-   'extern "C" void std::exit (int) throw (); using std::exit;' \
-   'extern "C" void std::exit (int); using std::exit;' \
-   'extern "C" void exit (int) throw ();' \
-   'extern "C" void exit (int);' \
-   'void exit (int);'
-do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-#include <stdlib.h>
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-continue
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-rm -f conftest*
-if test -n "$ac_declaration"; then
-  echo '#ifdef __cplusplus' >>confdefs.h
-  echo $ac_declaration      >>confdefs.h
-  echo '#endif'             >>confdefs.h
-fi
-
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-echo "$as_me:$LINENO: checking for addnstr in -lcurses" >&5
-echo $ECHO_N "checking for addnstr in -lcurses... $ECHO_C" >&6
-if test "${ac_cv_lib_curses_addnstr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lcurses  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char addnstr ();
-int
-main ()
-{
-addnstr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_curses_addnstr=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_curses_addnstr=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_curses_addnstr" >&5
-echo "${ECHO_T}$ac_cv_lib_curses_addnstr" >&6
-if test $ac_cv_lib_curses_addnstr = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBCURSES 1
-_ACEOF
-
-  LIBS="-lcurses $LIBS"
-
-fi
-
-
-echo "$as_me:$LINENO: checking for addnstr in -lncurses" >&5
-echo $ECHO_N "checking for addnstr in -lncurses... $ECHO_C" >&6
-if test "${ac_cv_lib_ncurses_addnstr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lncurses  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char addnstr ();
-int
-main ()
-{
-addnstr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_ncurses_addnstr=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_ncurses_addnstr=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_ncurses_addnstr" >&5
-echo "${ECHO_T}$ac_cv_lib_ncurses_addnstr" >&6
-if test $ac_cv_lib_ncurses_addnstr = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBNCURSES 1
-_ACEOF
-
-  LIBS="-lncurses $LIBS"
-
-fi
-
-
-echo "$as_me:$LINENO: checking for waddnwstr in -lncursesw" >&5
-echo $ECHO_N "checking for waddnwstr in -lncursesw... $ECHO_C" >&6
-if test "${ac_cv_lib_ncursesw_waddnwstr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lncursesw  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char waddnwstr ();
-int
-main ()
-{
-waddnwstr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_ncursesw_waddnwstr=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_ncursesw_waddnwstr=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_ncursesw_waddnwstr" >&5
-echo "${ECHO_T}$ac_cv_lib_ncursesw_waddnwstr" >&6
-if test $ac_cv_lib_ncursesw_waddnwstr = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBNCURSESW 1
-_ACEOF
-
-  LIBS="-lncursesw $LIBS"
-
-fi
-
-
-
-echo "$as_me:$LINENO: checking for iconv in -liconv" >&5
-echo $ECHO_N "checking for iconv in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_iconv+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char iconv ();
-int
-main ()
-{
-iconv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_iconv=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_iconv_iconv=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_iconv" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_iconv" >&6
-if test $ac_cv_lib_iconv_iconv = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBICONV 1
-_ACEOF
-
-  LIBS="-liconv $LIBS"
-
-fi
-
-
-echo "$as_me:$LINENO: checking for libiconv in -liconv" >&5
-echo $ECHO_N "checking for libiconv in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_libiconv+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char libiconv ();
-int
-main ()
-{
-libiconv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_libiconv=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_iconv_libiconv=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_libiconv" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_libiconv" >&6
-if test $ac_cv_lib_iconv_libiconv = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBICONV 1
-_ACEOF
-
-  LIBS="-liconv $LIBS"
-
-fi
-
-
-# Bit weird. On OpenBSD you need the 'lib' suffix to iconv functions, it seems
-
-for ac_func in libiconv
-do
-as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6
-if eval "test \"\${$as_ac_var+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-char (*f) () = $ac_func;
-#endif
-#ifdef __cplusplus
-}
-#endif
-
-int
-main ()
-{
-return f != $ac_func;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_var=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_var=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6
-if test `eval echo '${'$as_ac_var'}'` = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-cat >>confdefs.h <<\_ACEOF
-#define ICONV_LIB_PREFIX 1
-_ACEOF
-
-fi
-done
-
-
-# On linux we need to call doupdate() after endwin() to restore the term
-if uname -s | grep Linux > /dev/null 2>&1 ; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NCURSES_UPDATE_AFTER_END 1
-_ACEOF
-
-fi
-
-# some special libs need to be set for package.conf files
-if echo "$LIBS" | grep iconv > /dev/null 2>&1 ; then
-    ICONV=iconv
-fi
-
-if (echo "$LIBS" | grep ncursesw) >/dev/null 2>&1 ; then
-    CURSES=ncursesw
-elif (echo "$LIBS" | grep ncurses) >/dev/null 2>&1 ; then
-    CURSES=ncurses
-else
-    CURSES=curses
-fi
-
-
-
-#
-# Specific headers to check for
-#
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
-echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if test "${ac_cv_prog_CPP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether non-existent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  break
-fi
-
-    done
-    ac_cv_prog_CPP=$CPP
-
-fi
-  CPP=$ac_cv_prog_CPP
-else
-  ac_cv_prog_CPP=$CPP
-fi
-echo "$as_me:$LINENO: result: $CPP" >&5
-echo "${ECHO_T}$CPP" >&6
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether non-existent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details." >&5
-echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-echo "$as_me:$LINENO: checking for egrep" >&5
-echo $ECHO_N "checking for egrep... $ECHO_C" >&6
-if test "${ac_cv_prog_egrep+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if echo a | (grep -E '(a|b)') >/dev/null 2>&1
-    then ac_cv_prog_egrep='grep -E'
-    else ac_cv_prog_egrep='egrep'
-    fi
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5
-echo "${ECHO_T}$ac_cv_prog_egrep" >&6
- EGREP=$ac_cv_prog_egrep
-
-
-echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
-if test "${ac_cv_header_stdc+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_header_stdc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_header_stdc=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then
-  :
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then
-  :
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then
-  :
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ctype.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-		   (('a' <= (c) && (c) <= 'i') \
-		     || ('j' <= (c) && (c) <= 'r') \
-		     || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-	|| toupper (i) != TOUPPER (i))
-      exit(2);
-  exit (0);
-}
-_ACEOF
-rm -f conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_header_stdc=no
-fi
-rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
-fi
-fi
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6
-if test $ac_cv_header_stdc = yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define STDC_HEADERS 1
-_ACEOF
-
-fi
-
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
-
-
-
-
-
-
-
-
-
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
-		  inttypes.h stdint.h unistd.h
-do
-as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Header=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_Header=no"
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-
-
-
-
-
-
-for ac_header in iconv.h curses.h ncurses.h ncursesw/ncurses.h locale.h langinfo.h wchar.h limits.h signal.h
-do
-as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
-
-# Is the header present?
-echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=\$ac_header_preproc"
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-current_directory=`pwd`
-
-
-                              ac_config_files="$ac_config_files mk/config.mk hscurses.conf.m4 hscurses.buildinfo"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-{
-  (set) 2>&1 |
-    case `(ac_space=' '; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
-      # `set' does not quote correctly, so add quotes (double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \).
-      sed -n \
-	"s/'/'\\\\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;;
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n \
-	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
-      ;;
-    esac;
-} |
-  sed '
-     t clear
-     : clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     : end' >>confcache
-if diff $cache_file confcache >/dev/null 2>&1; then :; else
-  if test -w $cache_file; then
-    test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file"
-    cat confcache >$cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# VPATH may cause trouble with some makes, so we remove $(srcdir),
-# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
-s/:*\$(srcdir):*/:/;
-s/:*\${srcdir}:*/:/;
-s/:*@srcdir@:*/:/;
-s/^\([^=]*=[	 ]*\):*/\1/;
-s/:*$//;
-s/^[^=]*=[	 ]*$//;
-}'
-fi
-
-DEFS=-DHAVE_CONFIG_H
-
-ac_libobjs=
-ac_ltlibobjs=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_i=`echo "$ac_i" |
-	 sed 's/\$U\././;s/\.o$//;s/\.obj$//'`
-  # 2. Add them.
-  ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext"
-  ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-: ${CONFIG_STATUS=./config.status}
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
-echo "$as_me: creating $CONFIG_STATUS" >&6;}
-cat >$CONFIG_STATUS <<_ACEOF
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-SHELL=\${CONFIG_SHELL-$SHELL}
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
-
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
-fi
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
-fi
-
-
-# Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
-  else
-    $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-
-# Name of the executable.
-as_me=`$as_basename "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)$' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\/\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-
-
-# PATH needs CR, and LINENO needs CR and PATH.
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
-
-
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
-echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-	 case $as_dir in
-	 /*)
-	   if ("$as_dir/$as_base" -c '
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-	     CONFIG_SHELL=$as_dir/$as_base
-	     export CONFIG_SHELL
-	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-	   fi;;
-	 esac
-       done
-done
-;;
-  esac
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
-    sed '
-      N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
-      t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
-    ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
-    { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5
-echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;}
-   { (exit 1); exit 1; }; }
-
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
-  # Exit status is that of the last command.
-  exit
-}
-
-
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='	' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
-esac
-
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
-    as_ln_s='cp -p'
-  else
-    as_ln_s='ln -s'
-  fi
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
-else
-  as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.file
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-as_executable_p="test -f"
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS=" 	$as_nl"
-
-# CDPATH.
-$as_unset CDPATH
-
-exec 6>&1
-
-# Open the log real soon, to keep \$[0] and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.  Logging --version etc. is OK.
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-} >&5
-cat >&5 <<_CSEOF
-
-This file was extended by $as_me, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-_CSEOF
-echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5
-echo >&5
-_ACEOF
-
-# Files that config.status was made for.
-if test -n "$ac_config_files"; then
-  echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS
-fi
-
-if test -n "$ac_config_headers"; then
-  echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS
-fi
-
-if test -n "$ac_config_links"; then
-  echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS
-fi
-
-if test -n "$ac_config_commands"; then
-  echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-ac_cs_usage="\
-\`$as_me' instantiates files from templates according to the
-current configuration.
-
-Usage: $0 [OPTIONS] [FILE]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number, then exit
-  -q, --quiet      do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-  --file=FILE[:TEMPLATE]
-		   instantiate the configuration file FILE
-  --header=FILE[:TEMPLATE]
-		   instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Report bugs to <bug-autoconf@gnu.org>."
-_ACEOF
-
-cat >>$CONFIG_STATUS <<_ACEOF
-ac_cs_version="\\
-config.status
-configured by $0, generated by GNU Autoconf 2.59,
-  with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\"
-
-Copyright (C) 2003 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-srcdir=$srcdir
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-# If no file are specified by the user, then we need to provide default
-# value.  By we need to know if files were specified by the user.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=*)
-    ac_option=`expr "x$1" : 'x\([^=]*\)='`
-    ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  -*)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  *) # This is not an option, so the user has probably given explicit
-     # arguments.
-     ac_option=$1
-     ac_need_defaults=false;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --vers* | -V )
-    echo "$ac_cs_version"; exit 0 ;;
-  --he | --h)
-    # Conflict between --help and --header
-    { { echo "$as_me:$LINENO: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&2;}
-   { (exit 1); exit 1; }; };;
-  --help | --hel | -h )
-    echo "$ac_cs_usage"; exit 0 ;;
-  --debug | --d* | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
-    ac_need_defaults=false;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2;}
-   { (exit 1); exit 1; }; } ;;
-
-  *) ac_config_targets="$ac_config_targets $1" ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-if \$ac_cs_recheck; then
-  echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
-  exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-fi
-
-_ACEOF
-
-
-
-
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-for ac_config_target in $ac_config_targets
-do
-  case "$ac_config_target" in
-  # Handling of arguments.
-  "mk/config.mk" ) CONFIG_FILES="$CONFIG_FILES mk/config.mk" ;;
-  "hscurses.conf.m4" ) CONFIG_FILES="$CONFIG_FILES hscurses.conf.m4" ;;
-  "hscurses.buildinfo" ) CONFIG_FILES="$CONFIG_FILES hscurses.buildinfo" ;;
-  "cbits/config.h" ) CONFIG_HEADERS="$CONFIG_HEADERS cbits/config.h" ;;
-  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
-echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
-   { (exit 1); exit 1; }; };;
-  esac
-done
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason to put it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Create a temporary directory, and hook for its removal unless debugging.
-$debug ||
-{
-  trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0
-  trap '{ (exit 1); exit 1; }' 1 2 13 15
-}
-
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` &&
-  test -n "$tmp" && test -d "$tmp"
-}  ||
-{
-  tmp=./confstat$$-$RANDOM
-  (umask 077 && mkdir $tmp)
-} ||
-{
-   echo "$me: cannot create a temporary directory in ." >&2
-   { (exit 1); exit 1; }
-}
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<_ACEOF
-
-#
-# CONFIG_FILES section.
-#
-
-# No need to generate the scripts if there are no CONFIG_FILES.
-# This happens for instance when ./config.status config.h
-if test -n "\$CONFIG_FILES"; then
-  # Protect against being on the right side of a sed subst in config.status.
-  sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g;
-   s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF
-s,@SHELL@,$SHELL,;t t
-s,@PATH_SEPARATOR@,$PATH_SEPARATOR,;t t
-s,@PACKAGE_NAME@,$PACKAGE_NAME,;t t
-s,@PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t
-s,@PACKAGE_VERSION@,$PACKAGE_VERSION,;t t
-s,@PACKAGE_STRING@,$PACKAGE_STRING,;t t
-s,@PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t
-s,@exec_prefix@,$exec_prefix,;t t
-s,@prefix@,$prefix,;t t
-s,@program_transform_name@,$program_transform_name,;t t
-s,@bindir@,$bindir,;t t
-s,@sbindir@,$sbindir,;t t
-s,@libexecdir@,$libexecdir,;t t
-s,@datadir@,$datadir,;t t
-s,@sysconfdir@,$sysconfdir,;t t
-s,@sharedstatedir@,$sharedstatedir,;t t
-s,@localstatedir@,$localstatedir,;t t
-s,@libdir@,$libdir,;t t
-s,@includedir@,$includedir,;t t
-s,@oldincludedir@,$oldincludedir,;t t
-s,@infodir@,$infodir,;t t
-s,@mandir@,$mandir,;t t
-s,@build_alias@,$build_alias,;t t
-s,@host_alias@,$host_alias,;t t
-s,@target_alias@,$target_alias,;t t
-s,@DEFS@,$DEFS,;t t
-s,@ECHO_C@,$ECHO_C,;t t
-s,@ECHO_N@,$ECHO_N,;t t
-s,@ECHO_T@,$ECHO_T,;t t
-s,@LIBS@,$LIBS,;t t
-s,@GHC@,$GHC,;t t
-s,@WithGhc@,$WithGhc,;t t
-s,@GhcCodegen@,$GhcCodegen,;t t
-s,@GhcPkgCmd@,$GhcPkgCmd,;t t
-s,@Hsc2hsCmd@,$Hsc2hsCmd,;t t
-s,@GccCmd@,$GccCmd,;t t
-s,@HaddockCmd@,$HaddockCmd,;t t
-s,@STRIP@,$STRIP,;t t
-s,@LdCmd@,$LdCmd,;t t
-s,@LdXFlag@,$LdXFlag,;t t
-s,@RANLIB@,$RANLIB,;t t
-s,@ac_ct_RANLIB@,$ac_ct_RANLIB,;t t
-s,@CC@,$CC,;t t
-s,@CFLAGS@,$CFLAGS,;t t
-s,@LDFLAGS@,$LDFLAGS,;t t
-s,@CPPFLAGS@,$CPPFLAGS,;t t
-s,@ac_ct_CC@,$ac_ct_CC,;t t
-s,@EXEEXT@,$EXEEXT,;t t
-s,@OBJEXT@,$OBJEXT,;t t
-s,@ICONV@,$ICONV,;t t
-s,@CURSES@,$CURSES,;t t
-s,@CPP@,$CPP,;t t
-s,@EGREP@,$EGREP,;t t
-s,@SYMS@,$SYMS,;t t
-s,@current_directory@,$current_directory,;t t
-s,@LIBOBJS@,$LIBOBJS,;t t
-s,@LTLIBOBJS@,$LTLIBOBJS,;t t
-CEOF
-
-_ACEOF
-
-  cat >>$CONFIG_STATUS <<\_ACEOF
-  # Split the substitutions into bite-sized pieces for seds with
-  # small command number limits, like on Digital OSF/1 and HP-UX.
-  ac_max_sed_lines=48
-  ac_sed_frag=1 # Number of current file.
-  ac_beg=1 # First line for current file.
-  ac_end=$ac_max_sed_lines # Line after last line for current file.
-  ac_more_lines=:
-  ac_sed_cmds=
-  while $ac_more_lines; do
-    if test $ac_beg -gt 1; then
-      sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    else
-      sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    fi
-    if test ! -s $tmp/subs.frag; then
-      ac_more_lines=false
-    else
-      # The purpose of the label and of the branching condition is to
-      # speed up the sed processing (if there are no `@' at all, there
-      # is no need to browse any of the substitutions).
-      # These are the two extra sed commands mentioned above.
-      (echo ':t
-  /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed
-      if test -z "$ac_sed_cmds"; then
-	ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed"
-      else
-	ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed"
-      fi
-      ac_sed_frag=`expr $ac_sed_frag + 1`
-      ac_beg=$ac_end
-      ac_end=`expr $ac_end + $ac_max_sed_lines`
-    fi
-  done
-  if test -z "$ac_sed_cmds"; then
-    ac_sed_cmds=cat
-  fi
-fi # test -n "$CONFIG_FILES"
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case $ac_file in
-  - | *:- | *:-:* ) # input from stdin
-	cat >$tmp/stdin
-	ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  * )   ac_file_in=$ac_file.in ;;
-  esac
-
-  # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories.
-  ac_dir=`(dirname "$ac_file") 2>/dev/null ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$ac_file" : 'X\(//\)[^/]' \| \
-	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-  { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
-    as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-    done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
-   { (exit 1); exit 1; }; }; }
-
-  ac_builddir=.
-
-if test "$ac_dir" != .; then
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
-
-case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
-    ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
-
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
-
-
-
-  # Let's still pretend it is `configure' which instantiates (i.e., don't
-  # use $as_me), people would be surprised to read:
-  #    /* config.h.  Generated by config.status.  */
-  if test x"$ac_file" = x-; then
-    configure_input=
-  else
-    configure_input="$ac_file.  "
-  fi
-  configure_input=$configure_input"Generated from `echo $ac_file_in |
-				     sed 's,.*/,,'` by configure."
-
-  # First look for the input files in the build tree, otherwise in the
-  # src tree.
-  ac_file_inputs=`IFS=:
-    for f in $ac_file_in; do
-      case $f in
-      -) echo $tmp/stdin ;;
-      [\\/$]*)
-	 # Absolute (can't be DOS-style, as IFS=:)
-	 test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 echo "$f";;
-      *) # Relative
-	 if test -f "$f"; then
-	   # Build tree
-	   echo "$f"
-	 elif test -f "$srcdir/$f"; then
-	   # Source tree
-	   echo "$srcdir/$f"
-	 else
-	   # /dev/null tree
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 fi;;
-      esac
-    done` || { (exit 1); exit 1; }
-
-  if test x"$ac_file" != x-; then
-    { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    rm -f "$ac_file"
-  fi
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-  sed "$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s,@configure_input@,$configure_input,;t t
-s,@srcdir@,$ac_srcdir,;t t
-s,@abs_srcdir@,$ac_abs_srcdir,;t t
-s,@top_srcdir@,$ac_top_srcdir,;t t
-s,@abs_top_srcdir@,$ac_abs_top_srcdir,;t t
-s,@builddir@,$ac_builddir,;t t
-s,@abs_builddir@,$ac_abs_builddir,;t t
-s,@top_builddir@,$ac_top_builddir,;t t
-s,@abs_top_builddir@,$ac_abs_top_builddir,;t t
-" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out
-  rm -f $tmp/stdin
-  if test x"$ac_file" != x-; then
-    mv $tmp/out $ac_file
-  else
-    cat $tmp/out
-    rm -f $tmp/out
-  fi
-
-done
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-#
-# CONFIG_HEADER section.
-#
-
-# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
-# NAME is the cpp macro being defined and VALUE is the value it is being given.
-#
-# ac_d sets the value in "#define NAME VALUE" lines.
-ac_dA='s,^\([	 ]*\)#\([	 ]*define[	 ][	 ]*\)'
-ac_dB='[	 ].*$,\1#\2'
-ac_dC=' '
-ac_dD=',;t'
-# ac_u turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
-ac_uA='s,^\([	 ]*\)#\([	 ]*\)undef\([	 ][	 ]*\)'
-ac_uB='$,\1#\2define\3'
-ac_uC=' '
-ac_uD=',;t'
-
-for ac_file in : $CONFIG_HEADERS; do test "x$ac_file" = x: && continue
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case $ac_file in
-  - | *:- | *:-:* ) # input from stdin
-	cat >$tmp/stdin
-	ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  * )   ac_file_in=$ac_file.in ;;
-  esac
-
-  test x"$ac_file" != x- && { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-
-  # First look for the input files in the build tree, otherwise in the
-  # src tree.
-  ac_file_inputs=`IFS=:
-    for f in $ac_file_in; do
-      case $f in
-      -) echo $tmp/stdin ;;
-      [\\/$]*)
-	 # Absolute (can't be DOS-style, as IFS=:)
-	 test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 # Do quote $f, to prevent DOS paths from being IFS'd.
-	 echo "$f";;
-      *) # Relative
-	 if test -f "$f"; then
-	   # Build tree
-	   echo "$f"
-	 elif test -f "$srcdir/$f"; then
-	   # Source tree
-	   echo "$srcdir/$f"
-	 else
-	   # /dev/null tree
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 fi;;
-      esac
-    done` || { (exit 1); exit 1; }
-  # Remove the trailing spaces.
-  sed 's/[	 ]*$//' $ac_file_inputs >$tmp/in
-
-_ACEOF
-
-# Transform confdefs.h into two sed scripts, `conftest.defines' and
-# `conftest.undefs', that substitutes the proper values into
-# config.h.in to produce config.h.  The first handles `#define'
-# templates, and the second `#undef' templates.
-# And first: Protect against being on the right side of a sed subst in
-# config.status.  Protect against being in an unquoted here document
-# in config.status.
-rm -f conftest.defines conftest.undefs
-# Using a here document instead of a string reduces the quoting nightmare.
-# Putting comments in sed scripts is not portable.
-#
-# `end' is used to avoid that the second main sed command (meant for
-# 0-ary CPP macros) applies to n-ary macro definitions.
-# See the Autoconf documentation for `clear'.
-cat >confdef2sed.sed <<\_ACEOF
-s/[\\&,]/\\&/g
-s,[\\$`],\\&,g
-t clear
-: clear
-s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*\)\(([^)]*)\)[	 ]*\(.*\)$,${ac_dA}\1${ac_dB}\1\2${ac_dC}\3${ac_dD},gp
-t end
-s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)$,${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD},gp
-: end
-_ACEOF
-# If some macros were called several times there might be several times
-# the same #defines, which is useless.  Nevertheless, we may not want to
-# sort them, since we want the *last* AC-DEFINE to be honored.
-uniq confdefs.h | sed -n -f confdef2sed.sed >conftest.defines
-sed 's/ac_d/ac_u/g' conftest.defines >conftest.undefs
-rm -f confdef2sed.sed
-
-# This sed command replaces #undef with comments.  This is necessary, for
-# example, in the case of _POSIX_SOURCE, which is predefined and required
-# on some systems where configure will not decide to define it.
-cat >>conftest.undefs <<\_ACEOF
-s,^[	 ]*#[	 ]*undef[	 ][	 ]*[a-zA-Z_][a-zA-Z_0-9]*,/* & */,
-_ACEOF
-
-# Break up conftest.defines because some shells have a limit on the size
-# of here documents, and old seds have small limits too (100 cmds).
-echo '  # Handle all the #define templates only if necessary.' >>$CONFIG_STATUS
-echo '  if grep "^[	 ]*#[	 ]*define" $tmp/in >/dev/null; then' >>$CONFIG_STATUS
-echo '  # If there are no defines, we may have an empty if/fi' >>$CONFIG_STATUS
-echo '  :' >>$CONFIG_STATUS
-rm -f conftest.tail
-while grep . conftest.defines >/dev/null
-do
-  # Write a limited-size here document to $tmp/defines.sed.
-  echo '  cat >$tmp/defines.sed <<CEOF' >>$CONFIG_STATUS
-  # Speed up: don't consider the non `#define' lines.
-  echo '/^[	 ]*#[	 ]*define/!b' >>$CONFIG_STATUS
-  # Work around the forget-to-reset-the-flag bug.
-  echo 't clr' >>$CONFIG_STATUS
-  echo ': clr' >>$CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.defines >>$CONFIG_STATUS
-  echo 'CEOF
-  sed -f $tmp/defines.sed $tmp/in >$tmp/out
-  rm -f $tmp/in
-  mv $tmp/out $tmp/in
-' >>$CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.defines >conftest.tail
-  rm -f conftest.defines
-  mv conftest.tail conftest.defines
-done
-rm -f conftest.defines
-echo '  fi # grep' >>$CONFIG_STATUS
-echo >>$CONFIG_STATUS
-
-# Break up conftest.undefs because some shells have a limit on the size
-# of here documents, and old seds have small limits too (100 cmds).
-echo '  # Handle all the #undef templates' >>$CONFIG_STATUS
-rm -f conftest.tail
-while grep . conftest.undefs >/dev/null
-do
-  # Write a limited-size here document to $tmp/undefs.sed.
-  echo '  cat >$tmp/undefs.sed <<CEOF' >>$CONFIG_STATUS
-  # Speed up: don't consider the non `#undef'
-  echo '/^[	 ]*#[	 ]*undef/!b' >>$CONFIG_STATUS
-  # Work around the forget-to-reset-the-flag bug.
-  echo 't clr' >>$CONFIG_STATUS
-  echo ': clr' >>$CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.undefs >>$CONFIG_STATUS
-  echo 'CEOF
-  sed -f $tmp/undefs.sed $tmp/in >$tmp/out
-  rm -f $tmp/in
-  mv $tmp/out $tmp/in
-' >>$CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.undefs >conftest.tail
-  rm -f conftest.undefs
-  mv conftest.tail conftest.undefs
-done
-rm -f conftest.undefs
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-  # Let's still pretend it is `configure' which instantiates (i.e., don't
-  # use $as_me), people would be surprised to read:
-  #    /* config.h.  Generated by config.status.  */
-  if test x"$ac_file" = x-; then
-    echo "/* Generated by configure.  */" >$tmp/config.h
-  else
-    echo "/* $ac_file.  Generated by configure.  */" >$tmp/config.h
-  fi
-  cat $tmp/in >>$tmp/config.h
-  rm -f $tmp/in
-  if test x"$ac_file" != x-; then
-    if diff $ac_file $tmp/config.h >/dev/null 2>&1; then
-      { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
-echo "$as_me: $ac_file is unchanged" >&6;}
-    else
-      ac_dir=`(dirname "$ac_file") 2>/dev/null ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$ac_file" : 'X\(//\)[^/]' \| \
-	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-      { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
-    as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-    done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
-   { (exit 1); exit 1; }; }; }
-
-      rm -f $ac_file
-      mv $tmp/config.h $ac_file
-    fi
-  else
-    cat $tmp/config.h
-    rm -f $tmp/config.h
-  fi
-done
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-{ (exit 0); exit 0; }
-_ACEOF
-chmod +x $CONFIG_STATUS
-ac_clean_files=$ac_clean_files_save
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded.  So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status.  When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
-  ac_cs_success=:
-  ac_config_status_args=
-  test "$silent" = yes &&
-    ac_config_status_args="$ac_config_status_args --quiet"
-  exec 5>/dev/null
-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
-  exec 5>>config.log
-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
-  # would make configure fail if this is the last instruction.
-  $ac_cs_success || { (exit 1); exit 1; }
-fi
-
diff --git a/configure.ac b/configure.ac
deleted file mode 100644
--- a/configure.ac
+++ /dev/null
@@ -1,175 +0,0 @@
-
-# sanity
-AC_INIT(HSCurses/Curses.hsc)
-
-# Prepare to generate the config.h.in file
-AC_CONFIG_HEADERS([cbits/config.h])
-
-# this is arbitrary
-AC_PREREQ([2.52])
-
-#
-# Looking for HC, stolen from $fptools
-#
-AC_ARG_WITH(hc,
-[AC_HELP_STRING([--with-hc=ARG],
-    [Use ARG as the path to a Haskell compiler [default=autodetect]])],
-[ WithGhc="$withval" 
-  if test "$WithGhc" = "nhc98"; then
-    AC_DEFINE(__NHC__, [], [Defined if compiling with nhc98])
-    SYMS="$SYMS -D__NHC__"
-  fi
-],
-[
-  if test "$GHC" = ""; then
-    AC_CHECK_PROGS(GHC,ghc)
-  fi
-  if test "$GHC" = ""; then
-    AC_CHECK_PROGS(GHC,nhc98)
-  fi
-  if test "$GHC" = "nhc98"; then
-    AC_DEFINE(__NHC__, [], [Defined if compiling with nhc98])
-    SYMS="$SYMS -D__NHC__"
-  fi
-  WithGhc=`which $GHC`
-])
-AC_SUBST(WithGhc)
-
-# code generation option for GHC (normally, we want to use `-fvia-C', however,
-# with ghc-6.4 -fvia-C produces a buggy binary, dying with:
-#       user error (Curses[-1]:keypad))
-if test `$WithGhc --numeric-version 2> /dev/null` = "6.4"; then
-  GhcCodegen="-fasm"
-else
-  GhcCodegen="-fvia-C"
-fi
-AC_SUBST(GhcCodegen)
-
-#
-# Look for a ghc-pkg that matches our ghc version.
-#
-ghc_pkg_guess=`dirname $WithGhc`/ghc-pkg-`$WithGhc --numeric-version`
-if "$ghc_pkg_guess" -l > /dev/null 2>&1; then
-      matching_ghc_pkg=$ghc_pkg_guess
-else
-      matching_ghc_pkg=no
-fi
-if test x"$matching_ghc_pkg" = xno; then
-    AC_CHECK_PROG(GhcPkgCmd, ghc-pkg, ghc-pkg)
-else
-    GhcPkgCmd=$matching_ghc_pkg
-fi
-AC_SUBST(GhcPkgCmd)
-
-# check if ghc-pkg has version >= or < 6.4
-ghcPkgVersion=`$GhcPkgCmd --version | sed 's/GHC package manager version //'`
-echo -e "$ghcPkgVersion\n6.3" | sort -c > /dev/null 2>&1
-sorted=$?
-if test $sorted -eq 0; then
-  cp ./hscurses.conf.m4.in.before64 ./hscurses.conf.m4.in
-else
-  cp ./hscurses.conf.m4.in.64 ./hscurses.conf.m4.in
-fi
-
-#
-# Look for a hsc2hs that matches our ghc version.
-#
-hsc2hs_guess=`dirname $WithGhc`/hsc2hs
-if "$hsc2hs_guess" -V > /dev/null 2>&1; then
-  Hsc2hsCmd=$hsc2hs_guess
-else
-  AC_CHECK_PROG(Hsc2hsCmd, hsc2hs, hsc2hs)
-fi
-AC_SUBST(Hsc2hsCmd)
-
-
-#
-# And some other tools
-#
-# AC_CHECK_PROG(AlexCmd,alex,alex)
-# AC_CHECK_PROG(HappyCmd,happy,happy)
-AC_CHECK_PROG(GccCmd, gcc, gcc)
-AC_CHECK_PROG(HaddockCmd,haddock,haddock)
-
-AC_CHECK_PROG(STRIP,strip,strip)
-AC_PATH_PROG(LdCmd,ld)
-
-# check for -x flag to ld. stolen from $fptools
-AC_DEFUN(FPTOOLS_LD_X,
-[AC_CACHE_CHECK([whether ld understands -x], fptools_cv_ld_x,
-[
-echo 'foo() {}' > conftest.c
-${CC-cc} -c conftest.c
-if ${LdCmd} -r -x -o foo.o conftest.o; then
-   fptools_cv_ld_x=yes 
-else
-   fptools_cv_ld_x=no
-fi
-rm -rf conftest.c conftest.o foo.o 
-])
-if test "$fptools_cv_ld_x" = yes; then
-    LdXFlag=-x
-else
-    LdXFlag=
-fi
-AC_SUBST(LdXFlag)
-])
-
-FPTOOLS_LD_X
-
-#
-# May as well check for this
-#
-AC_PROG_RANLIB
-
-#
-# Curses. If you don't have wchar_t-aware ncurses (Debian package:
-# libncursesw5-dev),  uncomment the first line and comment-out the
-# two later. 
-#
-# The shell variables should be added to, e.g., $LIBS
-#
-AC_CHECK_LIB(curses,  addnstr)
-AC_CHECK_LIB(ncurses, addnstr)
-AC_CHECK_LIB(ncursesw,waddnwstr)
-
-AC_CHECK_LIB(iconv, iconv)
-AC_CHECK_LIB(iconv, libiconv)
-
-# Bit weird. On OpenBSD you need the 'lib' suffix to iconv functions, it seems
-AC_CHECK_FUNCS(libiconv, AC_DEFINE( [ICONV_LIB_PREFIX],[1],
-                [Define to 1 if you need a 'lib' prefix to iconv functions]))
-
-# On linux we need to call doupdate() after endwin() to restore the term
-if uname -s | grep Linux > /dev/null 2>&1 ; then
-    AC_DEFINE( [NCURSES_UPDATE_AFTER_END],[1],
-               [Define to 1 if you need to call doupdate after endwin])
-fi
-
-# some special libs need to be set for package.conf files
-if echo "$LIBS" | grep iconv > /dev/null 2>&1 ; then
-    ICONV=iconv
-fi
-
-if (echo "$LIBS" | grep ncursesw) >/dev/null 2>&1 ; then
-    CURSES=ncursesw
-elif (echo "$LIBS" | grep ncurses) >/dev/null 2>&1 ; then
-    CURSES=ncurses
-else
-    CURSES=curses
-fi
-AC_SUBST(ICONV)
-AC_SUBST(CURSES)
-
-#
-# Specific headers to check for
-#
-AC_CHECK_HEADERS([iconv.h curses.h ncurses.h ncursesw/ncurses.h locale.h langinfo.h wchar.h limits.h signal.h ])
-
-AC_SUBST(SYMS)
-
-current_directory=`pwd`
-AC_SUBST(current_directory)
-
-AC_CONFIG_FILES([mk/config.mk hscurses.conf.m4 hscurses.buildinfo])
-AC_OUTPUT
diff --git a/example/ContactManager.hs b/example/ContactManager.hs
--- a/example/ContactManager.hs
+++ b/example/ContactManager.hs
@@ -1,5 +1,5 @@
 -- Copyright (c) 2005 Stefan Wehr (http://www.stefanwehr.de)
--- 
+--
 -- Permission is hereby granted, free of charge, to any person obtaining a
 -- copy of this software and associated documentation files (the
 -- "Software"), to deal in the Software without restriction, including
@@ -7,10 +7,10 @@
 -- distribute, sublicense, and/or sell copies of the Software, and to
 -- permit persons to whom the Software is furnished to do so, subject to
 -- the following conditions:
--- 
+--
 -- The above copyright notice and this permission notice shall be included
 -- in all copies or substantial portions of the Software.
--- 
+--
 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
@@ -19,7 +19,7 @@
 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
--- Simple addressbook application to show the capabilities of the hscurses 
+-- Simple addressbook application to show the capabilities of the hscurses
 -- library, especially its widget set.
 
 module Main where
@@ -31,16 +31,18 @@
 * add
 -}
 
-import List ( sort )
-import System
 import Control.Exception
 import Control.Monad.State
+import Data.List ( sort )
+import System.Environment (getArgs, getProgName)
+import System.Exit (exitFailure)
 import Text.PrettyPrint.HughesPJ
-import qualified HSCurses.Curses as Curses
-import qualified HSCurses.CursesHelper as CursesH
-import HSCurses.Widgets
-import HSCurses.Logging
 
+import UI.HSCurses.Logging
+import UI.HSCurses.Widgets
+import qualified UI.HSCurses.Curses as Curses
+import qualified UI.HSCurses.CursesHelper as CursesH
+
 type Name = String
 type Email = String
 type Address = String
@@ -75,10 +77,10 @@
                , phoneNumber      = ""
                }
 
-pprContact c = 
+pprContact c =
     pprLine (combine (lastName c) ", " (firstName c)) $
     pprLine (address c) $
-    pprLine (combine (zipCode c) " " (city c)) $ 
+    pprLine (combine (zipCode c) " " (city c)) $
     pprLine (province c) $
     pprLine (country c) $
     pprLine (phoneNumber c) $
@@ -93,7 +95,7 @@
     combine s1 delim s2 = s1 ++ delim ++ s2
 
 contactToLabelValueList :: Contact -> [(String, String)]
-contactToLabelValueList c = 
+contactToLabelValueList c =
     [ ("Last Name", lastName c)
     , ("First Name", firstName c)
     , ("Email", emailAddress c)
@@ -105,14 +107,14 @@
     , ("Phone", phoneNumber c) ]
 
 readContacts :: FilePath -> IO [Contact]
-readContacts f = 
+readContacts f =
     do s <- readFile f
        case reads s of
          [(contacts, [])] -> return (sort contacts)
          _ -> error ("corrupt contact file: " ++ f)
 
 writeContacts :: FilePath -> [Contact] -> IO ()
-writeContacts f contacts = 
+writeContacts f contacts =
     writeFile f (show contacts)
 
 sampleContacts =
@@ -138,11 +140,11 @@
                    , city = "Sydney"
                    , country = "Australia" } ]
 
-    
+
 title = "contact-manager"
 
 help = "q:quit, d:delete, a:add"
-                              
+
 data CMState = CMState
     { cm_styles  :: [CursesH.CursesStyle]
     , cm_contacts :: [Contact]
@@ -150,29 +152,29 @@
 type CM = StateT CMState IO
 
 runCM :: [CursesH.CursesStyle] -> [Contact] -> CM a -> IO a
-runCM stys contacts cm = evalStateT cm (CMState { cm_styles = stys 
+runCM stys contacts cm = evalStateT cm (CMState { cm_styles = stys
                                                 , cm_contacts = contacts })
 
 nthStyle :: Int -> CM CursesH.CursesStyle
-nthStyle n = 
+nthStyle n =
     do cs <- gets cm_styles
        return $ cs !! n
 
 getSize = liftIO $ Curses.scrSize
- 
+
 styles = [ CursesH.defaultStyle
          , CursesH.AttributeStyle [CursesH.Bold] CursesH.GreenF CursesH.DarkBlueB
          ]
 
-    
+
 defStyle = nthStyle 0
 lineStyle = nthStyle 1
 
-lineDrawingStyle = 
+lineDrawingStyle =
     do sty <- lineStyle
        return $ mkDrawingStyle sty
 
-lineOptions = 
+lineOptions =
     do sz <- getSize
        ds <- lineDrawingStyle
        return $ TWOptions { twopt_size = TWSizeFixed (1, getWidth sz),
@@ -187,13 +189,13 @@
 type ContactDetailsWidget = TextWidget
 type ContactEditWidget = TableWidget
 
-mkToplineWidget = 
+mkToplineWidget =
     do opts <- lineOptions
-       return $ newTextWidget (opts { twopt_halign = AlignCenter }) 
+       return $ newTextWidget (opts { twopt_halign = AlignCenter })
                   title
 
 mkMidlineWidget :: ContactListWidget -> CM MidlineWidget
-mkMidlineWidget listWidget = 
+mkMidlineWidget listWidget =
     do opts <- lineOptions
        contacts <- gets cm_contacts
        let s = case tbw_pos listWidget of
@@ -201,7 +203,7 @@
                  Just (row, _) -> show (1+row) ++ "/" ++ show (length contacts)
        return $ newTextWidget  (opts { twopt_halign = AlignRight }) s
 
-mkBotlineWidget = 
+mkBotlineWidget =
     do opts <- lineOptions
        return $ newTextWidget opts help
 
@@ -209,7 +211,7 @@
 -- i.e. at the lower-right corner of the message line. Otherwise, an
 -- error occurs because drawing a character to this position moves the
 -- cursor to the next line, which doesn't exist.
-mkMsglineWidget = 
+mkMsglineWidget =
     do sz <- getSize
        let width = getWidth sz
            opts = TWOptions { twopt_size = TWSizeFixed (1, width - 1),
@@ -224,11 +226,11 @@
 
 contactListHeight (h, _) = (h - nlines) `div` 2
 
-contactDetailsHeight (h, _) = 
+contactDetailsHeight (h, _) =
     let n = h - nlines
         in n `div` 2 + (n `mod` 2)
 
-contactListOptions = 
+contactListOptions =
     do sz <- getSize
        return $ TBWOptions
                   { tbwopt_fillCol = Nothing,
@@ -236,39 +238,39 @@
                     tbwopt_activeCols = [0],
                     tbwopt_minSize = (contactListHeight sz, getWidth sz) }
 
-contactDetailsOptions = 
+contactDetailsOptions =
     do sz <- getSize
-       return $ TWOptions { twopt_size = TWSizeFixed (contactDetailsHeight sz, 
+       return $ TWOptions { twopt_size = TWSizeFixed (contactDetailsHeight sz,
                                                          getWidth sz),
                             twopt_style = defaultDrawingStyle,
                             twopt_halign = AlignLeft }
 
 mkContactListWidget :: CM ContactListWidget
-mkContactListWidget = 
+mkContactListWidget =
     do contacts <- gets cm_contacts
        sz <- getSize
        let lines = alignRows (map contactLine contacts) ' ' "  "
            rows = map (contactRow $ getWidth sz) lines
-       opts <- contactListOptions 
+       opts <- contactListOptions
        return $ newTableWidget opts rows
     where contactLine c = [lastName c, firstName c, emailAddress c]
-          contactRow w s = [TableCell $ newTextWidget 
+          contactRow w s = [TableCell $ newTextWidget
                             (defaultTWOptions { twopt_size = TWSizeFixed (1, w) }) s]
           lastRow = [TableCell (EmptyWidget (0,0))]
 
 mkContactDetailsWidget :: ContactListWidget -> CM ContactDetailsWidget
-mkContactDetailsWidget listWidget = 
+mkContactDetailsWidget listWidget =
     do contacts <- gets cm_contacts
        let contact = case tbw_pos listWidget of
                        Nothing -> ""
-                       Just (row, _) -> 
+                       Just (row, _) ->
                            let c = contacts !! row
                                in show $ pprContact c
        opts <- contactDetailsOptions
        return $ newTextWidget opts contact
 
 mkContactEditWidget :: Contact -> CM ContactEditWidget
-mkContactEditWidget contact = 
+mkContactEditWidget contact =
     let l = contactToLabelValueList contact
         rows = map mkRow l
         in do sz <- getSize
@@ -278,12 +280,12 @@
                            tbwopt_activeCols = [1],
                            tbwopt_minSize = (getHeight sz - 3, getWidth sz) }
               return $ newTableWidget opts rows
-    where mkRow (label, value) = 
+    where mkRow (label, value) =
               let labelW = newTextWidget defaultTWOptions label
                   valueW = newEditWidget defaultEWOptions value
                   in [TableCell labelW, ActiveTableCell valueW]
 
-mkMainEditWidget contact = 
+mkMainEditWidget contact =
     do tlw <- mkToplineWidget
        blw <- mkBotlineWidget
        msglw <- mkMsglineWidget
@@ -296,7 +298,7 @@
     , msglineEditWidget :: MsglineWidget
     , contactEditWidget :: ContactEditWidget }
 
-mkMainWidget = 
+mkMainWidget =
     do tlw <- mkToplineWidget
        clw <- mkContactListWidget
        mlw <- mkMidlineWidget clw
@@ -310,7 +312,7 @@
     minSize w = minSize (mkRealMainEditWidget Nothing w)
 
 mkRealMainEditWidget :: (Maybe Size) -> MainEditWidget -> TableWidget
-mkRealMainEditWidget msz w = 
+mkRealMainEditWidget msz w =
     let cells = [ TableCell $ toplineEditWidget w
                 , TableCell $ contactEditWidget w
                 , TableCell $ botlineEditWidget w
@@ -333,7 +335,7 @@
     draw pos sz hint w = draw pos sz hint (mkRealMainWidget (Just sz) w)
     minSize w = minSize (mkRealMainWidget Nothing w)
 
-mkRealMainWidget msz w = 
+mkRealMainWidget msz w =
     let cells = [ TableCell $ toplineWidget w
                 , TableCell $ contactListWidget w
                 , TableCell $ midlineWidget w
@@ -355,12 +357,12 @@
                   , midlineWidget = midlineWidget }
 
 move :: Direction -> MainWidget -> CM MainWidget
-move dir w = 
+move dir w =
     do sz <- getSize
        let listWidget = tableWidgetMove dir sz (contactListWidget w)
        updateStateDependentWidgets w listWidget
 
-delete w = 
+delete w =
     let lw = contactListWidget w
         in case tbw_pos lw of
              Nothing -> return w
@@ -386,7 +388,7 @@
          _ -> editEventloop w ewm
 -}
 
-edit w = 
+edit w =
     let lw = contactListWidget w
         in case tbw_pos lw of
              Nothing -> return w
@@ -396,10 +398,10 @@
                     ew <- mkMainEditWidget c
                     redraw ew
                     return w
-                    --editEventloop w ew 
+                    --editEventloop w ew
 
-resize :: Widget w => CM w -> CM ()                   
-resize f = 
+resize :: Widget w => CM w -> CM ()
+resize f =
     do liftIO $ do Curses.endWin
                    Curses.resetParams
                    Curses.cursSet Curses.CursorInvisible
@@ -408,12 +410,12 @@
        redraw w
 
 redraw :: Widget w => w -> CM ()
-redraw w = 
+redraw w =
     do sz <- getSize
        liftIO $ draw (0, 0) sz DHNormal w
        liftIO $ Curses.refresh
 
-eventloop w = 
+eventloop w =
     do k <- CursesH.getKey (resize mkMainWidget)
        case k of
          Curses.KeyChar 'q' -> return ()
@@ -422,19 +424,19 @@
          Curses.KeyUp       -> process $ move DirUp w
          Curses.KeyDown     -> process $ move DirDown w
          _ -> eventloop w
-    where process f = 
+    where process f =
               do w' <- f
                  redraw w'
                  eventloop w'
 cmMain :: CM ()
-cmMain = 
+cmMain =
     do w <- mkMainWidget
        redraw w
        eventloop w
 
 
 main :: IO ()
-main = 
+main =
     do args <- getArgs
        contacts <-
              if length args /= 1
@@ -443,7 +445,7 @@
                         exitFailure
                 else readContacts (args!!0)
        runCurses contacts `finally` CursesH.end
-    where runCurses contacts = 
+    where runCurses contacts =
               do CursesH.start
                  cstyles <- CursesH.convertStyles styles
                  Curses.cursSet Curses.CursorInvisible
diff --git a/example/Makefile b/example/Makefile
deleted file mode 100644
--- a/example/Makefile
+++ /dev/null
@@ -1,9 +0,0 @@
-GHC = ghc
-PKG_CONF = ../hscurses.conf
-
-cm: ContactManager.hs $(PKG_CONF)
-	$(GHC) --make -package-conf $(PKG_CONF) -package hscurses -o $@ $<
-
-.PHONY: clean
-clean:
-	rm -f *.o *.hi cm	
diff --git a/example/Setup.hs b/example/Setup.hs
--- a/example/Setup.hs
+++ b/example/Setup.hs
@@ -1,3 +1,3 @@
 #!/usr/bin/env runhaskell
 import Distribution.Simple
-main = defaultMainWithHooks defaultUserHooks
+main = defaultMainWithHooks simpleUserHooks
diff --git a/example/cm.cabal b/example/cm.cabal
--- a/example/cm.cabal
+++ b/example/cm.cabal
@@ -4,7 +4,9 @@
 License:       GPL
 License-file:  ../LICENSE
 Author:   Stefan Wehr <http://www.informatik.uni-freiburg.de/~wehr>
-Build-Depends:       base, hscurses >= 1.0, mtl, haskell98
+
+Build-Depends:       base>3, hscurses >= 1.2, mtl, pretty
+Build-Type:          Simple
 
 Executable:          cm
 Main-Is:             ContactManager.hs
diff --git a/hscurses.buildinfo.in b/hscurses.buildinfo.in
deleted file mode 100644
--- a/hscurses.buildinfo.in
+++ /dev/null
@@ -1,1 +0,0 @@
-Extra-libraries:  @CURSES@ @ICONV@
diff --git a/hscurses.cabal b/hscurses.cabal
--- a/hscurses.cabal
+++ b/hscurses.cabal
@@ -1,5 +1,5 @@
 Name:           hscurses
-Version:        1.2
+Version:        1.3
 License:        LGPL
 License-file:   LICENSE
 Author:         John Meacham <john at repetae dot net>
@@ -21,29 +21,28 @@
     a table widget.
 Homepage:       http://www.informatik.uni-freiburg.de/~wehr/haskell/
 
-Build-depends:  base >= 1.0, haskell98 >= 1.0, unix >= 1.0, mtl >= 1.0
+Build-depends:  base >= 1.0, unix >= 1.0, mtl >= 1.0, old-time, old-locale
 Build-Type:     Simple
 Tested-with:    GHC==6.8.2, GHC==6.6.1
 
 Exposed-modules:
-    HSCurses.Curses, HSCurses.CursesHelper, HSCurses.Widgets,
-    HSCurses.MonadException, HSCurses.Logging
+    UI.HSCurses.Curses, UI.HSCurses.CursesHelper, UI.HSCurses.Widgets,
+    UI.HSCurses.MonadException, UI.HSCurses.Logging
 Other-modules:
-    HSCurses.CWString, HSCurses.IConv
+    UI.HSCurses.CWString, UI.HSCurses.IConv
 C-sources:
     cbits/HSCursesUtils.c
 Includes:
     HSCurses.h, HSCursesUtils.h
 Data-files:
     README, TODO, example/contacts2, example/Setup.hs, example/ContactManager.hs,
-    example/cm.cabal, example/contacts, example/Makefile
+    example/cm.cabal, example/contacts
 Extra-source-files:
-    configure, hscurses.conf.m4.in.before64, HSCurses/Curses.hsc,
-    HSCurses/CursesHelper.hs, HSCurses/CWString.hsc, HSCurses/Widgets.hs,
-    HSCurses/MonadException.hs, HSCurses/Logging.hs, HSCurses/IConv.hsc,
-    install-sh, hscurses.conf.m4.in.64, hscurses.buildinfo.in, configure.ac,
-    cbits/config.h.in, cbits/HSCursesUtils.h, cbits/HSCurses.h, Makefile,
-    mk/config.mk.in, mk/rules.mk, mk/paths.mk
-Extensions:       CPP, ForeignFunctionInterface
+    UI/HSCurses/Curses.hsc,
+    UI/HSCurses/CursesHelper.hs, UI/HSCurses/CWString.hsc, UI/HSCurses/Widgets.hs,
+    UI/HSCurses/MonadException.hs, UI/HSCurses/Logging.hs, UI/HSCurses/IConv.hsc,
+    cbits/config.h.in, cbits/HSCursesUtils.h, cbits/HSCurses.h
+
+Extensions:       CPP, ForeignFunctionInterface, GeneralizedNewtypeDeriving, ScopedTypeVariables, ExistentialQuantification
 Include-dirs:     cbits .
-Ghc-options:      -funbox-strict-fields
+Ghc-options:      -funbox-strict-fields -Wall -fvia-c
diff --git a/hscurses.conf.m4.in.64 b/hscurses.conf.m4.in.64
deleted file mode 100644
--- a/hscurses.conf.m4.in.64
+++ /dev/null
@@ -1,43 +0,0 @@
-dnl Package configuration file for use with ghc-pkg >= 6.4
-
-Name:           hscurses
-Version:        1.0
-License:        LGPL
-License-file:   LICENSE
-Author:         John Meacham <john at repetae dot net>
-                Tuomo Valkonen <tuomov at iki.fi>
-                Don Stewart <http://www.cse.unsw.edu.au/~dons>
-                Stefan Wehr <http://www.stefanwehr.de>
-Maintainer:     Stefan Wehr <http://www.stefanwehr.de>
-Copyright:      Stefan Wehr 2004, 2005
-                Don Stewart 2004
-                Tuomo Valkonen 2004
-                John Meacham 2002-2004
-Homepage:       http://www.stefanwehr.de/haskell
-Category:       User-interface
-Depends:        base, haskell98, unix
-Synopsis:       NCurses bindings for Haskell
-Description:   
-  Binding to NCurses, a library of functions that manage an
-  application's display on character-cell terminals. Additionally,
-  it contains some basic widgets such as a text input widget and
-  a table widget.
-Exposed-modules:
-    HSCurses.Curses, HSCurses.CursesHelper, HSCurses.Widgets,
-    HSCurses.MonadException, HSCurses.Logging
-Hidden-modules:
-    HSCurses.CWString, HSCurses.IConv
-C-sources:      
-    cbits/HSCursesUtils.c HSCurses/CWString_hsc.c HSCurses/Curses_hsc.c
-Includes:         HSCurses.h, HSCursesUtils.h
-hs-libraries:     hscurses
-Extra-libraries:  @CURSES@ @ICONV@
-ifdef(`__INSTALLING__', `
-Import-dirs:      @prefix@/lib/hscurses/imports
-Library-dirs:     @prefix@/lib/hscurses
-Include-dirs:     @prefix@/include/hscurses
-',`
-Import-dirs:      @current_directory@
-Library-dirs:     @current_directory@
-Include-dirs:     @current_directory@/cbits
-')
diff --git a/hscurses.conf.m4.in.before64 b/hscurses.conf.m4.in.before64
deleted file mode 100644
--- a/hscurses.conf.m4.in.before64
+++ /dev/null
@@ -1,23 +0,0 @@
-dnl Package configuration file for use with ghc-pkg < 6.4
-
-Package {
-        name            = "hscurses",
-        auto            = False,
-        hs_libraries    = [ "hscurses" ],
-ifdef(`__INSTALLING__', `
-        import_dirs     = [ "@prefix@/lib/hscurses/imports" ],
-        library_dirs    = [ "@prefix@/lib/hscurses" ],
-        include_dirs    = [ "@prefix@/include/hscurses" ],
-',`
-        import_dirs     = [ "@current_directory@" ],
-        library_dirs    = [ "@current_directory@" ],
-        include_dirs    = [ "@current_directory@/cbits" ],
-')
-        c_includes      = [ "HSCurses.h", "HSCursesUtils.h" ],
-        source_dirs     = [],
-        extra_libraries = [ "@CURSES@", "@ICONV@" ],
-        package_deps    = [ "base", "haskell98", "posix" ],
-        extra_ghc_opts  = [],
-        extra_cc_opts   = [],
-        extra_ld_opts   = []
-}
diff --git a/install-sh b/install-sh
deleted file mode 100644
--- a/install-sh
+++ /dev/null
@@ -1,251 +0,0 @@
-#!/bin/sh
-#
-# install - install a program, script, or datafile
-# This comes from X11R5 (mit/util/scripts/install.sh).
-#
-# Copyright 1991 by the Massachusetts Institute of Technology
-#
-# Permission to use, copy, modify, distribute, and sell this software and its
-# documentation for any purpose is hereby granted without fee, provided that
-# the above copyright notice appear in all copies and that both that
-# copyright notice and this permission notice appear in supporting
-# documentation, and that the name of M.I.T. not be used in advertising or
-# publicity pertaining to distribution of the software without specific,
-# written prior permission.  M.I.T. makes no representations about the
-# suitability of this software for any purpose.  It is provided "as is"
-# without express or implied warranty.
-#
-# Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
-# when there is no Makefile.
-#
-# This script is compatible with the BSD install script, but was written
-# from scratch.  It can only install one file at a time, a restriction
-# shared with many OS's install programs.
-
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit="${DOITPROG-}"
-
-
-# put in absolute paths if you don't have them in your path; or use env. vars.
-
-mvprog="${MVPROG-mv}"
-cpprog="${CPPROG-cp}"
-chmodprog="${CHMODPROG-chmod}"
-chownprog="${CHOWNPROG-chown}"
-chgrpprog="${CHGRPPROG-chgrp}"
-stripprog="${STRIPPROG-strip}"
-rmprog="${RMPROG-rm}"
-mkdirprog="${MKDIRPROG-mkdir}"
-
-transformbasename=""
-transform_arg=""
-instcmd="$mvprog"
-chmodcmd="$chmodprog 0755"
-chowncmd=""
-chgrpcmd=""
-stripcmd=""
-rmcmd="$rmprog -f"
-mvcmd="$mvprog"
-src=""
-dst=""
-dir_arg=""
-
-while [ x"$1" != x ]; do
-    case $1 in
-	-c) instcmd="$cpprog"
-	    shift
-	    continue;;
-
-	-d) dir_arg=true
-	    shift
-	    continue;;
-
-	-m) chmodcmd="$chmodprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-o) chowncmd="$chownprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-g) chgrpcmd="$chgrpprog $2"
-	    shift
-	    shift
-	    continue;;
-
-	-s) stripcmd="$stripprog"
-	    shift
-	    continue;;
-
-	-t=*) transformarg=`echo $1 | sed 's/-t=//'`
-	    shift
-	    continue;;
-
-	-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
-	    shift
-	    continue;;
-
-	*)  if [ x"$src" = x ]
-	    then
-		src=$1
-	    else
-		# this colon is to work around a 386BSD /bin/sh bug
-		:
-		dst=$1
-	    fi
-	    shift
-	    continue;;
-    esac
-done
-
-if [ x"$src" = x ]
-then
-	echo "install:	no input file specified"
-	exit 1
-else
-	true
-fi
-
-if [ x"$dir_arg" != x ]; then
-	dst=$src
-	src=""
-	
-	if [ -d $dst ]; then
-		instcmd=:
-		chmodcmd=""
-	else
-		instcmd=mkdir
-	fi
-else
-
-# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
-# might cause directories to be created, which would be especially bad 
-# if $src (and thus $dsttmp) contains '*'.
-
-	if [ -f $src -o -d $src ]
-	then
-		true
-	else
-		echo "install:  $src does not exist"
-		exit 1
-	fi
-	
-	if [ x"$dst" = x ]
-	then
-		echo "install:	no destination specified"
-		exit 1
-	else
-		true
-	fi
-
-# If destination is a directory, append the input filename; if your system
-# does not like double slashes in filenames, you may need to add some logic
-
-	if [ -d $dst ]
-	then
-		dst="$dst"/`basename $src`
-	else
-		true
-	fi
-fi
-
-## this sed command emulates the dirname command
-dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
-
-# Make sure that the destination directory exists.
-#  this part is taken from Noah Friedman's mkinstalldirs script
-
-# Skip lots of stat calls in the usual case.
-if [ ! -d "$dstdir" ]; then
-defaultIFS='	
-'
-IFS="${IFS-${defaultIFS}}"
-
-oIFS="${IFS}"
-# Some sh's can't handle IFS=/ for some reason.
-IFS='%'
-set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
-IFS="${oIFS}"
-
-pathcomp=''
-
-while [ $# -ne 0 ] ; do
-	pathcomp="${pathcomp}${1}"
-	shift
-
-	if [ ! -d "${pathcomp}" ] ;
-        then
-		$mkdirprog "${pathcomp}"
-	else
-		true
-	fi
-
-	pathcomp="${pathcomp}/"
-done
-fi
-
-if [ x"$dir_arg" != x ]
-then
-	$doit $instcmd $dst &&
-
-	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
-	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
-	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
-	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
-else
-
-# If we're going to rename the final executable, determine the name now.
-
-	if [ x"$transformarg" = x ] 
-	then
-		dstfile=`basename $dst`
-	else
-		dstfile=`basename $dst $transformbasename | 
-			sed $transformarg`$transformbasename
-	fi
-
-# don't allow the sed command to completely eliminate the filename
-
-	if [ x"$dstfile" = x ] 
-	then
-		dstfile=`basename $dst`
-	else
-		true
-	fi
-
-# Make a temp file name in the proper directory.
-
-	dsttmp=$dstdir/#inst.$$#
-
-# Move or copy the file name to the temp name
-
-	$doit $instcmd $src $dsttmp &&
-
-	trap "rm -f ${dsttmp}" 0 &&
-
-# and set any options; do chmod last to preserve setuid bits
-
-# If any of these fail, we abort the whole thing.  If we want to
-# ignore errors from any of these, just make sure not to ignore
-# errors from the above "$doit $instcmd $src $dsttmp" command.
-
-	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
-	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
-	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
-	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
-
-# Now rename the file to the real destination.
-
-	$doit $rmcmd -f $dstdir/$dstfile &&
-	$doit $mvcmd $dsttmp $dstdir/$dstfile 
-
-fi &&
-
-
-exit 0
diff --git a/mk/config.mk.in b/mk/config.mk.in
deleted file mode 100644
--- a/mk/config.mk.in
+++ /dev/null
@@ -1,55 +0,0 @@
-#
-# System-specific settings
-#
-
-PREFIX=         @prefix@
-BINDIR=         @prefix@/bin
-LIBDIR=         @prefix@/lib/$(PKG)
-DATADIR=        @prefix@/share/doc/$(PKG)
-INCDIR=         @prefix@/include/$(PKG)
-IFACEDIR=       $(LIBDIR)/imports
-
-GHC=            @WithGhc@
-GCC=            @GccCmd@
-INCFLAGS=       -Icbits -I.
-HC_OPTS=        @GhcCodegen@ -funbox-strict-fields
-
-GHC_PKG=        @GhcPkgCmd@
-HSC2HS=         @Hsc2hsCmd@
-
-HADDOCK=        @HaddockCmd@
-HADDOCK_OPTS=   -h
-
-AR=             ar
-AR_OPTS=        cr
-
-LD=             @LdCmd@
-LD_X=           @LdCmd@ @LdXFlag@
-
-RANLIB=         @RANLIB@
-STRIP=          @STRIP@
-
-INSTALL=        sh $(TOPDIR)/install-sh -c
-INSTALL_PROGRAM=$(INSTALL) -m 755
-INSTALL_DATA=   $(INSTALL) -m 644
-INSTALL_DIR=    mkdir -p
-
-CP=             cp
-RM=             rm -f
-
-#
-# Extra paths to find things
-#
-LD_OPTS=        @LDFLAGS@
-INC_OPTS=       @CPPFLAGS@
-C_OPTS=         @CFLAGS@
-LIBS=           @LIBS@
-
-#
-# Special libs needed in package.conf files
-#
-CURSES=         @CURSES@
-ICONV=          @ICONV@
-
-# extra symbols
-SYMS=           @SYMS@
diff --git a/mk/paths.mk b/mk/paths.mk
deleted file mode 100644
--- a/mk/paths.mk
+++ /dev/null
@@ -1,228 +0,0 @@
-################################################################################
-#
-#			    paths.mk
-#
-# 	This file defines Make variables for standard directories
-#	and file lists
-#
-################################################################################
-
-#
-#
-#		Standard variable names
-#
-#
-# The fptools mk setup defines a set of standard names which are used
-# by the standard targets provided by mk. One example of this is the
-# use of standard names for specifying what files to compile, their
-# intermediate/object code, and the name of the final
-# executable. Based on the settings of these variables, the standard
-# targets will generate/expand rules that automatically compile and
-# link your program.
-#
-# The general rules:
-#
-#   SRCS - sources, might be prefixed to indicate what type of source
-#          they are.
-#   OBJS - object files (possibly prefixed).
-#
-#   PROG - name of final executable
-#
-# We attempt to automatically devine the list of sources $(SRCS) to
-# compile by looking in the directories which may be specified by
-# setting the $(ALL_DIRS) variable.  This is complicated by the fact
-# that some files are derived from other files: eg. .hsc files give
-# rise to -hsc.c and -hsc.h files, .ly files give rise to .hs files,
-# and .hs files give rise to .hc files sometimes.
-
-# So we figure out the sources in three stages: first figure out what
-# sources we can find (this is $(ALL_SRCS)).  Then figure out all the
-# "derived" sources (eg. A.hsc generates A.hs and A_hsc.c), and
-# finally put all these together and remove duplicates (GNU make's
-# handy sort function does the duplicate removing).
-
-# HS_SRCS:   list of Haskell modules you want to compile.
-#             (also use by depend rule).
-# HS_OBJS:   list of corresponding object files
-# HS_PROG:   program that is ultimately linked.
-# HS_IFACES: list of interface files generated
-#             (caveat: assuming no funny use of -hisuf and that
-#               file name and module name match)
-
-ALL_SRCS    = $(wildcard $(patsubst ./%, %,  \
-		   $(patsubst %,%/*.hs,   $(ALL_DIRS)) \
-		   $(patsubst %,%/*.lhs,  $(ALL_DIRS)) \
-		   $(patsubst %,%/*.y,    $(ALL_DIRS)) \
-		   $(patsubst %,%/*.ly,   $(ALL_DIRS)) \
-		   $(patsubst %,%/*.x,    $(ALL_DIRS)) \
-		   $(patsubst %,%/*.c,    $(ALL_DIRS)) \
-		   $(patsubst %,%/*.hc,   $(ALL_DIRS)) \
-		   $(patsubst %,%/*.S,    $(ALL_DIRS)) \
-		   $(patsubst %,%/*.prl,  $(ALL_DIRS)) \
-		   $(patsubst %,%/*.lprl, $(ALL_DIRS)) \
-		   $(patsubst %,%/*.lit,  $(ALL_DIRS)) \
-		   $(patsubst %,%/*.verb, $(ALL_DIRS)) \
-		   $(patsubst %,%/*.hsc,  $(ALL_DIRS)) \
-		   $(patsubst %,%/*.gc,   $(ALL_DIRS)) \
-	       )) $(EXTRA_SRCS)
-
-# ALL_SRCS is computed once and for all into PRE_SRCS at the top of
-# rules.mk.  Otherwise, we end up re-computing ALL_SRCS every time it
-# is expanded (it is used in several variables below, and these
-# variables are used in several others, etc.), which can really slow
-# down make.
-
-PRE_HS_SRCS  = $(filter %.hs,  $(PRE_SRCS))
-PRE_LHS_SRCS = $(filter %.lhs, $(PRE_SRCS))
-
-GC_SRCS       = $(filter %.gc,  $(PRE_SRCS))
-HSC_SRCS      = $(filter %.hsc, $(PRE_SRCS))
-HAPPY_Y_SRCS  = $(filter %.y,   $(PRE_SRCS))
-HAPPY_LY_SRCS = $(filter %.ly,   $(PRE_SRCS))
-HAPPY_SRCS    = $(HAPPY_Y_SRCS) $(HAPPY_LY_SRCS)
-ALEX_SRCS     = $(filter %.x,   $(PRE_SRCS))
-
-DERIVED_GC_SRCS       = $(patsubst %.gc, %.hs, $(GC_SRCS)) \
-			$(patsubst %.gc, %_stub_ffi.c, $(GC_SRCS)) \
-			$(patsubst %.gc, %_stub_ffi.h, $(GC_SRCS))
-
-DERIVED_HSC_SRCS      = $(patsubst %.hsc, %.hs, $(HSC_SRCS)) \
-			$(patsubst %.hsc, %_hsc.c, $(HSC_SRCS)) \
-			$(patsubst %.hsc, %_hsc.h, $(HSC_SRCS)) \
-			$(patsubst %.hsc, %.hc, $(HSC_SRCS))
-
-DERIVED_HAPPY_SRCS    = $(patsubst %.y,   %.hs, $(HAPPY_Y_SRCS)) \
-			$(patsubst %.ly,  %.hs, $(HAPPY_LY_SRCS))
-
-DERIVED_ALEX_SRCS     = $(patsubst %.x,   %.hs, $(ALEX_SRCS))
-
-DERIVED_HC_SRCS       = $(patsubst %.hs,  %.hc, $(PRE_HS_SRCS)) \
-			$(patsubst %.lhs, %.hc, $(PRE_LHS_SRCS))
-
-DERIVED_SRCS	      = $(DERIVED_GC_SRCS) \
-			$(DERIVED_HSC_SRCS) \
-			$(DERIVED_HAPPY_SRCS) \
-			$(DERIVED_ALEX_SRCS) \
-			$(DERIVED_HC_SRCS)
-
-# EXCLUDED_SRCS can be set in the Makefile, otherwise it defaults to empty.
-EXCLUDED_GC_SRCS       = $(filter %.gc,  $(EXCLUDED_SRCS))
-EXCLUDED_HSC_SRCS      = $(filter %.hsc, $(EXCLUDED_SRCS))
-EXCLUDED_HAPPY_Y_SRCS  = $(filter %.y,   $(EXCLUDED_SRCS))
-EXCLUDED_HAPPY_LY_SRCS = $(filter %.ly,  $(EXCLUDED_SRCS))
-EXCLUDED_HAPPY_SRCS   = $(EXCLUDED_HAPPY_Y_SRCS) $(EXCLUDED_HAPPY_LY_SRCS)
-EXCLUDED_ALEX_SRCS    = $(filter %.x,   $(EXCLUDED_SRCS))
-EXCLUDED_HS_SRCS      = $(filter %.hs,  $(EXCLUDED_SRCS))
-EXCLUDED_LHS_SRCS     = $(filter %.lhs, $(EXCLUDED_SRCS))
-EXCLUDED_DERIVED_SRCS = $(patsubst %.hsc, %.hs, $(EXCLUDED_HSC_SRCS)) \
-			$(patsubst %.hsc, %_hsc.h, $(EXCLUDED_HSC_SRCS)) \
-			$(patsubst %.hsc, %_hsc.c, $(EXCLUDED_HSC_SRCS)) \
-			$(patsubst %.hsc, %.hc, $(EXCLUDED_HSC_SRCS)) \
-			$(patsubst %.gc,  %_stub_ffi.c, $(EXCLUDED_GC_SRCS)) \
-			$(patsubst %.gc,  %_stub_ffi.h, $(EXCLUDED_GC_SRCS)) \
-                        $(patsubst %.y,   %.hs, $(EXCLUDED_HAPPY_Y_SRCS)) \
-			$(patsubst %.ly,  %.hs, $(EXCLUDED_HAPPY_LY_SRCS)) \
-                        $(patsubst %.x,   %.hs, $(EXCLUDED_ALEX_SRCS)) \
-			$(patsubst %.hs,  %.hc, $(EXCLUDED_HS_SRCS)) \
-			$(patsubst %.lhs, %.hc, $(EXCLUDED_LHS_SRCS)) \
-			$(patsubst %.hs,  %_stub.c, $(EXCLUDED_HS_SRCS)) \
-			$(patsubst %.lhs, %_stub.c, $(EXCLUDED_LHS_SRCS))
-
-# Exclude _hsc.c files; they get built as part of the cbits library,
-# not part of the main library
-
-CLOSED_EXCLUDED_SRCS  = $(sort $(EXCLUDED_SRCS) $(EXCLUDED_DERIVED_SRCS))
-
-SRCS        = $(filter-out $(CLOSED_EXCLUDED_SRCS), \
-	        $(sort $(PRE_SRCS) $(DERIVED_SRCS)))
-
-HS_SRCS	    = $(filter %.lhs %.hs, $(sort $(SRCS) $(BOOT_SRCS)))
-HS_OBJS     = $(addsuffix .$(way_)o,$(basename $(HS_SRCS)))
-HS_IFACES   = $(addsuffix .$(way_)hi,$(basename $(HS_SRCS)))
-
-GC_C_OBJS   = $(addsuffix _stub_ffi.$(way_)o,$(basename $(filter %.gc,$(SRCS))))
-HSC_C_OBJS  = $(addsuffix _hsc.$(way_)o,$(basename $(filter %.hsc,$(SRCS))))
-
-# These are droppings from hsc2hs - ignore them if we see them.
-EXCLUDED_C_SRCS += $(patsubst %.hsc, %_hsc_make.c, $(HSC_SRCS))
-
-C_SRCS      = $(filter-out $(EXCLUDED_C_SRCS),$(filter %.c,$(SRCS)))
-C_OBJS      = $(addsuffix .$(way_)o,$(basename $(C_SRCS)))
-
-# SCRIPT_SRCS:  list of raw script files (in literate form)
-# SCRIPT_OBJS:  de-litted scripts
-SCRIPT_SRCS = $(filter %.lprl,$(SRCS))
-SCRIPT_OBJS = $(addsuffix .prl,$(basename $(SCRIPT_SRCS)))
-
-OBJS        = $(HS_OBJS) $(C_OBJS) $(GC_C_OBJS) 
-
-# The default is for $(LIBOBJS) to be the same as $(OBJS)
-LIBOBJS	    = $(OBJS)
-
-#
-# Note that as long as you use the standard variables for setting
-# which C & Haskell programs you want to work on, you don't have
-# to set any of the clean variables - the default should do the Right
-# Thing.
-#
-
-#------------------------------------------------------------------
-#
-# make depend defaults
-#
-# The default set of files for the dependency generators to work on
-# is just their source equivalents.
-#
-
-MKDEPENDHS_SRCS=$(HS_SRCS)
-MKDEPENDC_SRCS=$(C_SRCS)
-
-#------------------------------------------------------------------
-# Clean file make-variables.
-#
-# The following three variables are used to control
-# what gets removed when doing `make clean'
-#
-# MOSTLYCLEAN_FILES   object code etc., but not stuff
-#                     that is slow to recompile and/or stable
-#
-# CLEAN_FILES  all files that are created by running make.
-#
-# MAINTAINER_CLEAN_FILES also clean out machine-generated files
-#                        that may require extra tools to create.
-#
-#
-# NOTE: $(SCRIPT_OBJS) is not in MOSTLY_CLEAN_FILES, because in some
-# places in the tree it appears that we have source files in $(SCRIPT_OBJS).
-# Specifically glafp-utils/mkdependC/mkdependC.prl and others in ghc/driver and
-# possibly others elsewhere in the tree.  ToDo: fix this properly.
-MOSTLY_CLEAN_FILES += $(HS_OBJS) $(C_OBJS) $(HSC_C_OBJS) $(GC_C_OBJS)
-CLEAN_FILES        += $(HS_PROG) $(C_PROG) $(SCRIPT_PROG) $(SCRIPT_LINK) \
-		      $(PROG) $(LIBRARY) a.out \
-		      $(DERIVED_HSC_SRCS) \
-		      $(DERIVED_GC_SRCS) \
-		      $(patsubst %,%/*.$(way_)hi, . $(ALL_DIRS)) \
-		      $(patsubst %,%/*.p_hi, . $(ALL_DIRS)) \
-		      $(patsubst %,%/*.p_o, . $(ALL_DIRS))
-
-# we delete *all* the .hi files we can find, rather than just
-# $(HS_IFACES), because stale interfaces left around by modules which
-# don't exist any more can screw up the build.
-
-# Don't clean the .hc files if we're bootstrapping
-CLEAN_FILES += $(DERIVED_HC_SRCS)
-
-DIST_CLEAN_FILES 	+= depend* *.hp *.prof configure mk/config.h* mk/config.mk
-DIST_CLEAN_DIRS=  *.cache
-
-MAINTAINER_CLEAN_FILES 	+= $(BOOT_SRCS) $(DERIVED_HAPPY_SRCS) $(DERIVED_ALEX_SRCS)
-
-#
-# `Standard' set of files to clean out.
-#
-MOSTLY_CLEAN_FILES += \
- *.CKP *.ln *.BAK *.bak .*.bak *.o *.p_o core a.out errs ,* *.a .emacs_*  \
- tags TAGS *.ind *.ilg *.idx *.idx-prev *.aux *.aux-prev *.dvi *.log \
- *.toc *.lot *.lof *.blg *.cb *_stub.c *_stub.h *.raw_s *.a.list \
- *.log *.status
-
diff --git a/mk/rules.mk b/mk/rules.mk
deleted file mode 100644
--- a/mk/rules.mk
+++ /dev/null
@@ -1,292 +0,0 @@
-#
-# rules.mk : set flags and make rules
-#
-
-#
-# pull in the file search stuff
-#
-include $(TOPDIR)/mk/paths.mk
-
-PRE_SRCS:=      $(ALL_SRCS)
-
-HC_OPTS        += $(INCFLAGS) $(INC_OPTS) $(HCFLAGS)
-HSC_OPTS       += $(INCFLAGS) $(INC_OPTS)
-CC_OPTS        += $(INCFLAGS) -optc-O3 $(INC_OPTS)
-
-# If $(way) is set then we define $(way_) and $(_way) from it in the
-# obvious fashion.
-ifeq "$(way)" "p"
-  way_ := $(way)_
-  _way := _$(way)
-endif
-
-#
-# building the profiled way
-#
-ifeq "$(way)" "p"
-PROF_OPTS	= -prof -auto-all -Icbits
-LD_OPTS		+= $(PROF_OPTS)
-HC_OPTS     += $(PROF_OPTS)
-HC_OPTS 	+= -hisuf $(way_)hi -hcsuf $(way_)hc -osuf $(way_)o
-endif
-
-# Distclean files (all files generated by configure)
-DIST_CLEAN_FILES+= $(PKG).conf.m4.in $(PKG).conf.m4 aclocal.m4 config.log \
-  config.status cbits/config.h
-DIST_CLEAN_DIRS+= autom4te.cache
-
-#
-# Library flags
-#
-PKG_OPTS       += -package-name $(PKG)-1.0
-GHCI_LIBRARY    = $(patsubst lib%.a,%.o,$(LIBRARY))
-
-#
-# Compute dependencies
-#
-depend: $(MKDEPENDHS_SRCS) $(C_SRCS)
-	@echo "Rebuilding dependencies... "
-	@$(RM) depend
-	@$(GHC) -M -optdep-f -optdepdepend $(HC_OPTS) $(MKDEPENDHS_SRCS)
-	@for x in $(C_SRCS) ; do \
-	$(GCC) -MM $(INCFLAGS) "$$x" >> $@; \
-	done
-	@echo "done."
-
-#
-#  boot and all targets
-#
-.PHONY: boot all lib
-
-boot :: depend
-
-#
-# Building libraries from $(LIBOBJS)
-#
-
-all :: lib
-lib :: $(LIBRARY)
-
-$(LIBRARY) :: $(LIBOBJS)
-	$(RM) $@
-	$(AR) $(AR_OPTS) $@ $(LIBOBJS)
-	$(RANLIB) $@
-
-lib :: $(GHCI_LIBRARY)
-
-$(GHCI_LIBRARY) : $(LIBOBJS)
-	$(LD_X) -r -o $@ $(STUBOBJS) $(LIBOBJS)
-
-# No need to define .SUFFIXES because we don't use any suffix rules
-# Instead we use gmake's pattern rules exlusively
-
-.SUFFIXES:
-
-# This declaration tells GNU make to delete the target if it has
-# changed and the command which created it exited with a non-zero exit
-# code.
-
-.DELETE_ON_ERROR:
-
-#
-# We anticipate wanting to use multiple ways. Particularly prof.
-#
-
-%.$(way_)o: %.hs
-	$(GHC) $(HC_OPTS) $(PKG_OPTS) -c $< -o $@ -ohi $(basename $@).$(way_)hi
-
-%.$(way_)o : %.lhs
-	$(GHC) $(HC_OPTS) $(PKG_OPTS) -c $< -o $@  -ohi $(basename $@).$(way_)hi
-
-%.$(way_)hi : %.$(way_)o
-	@:
-
-%_hsc.c %_hsc.h %.hs : %.hsc
-	$(HSC2HS) $(HSC_OPTS) $(SYMS) $<
-	@touch $(patsubst %.hsc,%_hsc.c,$<)
-
-%.$(way_)o : %.c
-	@$(RM) $@
-	$(GHC) $(CC_OPTS) -c $< -o $@
-
-# preprocssed files, for haddock docs
-%.raw-hs : %.lhs
-	$(GHC) $(HC_OPTS) -D__HADDOCK__ -E -optP-P $< -o $@
-
-%.raw-hs : %.hs
-	$(GHC) $(HC_OPTS) -D__HADDOCK__ -E -optP-P $< -o $@
-
-
-#
-# Package creation
-#
-
-PKG_PREREQS = $(LIBRARY) $(GHCI_LIBRARY)
-
-# in-tree package.conf
-$(PKG).conf: $(PKG).conf.m4 $(PKG_PREREQS)
-	@if [ ! -f $(PKG).conf ]; then echo [] > $(PKG).conf ; fi
-	@m4 $(PKG).conf.m4 \
-	  | sed 's/"",//g; s/, ""//g' \
-	  | $(GHC_PKG) --force -f $(PKG).conf -u 
-	@$(RM) $(PKG).conf.old
-
-# installable package.conf
-$(PKG).conf.install: $(PKG).conf.m4 $(PKG_PREREQS)
-	@if [ ! -f $(PKG).conf.install ]; then echo [] > $(PKG).conf.install; fi
-	@m4 -D__INSTALLING__ $(PKG).conf.m4 \
-	  | sed 's/"",//g; s/, ""//g' \
-	  | $(GHC_PKG) --force -f $(PKG).conf.install -u 
-	@$(RM) $(PKG).conf.install.old
-
-# (un-)register package.conf (needs usually be done as root
-.PHONY: register unregister user-register user-unregister
-register: $(PKG).conf.m4 $(PKG_PREREQS)
-	@m4 -D__INSTALLING__ $(PKG).conf.m4 \
-	  | sed 's/"",//g; s/, ""//g' \
-	  | $(GHC_PKG) register -
-
-user-register: $(PKG).conf.m4 $(PKG_PREREQS)
-	@m4 -D__INSTALLING__ $(PKG).conf.m4 \
-	  | sed 's/"",//g; s/, ""//g' \
-	  | $(GHC_PKG) --user register -
-
-unregister:
-	$(GHC_PKG) unregister $(PKG)
-
-user-unregister:
-	$(GHC_PKG) --user unregister $(PKG)
-
-EXTRA_CLEANS+= $(PKG).conf.install $(PKG).conf
-
-lib :: $(PKG).conf
-
-
-#
-# Building the haddock docs
-#
-ifneq "$(HADDOCK)" ""
-
-HTML_DIR      = html
-HADDOCK_SRCS += $(HS_SRCS)
-HS_PPS        = $(addsuffix .raw-hs, \
-                        $(filter-out $(basename $(NO_DOCS)), \
-                                $(basename $(HADDOCK_SRCS))))
-
-CLEAN_FILES     += $(HS_PPS) $(EXTRA_HS_PPS)
-CLEAN_DIRS      += $(HTML_DIR)
-
-INSTALL_DATAS  += $(HTML_DIR)
-
-DOC_INDEX  = html/index.html
-
-# circular (excluded) modules first
-
-$(DOC_INDEX): $(HS_PPS)
-	@$(INSTALL_DIR) $(HTML_DIR)
-	cd $(HTML_DIR) && $(HADDOCK) -h -k $(PKG) $(addprefix ../,$(HS_PPS))
-
-.PHONY: doc
-html:
-	mkdir html
-
-doc  :: $(DOC_INDEX)
-# all  :: doc
-endif
-
-
-#
-# cleaning
-#
-.PHONY: clean distclean
-
-clean:
-	$(RM) $(MOSTLY_CLEAN_FILES) $(EXTRA_CLEANS) $(CLEAN_FILES)
-	$(RM) -rf $(CLEAN_DIRS)
-
-distclean :: clean
-	$(RM) $(DIST_CLEAN_FILES) *~ */*~
-	$(RM) -rf $(DIST_CLEAN_DIRS)
-
-#
-# installing
-#
-# For each of these variables that is defined, you
-# get one install rule
-#
-#       INSTALL_PROGS        executable programs in $(bindir)
-#       INSTALL_LIBS         platform-dependent libraries in $(libdir) (ranlib'ed)
-#       INSTALL_DATAS        platform-independent files in $(datadir)
-#       INSTALL_IFACES       platform-dependent interface files in $(ifacedir)
-#
-
-.PHONY: install show-install
-
-INSTALL_IFACES += $(HS_IFACES)
-INSTALL_LIBS   += $(LIBRARY) $(GHCI_LIBRARY)
-
-show-install :
-	@echo "BINDIR  = $(BINDIR)"
-	@echo "LIBDIR  = $(LIBDIR)"
-	@echo "DATADIR = $(DATADIR)"
-	@echo "INCDIR  = $(INCDIR)"
-
-install :: all
-
-# the sed is to strip any trailing '_' from the inplace bin names.
-ifneq "$(INSTALL_PROGS)" ""
-install :: $(INSTALL_PROGS)
-	@$(INSTALL_DIR) $(BINDIR)
-	@for i in $(INSTALL_PROGS); do \
-        j=`echo $$i | sed 's/_$$//'` ;\
-		echo $(INSTALL_PROGRAM) $(INSTALL_BIN_OPTS) $$i $(BINDIR)/$$j ;\
-		$(INSTALL_PROGRAM) $(INSTALL_BIN_OPTS) $$i $(BINDIR)/$$j ;\
-	done
-endif
-
-ifneq "$(INSTALL_LIBS)" ""
-install :: $(INSTALL_LIBS)
-	@$(INSTALL_DIR) $(LIBDIR)
-	@for i in $(INSTALL_LIBS); do \
-		echo $(INSTALL_DATA) $(INSTALL_OPTS) $$i $(LIBDIR) ;\
-		$(INSTALL_DATA) $(INSTALL_OPTS) $$i $(LIBDIR) ;\
-	done
-endif
-
-ifneq "$(INSTALL_DATAS)" ""
-install :: $(INSTALL_DATAS)
-	@$(INSTALL_DIR) $(DATADIR)
-	@for i in $(INSTALL_DATAS); do \
-		if [ -d $$i ] ; then \
-			echo $(CP) -r $$i $(DATADIR)/ ;\
-			$(CP) -r $$i $(DATADIR)/ ;\
-		else \
-			echo $(INSTALL_DATA) $(INSTALL_OPTS) $$i $(DATADIR)/ ;\
-			$(INSTALL_DATA) $(INSTALL_OPTS) $$i $(DATADIR)/ ;\
-		fi ;\
-	done
-endif
-
-ifneq "$(INSTALL_IFACES)" ""
-install :: $(INSTALL_IFACES)
-	@$(INSTALL_DIR) $(IFACEDIR)
-	@for i in $(INSTALL_IFACES); do \
-	    $(INSTALL_DIR) $(IFACEDIR)/`dirname $$i` ;\
-		echo $(INSTALL_DATA) $(INSTALL_OPTS) $$i $(IFACEDIR)/`dirname $$i`/ ; \
-		$(INSTALL_DATA) $(INSTALL_OPTS) $$i $(IFACEDIR)/`dirname $$i`/ ; \
-	done
-endif
-
-ifneq "$(INSTALL_HEADERS)" ""
-install :: $(INSTALL_HEADERS)
-	@$(INSTALL_DIR) $(INCDIR)
-	@for i in $(INSTALL_HEADERS); do \
-		echo $(INSTALL_DATA) $(INSTALL_OPTS) $$i $(INCDIR) ; \
-		$(INSTALL_DATA) $(INSTALL_OPTS) $$i $(INCDIR) ; \
-	done
-endif
-
-install :: $(PKG).conf.install
-	@$(INSTALL_DIR) $(LIBDIR)
-	$(INSTALL_DATA) $(INSTALL_OPTS) $< $(LIBDIR)/$(PKG).conf
-
