{- |
Taken from Haskore.
-}
module Sound.MIDI.IO
          (openBinaryFile, readBinaryFile, writeBinaryFile,
           ByteList, listCharFromByte, listByteFromChar)
   where

import System.IO
import Control.Exception(bracket)
import Control.Monad(liftM)
import Data.Char (ord, chr)
import Data.Word (Word8)

type ByteList = [Word8]

{- |
Hugs makes trouble here because it performs UTF-8 conversions.
E.g. @[255]@ is output as @[195,191]@
It would be easy to replace these routines by FastPackedString(fps).ByteList.Lazy,
however this introduces a new package dependency.
-}
writeBinaryFile :: FilePath -> ByteList -> IO ()
writeBinaryFile :: FilePath -> ByteList -> IO ()
writeBinaryFile FilePath
path ByteList
str =
   forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (FilePath -> IOMode -> IO Handle
openBinaryFile FilePath
path IOMode
WriteMode) Handle -> IO ()
hClose
           (forall a b c. (a -> b -> c) -> b -> a -> c
flip Handle -> FilePath -> IO ()
hPutStr (ByteList -> FilePath
listCharFromByte ByteList
str))

listCharFromByte :: ByteList -> String
listCharFromByte :: ByteList -> FilePath
listCharFromByte = forall a b. (a -> b) -> [a] -> [b]
map (Int -> Char
chr forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (Integral a, Num b) => a -> b
fromIntegral)

readBinaryFile :: FilePath -> IO ByteList
readBinaryFile :: FilePath -> IO ByteList
readBinaryFile FilePath
path =
   forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM FilePath -> ByteList
listByteFromChar forall b c a. (b -> c) -> (a -> b) -> a -> c
.
      Handle -> IO FilePath
hGetContents forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< FilePath -> IOMode -> IO Handle
openBinaryFile FilePath
path IOMode
ReadMode

listByteFromChar :: String -> ByteList
listByteFromChar :: FilePath -> ByteList
listByteFromChar = forall a b. (a -> b) -> [a] -> [b]
map (forall a b. (Integral a, Num b) => a -> b
fromIntegral forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Int
ord)