Skip to main content

celestial_pointing/commands/
inmod.rs

1use super::{Command, CommandOutput};
2use crate::error::{Error, Result};
3use crate::session::Session;
4
5pub struct Inmod;
6
7impl Command for Inmod {
8    fn name(&self) -> &str {
9        "INMOD"
10    }
11    fn description(&self) -> &str {
12        "Load model from file"
13    }
14
15    fn execute(&self, session: &mut Session, args: &[&str]) -> Result<CommandOutput> {
16        if args.is_empty() {
17            return Err(Error::Parse("INMOD requires a filename".into()));
18        }
19        let content = std::fs::read_to_string(args[0]).map_err(Error::Io)?;
20
21        session.model.remove_all();
22        session.last_fit = None;
23
24        let mut term_coeffs = Vec::new();
25        for line in content.lines() {
26            let trimmed = line.trim();
27            if trimmed.is_empty() {
28                continue;
29            }
30            if trimmed.eq_ignore_ascii_case("END") {
31                break;
32            }
33            let parts: Vec<&str> = trimmed.split_whitespace().collect();
34            if parts.len() < 2 {
35                return Err(Error::Parse(format!("invalid model line: {}", trimmed)));
36            }
37            let name = parts[0];
38            let coeff: f64 = parts[1]
39                .parse()
40                .map_err(|e| Error::Parse(format!("invalid coefficient: {}", e)))?;
41            session.model.add_term(name)?;
42            term_coeffs.push(coeff);
43        }
44
45        if !term_coeffs.is_empty() {
46            session.model.set_coefficients(&term_coeffs)?;
47        }
48
49        Ok(CommandOutput::Text(format!(
50            "Loaded {} terms from {}",
51            term_coeffs.len(),
52            args[0]
53        )))
54    }
55}