extern crate um;
use um::cpu::{Cpu};
use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec; 
use clap::Parser;

/// Run a um program
#[derive(Parser)]
struct Cli {
    /// The path to the program to load
    program: std::path::PathBuf,
}


fn main() -> io::Result<()> {
  let args = Cli::parse();
  
  let mut pgm = Vec::new(); 
  
  let mut f = File::open(args.program)?;
  let mut cont = true;
  while cont {
    let mut buffer = [0u8; 4];
    cont = match f.read(&mut buffer) {
        Ok(4) => {
          let num = u32::from_be_bytes(
        buffer.try_into().unwrap());
          pgm.push(num);
          true
        },
        Ok(_) => false, 
        Err(_) => false,
    };
  }
  
  let mut c = Cpu::new(pgm);
  cont = true;
  println!("start\n{}", c.state());
  while cont {
    let r = c.step();
    cont = match r {
      Ok(_) => {
        println!("ok\n{}", c.state());
        true
      },
      Err(e) => {
        println!("Error {:?}", e);
        false
      }
    };
  }
  Ok(())
  
}