//! TARGA format images.

use crate::{err::*, image::*};
use std::io;

/// Writes a TGA file from an image.
///
/// # Errors
///
/// Errors if `out` cannot be written to.
pub fn write_tga(out: &mut impl io::Write, im: &impl Image) -> ResultS<()>
{
	// id len, color map type, image type
	out.write_all(&[0, 0, 2])?;
	// color map spec
	out.write_all(&[0, 0, 0, 0, 0])?;
	// x origin
	out.write_all(&[0, 0])?;
	// y origin
	out.write_all(&[0, 0])?;
	// width
	out.write_all(&u16::to_le_bytes(im.w() as u16))?;
	// height
	out.write_all(&u16::to_le_bytes(im.h() as u16))?;
	// depth, descriptor
	out.write_all(&[32, 0])?;

	for y in (0..im.h()).rev() {
		for x in 0..im.w() {
			let cr = im.index(x, y);
			out.write_all(&[(cr.b() >> 8) as u8,
			                (cr.g() >> 8) as u8,
			                (cr.r() >> 8) as u8,
			                (cr.a() >> 8) as u8])?;
		}
	}

	Ok(())
}

// EOF
