module Sound.MED.Basic.Amiga (
  Peek, Reader(..), peekPTR,
  StorableReader, runStorable,
  ByteStringReader, runByteString,
  PTR, LONG, ULONG, WORD, UWORD, BYTE, UBYTE,
  loadMEM, freeMEM,
  ) where

import Sound.MED.Basic.AmigaPrivate

import Sound.MED.Basic.Storable (MEM)
import Sound.MED.Basic.Utility (PTR, LONG, ULONG, WORD, UWORD, BYTE, UBYTE)

import qualified System.IO as IO

import qualified Foreign.Marshal.Alloc as Alloc

import Control.Monad (when)
import Control.Applicative ((<$>))


loadMEM :: String -> IO MEM
loadMEM :: String -> IO MEM
loadMEM String
s =
  String -> IOMode -> (Handle -> IO MEM) -> IO MEM
forall r. String -> IOMode -> (Handle -> IO r) -> IO r
IO.withBinaryFile String
s IOMode
IO.ReadMode ((Handle -> IO MEM) -> IO MEM) -> (Handle -> IO MEM) -> IO MEM
forall a b. (a -> b) -> a -> b
$ \Handle
h -> do
    Int
size <- Integer -> Int
forall a. Num a => Integer -> a
fromInteger (Integer -> Int) -> IO Integer -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Handle -> IO Integer
IO.hFileSize Handle
h
    MEM
ptr <- Int -> IO MEM
forall a. Int -> IO (Ptr a)
Alloc.mallocBytes Int
size
    Int
readSize <- Handle -> MEM -> Int -> IO Int
forall a. Handle -> Ptr a -> Int -> IO Int
IO.hGetBuf Handle
h MEM
ptr Int
size
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
readSizeInt -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<Int
size) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"loadMEM: incomplete load of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s
    MEM -> IO MEM
forall (m :: * -> *) a. Monad m => a -> m a
return MEM
ptr

freeMEM :: MEM -> IO ()
freeMEM :: MEM -> IO ()
freeMEM = MEM -> IO ()
forall a. Ptr a -> IO ()
Alloc.free