module Sound.MED.Raw.MMD2Song where

import qualified Sound.MED.Raw.MMD0Sample as MMD0Sample
import Sound.MED.Raw.MMD0Sample(MMD0Sample)
import qualified Sound.MED.Raw.PlaySeq as PlaySeq
import Sound.MED.Raw.PlaySeq(PlaySeq)
import Sound.MED.Basic.Amiga

data MMD2Song = MMD2Song
  { sample        :: [ MMD0Sample ]
  , numblocks     :: UWORD
  , songlen       :: UWORD
  , playseqtable  :: [ PlaySeq ]
  , sectiontable  :: [ UWORD ]
  , trackvols     :: [ UBYTE ]
  , numtracks     :: UWORD
  , numpseqs      :: UWORD
  , trackpans     :: [ BYTE ]
  , flags3        :: ULONG
  , voladj        :: UWORD
  , channels      :: UWORD
  , mix_echotype  :: UBYTE
  , mix_echodepth :: UBYTE
  , mix_echolen   :: UWORD
  , mix_stereosep :: BYTE
  , pad0          :: [ UBYTE ]
  , deftempo      :: UWORD
  , playtransp    :: BYTE
  , flags         :: UBYTE
  , flags2        :: UBYTE
  , tempo2        :: UBYTE
  , pad1          :: [ UBYTE ]
  , mastervol     :: UBYTE
  , numsamples    :: UBYTE
  }
  deriving (Show)

peek :: MEM -> PTR -> IO MMD2Song
peek m p = do
  sample'         <- mapM (MMD0Sample.peek m) $ pointerRange p 8 63
  numblocks'      <- peekUWORD m (p+504)
  songlen'        <- peekUWORD m (p+506)
  numpseqs'       <- peekUWORD m (p+522)
  playseqtable''' <- peekPTR   m (p+508)
  playseqtable''  <- mapM (peekPTR m) $ pointerRangeGen playseqtable''' 4 numpseqs'
  playseqtable'   <- mapM (PlaySeq.peek m) playseqtable''
  sectiontable''  <- peekPTR   m (p+512)
  sectiontable'   <- mapM (peekUWORD m) $ pointerRangeGen sectiontable'' 2 songlen'
  numtracks'      <- peekUWORD m (p+520)
  trackvols''     <- peekPTR   m (p+516)
  trackvols'      <- mapM (peekUBYTE m) $ pointerRangeGen trackvols'' 1 numtracks'
  trackpans''     <- peekPTR   m (p+524)
  trackpans'      <- if trackpans'' == 0 then return $ replicate (fromIntegral numtracks') 0 else mapM (peekBYTE m) $ pointerRangeGen trackpans'' 1 numtracks'
  flags3'         <- peekULONG m (p+528)
  voladj'         <- peekUWORD m (p+532)
  channels'       <- peekUWORD m (p+534)
  mix_echotype'   <- peekUBYTE m (p+536)
  mix_echodepth'  <- peekUBYTE m (p+537)
  mix_echolen'    <- peekUWORD m (p+538)
  mix_stereosep'  <- peekBYTE  m (p+540)
  pad0'           <- mapM (peekUBYTE m) $ pointerRange (p+541) 1 223
  deftempo'       <- peekUWORD m (p+764)
  playtransp'     <- peekBYTE  m (p+766)
  flags'          <- peekUBYTE m (p+767)
  flags2'         <- peekUBYTE m (p+768)
  tempo2'         <- peekUBYTE m (p+769)
  pad1'           <- mapM (peekUBYTE m) $ pointerRange (p+770) 1 16
  mastervol'      <- peekUBYTE m (p+786)
  numsamples'     <- peekUBYTE m (p+787)
  return $ MMD2Song
    sample' numblocks' songlen' playseqtable' sectiontable' trackvols'
    numtracks' numpseqs' trackpans' flags3' voladj' channels'
    mix_echotype' mix_echodepth' mix_echolen' mix_stereosep' pad0'
    deftempo' playtransp' flags' flags2' tempo2' pad1' mastervol'
    numsamples'