module UTF8_IO where
 
import Control.Monad (mapM_)
import Data.Word (Word8)
import Foreign.Marshal.Array (allocaArray, peekArray, pokeArray)
import System.IO (hFileSize, Handle, hGetBuf, hPutBuf, openBinaryFile, hClose,
                  IOMode(ReadMode, WriteMode))

-- wget http://abridgegame.org/repos/darcs/UTF8.lhs 
import UTF8

readFileUnicode :: FilePath -> IO String
readFileUnicode f = do
     fb <- readFileBytes f
     case decode fb of
       (cs, []) -> return cs
       (_,  xs) -> fail $ show xs

writeFileUnicode :: FilePath -> String -> IO ()
writeFileUnicode f cs = do
    writeFileBytes f (encode cs)

readFileBytes :: FilePath -> IO [Word8]
readFileBytes f =
  do h <- openBinaryFile f ReadMode
     hsize <- fromIntegral `fmap` hFileSize h
     hGetBytes h hsize

writeFileBytes :: FilePath -> [Word8] -> IO ()
writeFileBytes f ws =
 do h <- openBinaryFile f WriteMode
    hPutBytes h (length ws) ws
    hClose h

hGetBytes :: Handle -> Int -> IO [Word8]
hGetBytes h c = allocaArray c $ \p ->
                  do c' <- hGetBuf h p c
                     peekArray c' p

hPutBytes :: Handle -> Int -> [Word8] -> IO ()
hPutBytes h c ws = allocaArray c $ \p ->
                     do pokeArray p ws
                        hPutBuf h p c
