From d278d50528c13b6ab1dbe9e1da688e835e4ca99d Mon Sep 17 00:00:00 2001
From: Gwilym Inzani <gw@ilym.me>
Date: Thu, 6 Apr 2023 23:13:42 +0100
Subject: [PATCH] Extract function

---
 agb-gbafix/src/main.rs | 21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)

diff --git a/agb-gbafix/src/main.rs b/agb-gbafix/src/main.rs
index de7e9fb1..263a8011 100644
--- a/agb-gbafix/src/main.rs
+++ b/agb-gbafix/src/main.rs
@@ -1,22 +1,29 @@
 use std::{
-    fs,
+    error, fs,
     io::{BufWriter, Write},
     path::PathBuf,
 };
 
-fn main() -> Result<(), Box<dyn std::error::Error>> {
+fn main() -> Result<(), Box<dyn error::Error>> {
+    let mut output = BufWriter::new(fs::File::create("out.gba")?);
+
     let path = PathBuf::from("tests/text_render");
     let file_data = fs::read(path)?;
-    let file_data = file_data.as_slice();
 
-    let elf_file = elf::ElfBytes::<elf::endian::AnyEndian>::minimal_parse(file_data)?;
+    write_gba_file(file_data.as_slice(), &mut output)?;
+
+    output.flush()?;
+
+    Ok(())
+}
+
+fn write_gba_file<W: Write>(input: &[u8], output: &mut W) -> Result<(), Box<dyn error::Error>> {
+    let elf_file = elf::ElfBytes::<elf::endian::AnyEndian>::minimal_parse(input)?;
 
     let section_headers = elf_file
         .section_headers()
         .expect("Expected section headers");
 
-    let mut output = BufWriter::new(fs::File::create("out.gba")?);
-
     let mut header = gbafix::GBAHeader::default();
 
     const GBA_START_ADDRESS: u64 = 0x8000000;
@@ -64,7 +71,5 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
         address += data.len() as u64;
     }
 
-    output.flush()?;
-
     Ok(())
 }