use std::fs::File;
use std::io::{BufRead, BufReader};

fn traverse(xslope: usize, yslope: usize, data: &Vec<Vec<bool>>) -> i64 {
    let mut x = 0;
    let mut y = 0;
    let mut count = 0;

    loop {
        y += yslope;
        x += xslope;
        let row = data.get(y).unwrap();
        if x >= row.len() {
            x = x % row.len();
        }
        if row[x] {
            count += 1;
        }
        if y == data.len() - 1 {
            return count;
        }
    }
}

fn main() -> anyhow::Result<()> {
    let file = File::open("3.input")?;
    let reader = BufReader::new(file);

    let mut data: Vec<Vec<bool>> = Vec::new();

    for line in reader.lines() {
        data.push(Vec::new());
        let current_line = data.last_mut().unwrap();
        for c in line?.chars() {
            match c {
                '#' => current_line.push(true),
                '.' => current_line.push(false),
                '\n' => (),
                _ => panic!("unexpected input"),
            }
        }
    }

    println!("Count is {}", traverse(3, 1, &data));
    let second = traverse(1, 1, &data) * 
        traverse(3, 1, &data) * 
        traverse(5, 1, &data) * 
        traverse(7, 1, &data) * 
        traverse(1, 2, &data);
    println!("Second count is {}", second);

    Ok(())
}
