med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! beat detector settings (`conf_beatdetectorsetting.properties`).

use std::path::Path;

use crate::error::{Med64Error, Result};
use crate::toolkit::beat::BeatOptions;

#[derive(Debug, Clone)]
pub struct BeatPrefs {
    pub checksmoothing: bool,
    pub combohpf: String,
    pub combolpf: String,
    /// Last path; wire key `textfile1=` in .properties.
    pub last_path: String,
    /// Optional smoothing toggle mirrored onto [`BeatOptions::smoothing`].
    pub smoothing: bool,
}

impl Default for BeatPrefs {
    fn default() -> Self {
        Self {
            checksmoothing: false,
            combohpf: "None".into(),
            combolpf: "None".into(),
            last_path: String::new(),
            smoothing: false,
        }
    }
}

impl BeatPrefs {
    pub fn apply_to(&self, options: &mut BeatOptions) {
        options.smoothing = self.smoothing || self.checksmoothing;
        // Beat detection uses thresholds; HPF/LPF names are stored for roundtrip only.
        let _ = (&self.combohpf, &self.combolpf);
    }
}

pub fn load_beat_prefs(path: impl AsRef<Path>) -> Result<BeatPrefs> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path)
        .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    let mut prefs = BeatPrefs::default();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        let k = k.trim();
        let v = v.trim();
        match k {
            "checksmoothing" => {
                prefs.checksmoothing = parse_bool(v);
                prefs.smoothing = prefs.checksmoothing;
            }
            "combohpf" => prefs.combohpf = v.to_string(),
            "combolpf" => prefs.combolpf = v.to_string(),
            // Wire key in beat detector .properties files.
            "textfile1" => prefs.last_path = v.to_string(),
            _ => {}
        }
    }
    Ok(prefs)
}

pub fn write_beat_prefs(prefs: &BeatPrefs, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "# med64 beat detector prefs\n\
         checksmoothing={}\n\
         combohpf={}\n\
         combolpf={}\n\
         textfile1={}\n", // wire key
        if prefs.checksmoothing || prefs.smoothing { "1" } else { "0" },
        prefs.combohpf,
        prefs.combolpf,
        prefs.last_path,
    );
    std::fs::write(path, body)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

fn parse_bool(v: &str) -> bool {
    matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn beat_prefs_roundtrip() {
        let dir = std::env::temp_dir().join(format!("med64-beatpref-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("conf_beatdetectorsetting.properties");
        let prefs = BeatPrefs {
            checksmoothing: true,
            combohpf: "None".into(),
            combolpf: "None".into(),
            last_path: "/tmp".into(),
            smoothing: true,
        };
        write_beat_prefs(&prefs, &path).unwrap();
        let loaded = load_beat_prefs(&path).unwrap();
        assert!(loaded.checksmoothing);
        assert_eq!(loaded.combohpf, "None");
        let mut opts = BeatOptions::default();
        loaded.apply_to(&mut opts);
        assert!(opts.smoothing);
        let _ = std::fs::remove_dir_all(dir);
    }
}