//! Marathon Sounds format handling.

pub mod defs;
pub mod snds;

use crate::durandal::{bin::Ident, err::*};
use std::collections::BTreeMap;

/// Reads all sounds from a Sound file.
pub fn read(b: &[u8]) -> ResultS<Vec<SoundTable>>
{
   read_data! {
      endian: BIG, buf: b, size: 260, start: 0, data {
         let version = u32[0];
         let magic   = Ident[4];
         let src_num = u16[8] usize;
         let snd_num = u16[10] usize;
      }
   }

   if version != 1 || magic != b"snd2" {
      bail!("bad sound header");
   }

   let mut sc = Vec::with_capacity(src_num);
   let mut p  = 260;

   for _ in 0..src_num {
      let mut st = SoundTable::new();

      for _ in 0..snd_num {
         if let Some((ofs, idx, mut def)) = defs::read(&b[p..p + 64])? {
            for &ofs in &ofs {
               def.sounds.push(snds::read(&b[ofs..])?);
            }

            st.insert(idx, def);
         }

         p += 64;
      }

      sc.push(st);
   }

   Ok(sc)
}

/// A table of sound definitions.
pub type SoundTable = BTreeMap<u16, defs::SoundDef>;

// EOF
