//roman.cpp
// Converts between decimal and Roman numerals

#include <iostream>

using namespace std;

void romanToDecimal();
void decimalToRoman();
int nextRoman(int);
int romanNumeral(char);


int main() {

  char dir;

  do {
    cout << endl;
    cout << "Enter 'r' for roman to decimal, 'd' for decimal to roman, "
	    " 'q' to quit: ";
    cin >> dir;
    if (dir == 'r' || dir == 'R')
      romanToDecimal();
    else if (dir == 'd' || dir == 'D')
      decimalToRoman();
  } while (dir != 'q');
}




//****************************************************
// Read a roman number, display its decimal equivalent

void romanToDecimal () {

  int sum=0;
  char roman;

  cout << "Enter a number in roman numerals: ";
  cin >> roman;
  while (roman != '\n') {       // until end of line
    sum += romanNumeral(roman);
    cin.get(roman);             //input next char, incl. newline
  }
  cout << "Value in decimal is: " << sum << endl;
}

//****************************************************
// Return decimal value of a (single) roman numeral

int romanNumeral (char roman) {

  int value;

  switch (roman) {
  case 'M': value = 1000;  break;
  case 'D': value =  500;  break;
  case 'C': value =  100;  break;
  case 'L': value =   50;  break;
  case 'X': value =   10;  break;
  case 'V': value =    5;  break;
  case 'I': value =    1;  break;
  default: cout << "Error char as roman numeral: " << roman << endl;
	   value = 0;
  }

  return value;
}




//*******************************************************
// Read an integer, display its roman numeral equivalent.

void decimalToRoman () {

  int dec;

  cout << "Enter an integer for conversion to roman numerals: ";
  cin >> dec;

  while (dec > 0)          // loop subtracting largest roman numeral
    dec -= nextRoman(dec);

  cout << endl;
}

//*********************************************************
// Find largest roman numeral in the int argument, displays
// it, returns the int value of it.

int nextRoman (int d) {

  int value;

  if (d >= 1000) {
    cout << 'M';
    value = 1000;
  }
  else if (d >= 500) {
    cout << 'D';
    value = 500;
  }
  else if (d >= 100) {
    cout << 'C';
    value = 100;
  }
  else if (d >= 50) {
    cout << 'L';
    value = 50;
  }
  else if (d >= 10) {
    cout << 'X';
    value = 10;
  }
  else if (d >= 5) {
    cout << 'V';
    value = 5;
  }
  else if (d >= 1) {
    cout << 'I';
    value = 1;
  }
  else {
    cout << "Error value invalid: " << d << endl;
    value = 0;
  }

  return value;
}
