//! Sounds file audio type.

use crate::durandal::{bin::usize_from_u32, err::*, sound::Sound16};

/// Reads a sound.
pub fn read(b: &[u8]) -> ResultS<Sound16>
{
   read_data! {
      endian: BIG, buf: b, size: 21, start: 0, data {
         let len    = u32[4] usize;
         let rate   = u16[8];
         let lp_beg = u32[12] usize;
         let lp_end = u32[16] usize;
         let magic  = u8[20];
      }
   }

   match magic {
      0 => {
         let stream = &b[22..22 + len];
         Ok(Sound16::new_from_8(rate, lp_beg, lp_end, stream))
      }
      0xFF => {
         read_data! {
            endian: BIG, buf: b, size: 42, start: 22, data {
               let len = u32[0] usize;
               let bps = u16[26];
            }
         }

         match bps {
            16 => {
               let stream = &b[63..63 + len * 2];
               Ok(Sound16::new_from_16(rate, lp_beg, lp_end, stream))
            }
            8 => {
               let stream = &b[63..63 + len];
               Ok(Sound16::new_from_8(rate, lp_beg, lp_end, stream))
            }
            _ => bail!("bad bits per sample"),
         }
      }
      _ => bail!("invalid magic number"),
   }
}

// EOF
