#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && std::isfinite(value)
            && value >= low && value <= high) {
            return true;
        }
        std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid number was supplied.\n";
    return false;
}

bool readInteger(const std::string& prompt, int& value, int low, int high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && value >= low && value <= high) return true;
        std::cout << "Enter a whole number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid integer was supplied.\n";
    return false;
}

struct Wood {
    const char* name;
    double quarterCoefficient;
    double flatCoefficient;
};

int main() {
    // Historical assignment coefficients, per moisture percentage POINT.
    // Their physical calibration is unverified; this is a teaching model.
    const std::array<Wood, 4> woods{{
        {"Alder", 0.0015, 0.0026}, {"Cherry", 0.0013, 0.0025},
        {"Red Oak", 0.0016, 0.0037}, {"Black Walnut", 0.0019, 0.0027}
    }};
    double widthInches = 0.0, moisturePoints = 0.0;
    if (!readNumber("Initial width (inches): ", widthInches, 1e-6, 1e4)
        || !readNumber("Signed moisture change (percentage points): ", moisturePoints, -30.0, 30.0)) return 1;
    for (std::size_t i = 0; i < woods.size(); ++i) std::cout << i + 1 << ". " << woods[i].name << '\n';
    int woodChoice = 0, cutChoice = 0;
    if (!readInteger("Wood (1 to 4; 0 exits): ", woodChoice, 0, 4)) return 1;
    if (woodChoice == 0) return 0;
    if (!readInteger("Cut (1 quarter, 2 flat; 0 exits): ", cutChoice, 0, 2)) return 1;
    if (cutChoice == 0) return 0;
    const Wood& wood = woods.at(static_cast<std::size_t>(woodChoice - 1));
    const double coefficient = cutChoice == 1 ? wood.quarterCoefficient : wood.flatCoefficient;
    const double change = widthInches * moisturePoints * coefficient;
    std::cout << std::fixed << std::setprecision(6)
              << "Teaching model; historical coefficients not independently calibrated.\n"
              << "Width change (in): " << change << '\n'
              << "New width (in): " << widthInches + change << '\n';
}
