use std::{path::PathBuf, process, fs::File, io::Write};
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(author)]
struct PixTerm {
#[structopt()]
file: PathBuf,
#[structopt(short = "W", long, default_value = "32")]
width: u16,
#[structopt(short = "H", long, default_value = "32")]
height: u16,
#[structopt(short, long, default_value = "50")]
threshold: u8,
#[structopt(short, long)]
outfile: Option<PathBuf>,
#[structopt(short, long)]
raw: bool,
#[structopt(short, long)]
silent: bool,
}
fn run(pixterm: PixTerm) {
let img = ansipix::of_image(
pixterm.file.clone(),
(pixterm.width as usize, pixterm.height as usize),
pixterm.threshold,
pixterm.raw
).unwrap_or_else(|_| {
eprintln!(
"\x1b[1;31m{}\x1b[22m could not be opened as an image. Does it exist? Is it an image?\x1b[0m",
pixterm.file.to_str().unwrap_or("The specified file")
);
process::exit(1);
});
if !pixterm.silent {
println!("{}", img);
}
if pixterm.outfile.is_some() {
let outfile = pixterm.outfile.unwrap();
if outfile.exists() {
eprintln!("\x1b[1;31m{}\x1b[22m already exists.\x1b[0m", outfile.to_str().unwrap_or("The specified output file"));
process::exit(2);
}
let mut file = File::create(outfile).unwrap_or_else(|e| {
eprintln!("\x1b[1;31mError while creating the file:\x1b[22m {}", e);
process::exit(3);
});
file.write_all(img.as_bytes()).unwrap_or_else(|e| {
eprintln!("\x1b[1;31mError while writing to the file:\x1b[22m {}", e);
process::exit(4);
});
}
}
fn main() {
let pixterm = PixTerm::from_args();
run(pixterm);
}