use std::fs;
use xmas_elf::ElfFile;

mod error;
mod formats;
mod linker;
mod parts;

use linker::LinkState;
use parts::Relocatable;

fn main() {
    let mut args = std::env::args().peekable();

    // can this miss?
    args.next().unwrap();

    let mut contents: Vec<(String, Vec<u8>)> = Vec::new();
    let mut parsed: Vec<(&str, ElfFile)> = Vec::new();
    let mut linker = LinkState::default();

    while args.peek().is_some() {
        let fpath = args.next().expect("Unexpected peek-a-boo");
        let raw = fs::read(&fpath).expect("Error reading file");
        contents.push((fpath, raw));
    }

    for data in contents.iter() {
        let elf = ElfFile::new(&data.1).expect("Error parsing ELF file");
        parsed.push((&data.0, elf));
    }

    for elf in parsed.iter() {
        let relocatable = Relocatable::from_elf(elf.0, &elf.1).unwrap();
        linker.add_relocatable(relocatable).unwrap();
    }

    println!("{}", linker);
}
