import java.util.Scanner;
import java.util.Arrays;
/*
Online Java - IDE, Code Editor, Compiler

Online Java is a quick and easy tool that helps you to build, compile, test your programs online.
*/
public class Main
{
       public static void main(String[] args) {
        
        System.out.println("Welcome to Online IDE!! Happy Coding :)");
        
        char[] acceptedNumerals = new char[]{'M','D','C','L','X', 'V','I'};
        //These are all accepted roman numerals
         
        int number; //This is set once end user specifies number numerals in their number to be inputted
     
        boolean noMatch=true;  // this flag is used to check if the numeral entered is a valid one
       
        int j;  //used to increment the character array containing user input of numeral
        int count=0;  // this keeps track number times end user has entered a character. It can be decremented if it fails validation.
        
        //int pos;
        
        Scanner reader=null;
        
        // This is used to ascertain how many digits end user wants
        reader = new Scanner(System.in); // Reading from System.in
        System.out.println("Enter number numerals in the number to be converted to decimal:");
        number=reader.nextInt();
        
        char inputtedNumerals[] = new char[number];   // this creates character array with end user specified size
        int [][] posValues = new int [number][2];  // this is used to keep track of:
        
         // this is 2D array. 'number' simply increments with array index of the roman numeral in character array 
        // the multidimensal aspect at 0 index will store:  index of which numeral i.e  M is 0, D is 1
                             //aspect at 1 index will store:  decimal conversion
        // This will support later analysis.
        
do
{
reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter roman numeral " + (count+1) + " of " + number + ":");   // end user prompted to enter roman numeral
inputtedNumerals[count]=reader.next().charAt(0);
count++;

for (j=0; j<inputtedNumerals.length;j++)  // this will check each item in the inputted area against 7 roman numerals.
                                          // the condition could equally be set to count for better loop efficiency if the 
                                          //number entered is long
{

    for (int k=0; k<acceptedNumerals.length;k++)  // this goes through roman numerals
    {
    
    if (inputtedNumerals[j]==acceptedNumerals[k])  // this checks to see if the roman numerals entered are valid
    {
        
        posValues[count-1][0]=k;         // Variable k keeps a record of index of the roman numeral stored in acceptedNumerals      
        
        // This switch statement now checks 'k'validposition in hierarcy of the 7 numerals.
        //'M','D','C','L','X', 'V','I'
        
        
        // Depending on the roman numeral value, it will also store the decimal conversion into posValues array.
        switch(k)
        {
            case 0:
                posValues[count-1][1]=1000;
                break;
            
            case 1:
                posValues[count-1][1]=500;
                break;
                
            case 2:
                posValues[count-1][1]=100;
                break;
                
            case 3:
                posValues[count-1][1]=50;
                break;
                
            case 4:
                posValues[count-1][1]=10;
                break;
                
            case 5:
                posValues[count-1][1]=5;
                break;
                
            case 6:
                posValues[count-1][1]=1;
                break;
        }
        
        
        noMatch=false;   // This sets flag stating match has been found.
        //k=acceptedNumerals.length-1;
        break;
        
        }
    
}
// This will now give information if the user input is valid for each numeral.
// If found to be incorrect, the count will go back and end user will need to enter it again.

 if (noMatch==true)
    {
       System.out.println("Please input a successful roman numeral:  M  D  C  L  X  V  I");
       count=count-1;
       break;
    }
    
}

} while (count<inputtedNumerals.length);  // do while loop will end once count reaches the input user for length of roman numerals.


String str = String.valueOf(inputtedNumerals);
System.out.println("This will be converted to decimal:" + str);  // This informs end user of the roman numerals to be converted

performConversion pc = new performConversion(acceptedNumerals, inputtedNumerals,posValues,str); // calls constructor in class to perform conversion
}
}

class performConversion
{
    char[] inputtedNumerals;  // this contains numerals entered by end user
    char[] acceptedNumerals;  // this contains array of all accepted numerals
    int [][] posValues; // this keeps track for the  index for numeral and also its conversion into decimal
    int total; 
    int sum;
    int consecutiveOccurrences; 
    String numeralsToString;
    
     // This is the constructor used to call the converter method. 
    public performConversion (char[] aNumerals, char [] inputNumerals, int [][] pValues, String numeralsToString)
    {
        this.acceptedNumerals=aNumerals;
        this.inputtedNumerals=inputNumerals;
        this.posValues=pValues;
        this.numeralsToString=numeralsToString;
        
        converter();
    }
    
    
    public void converter()
    {
        // There will be NO issues in performing conversion of a single roman numeral
        
        if (inputtedNumerals.length==1)    // This functions correctly.
        {
                System.out.println("Conversion is:" + posValues[0][1]);
                System.exit(0);
        }
        
              // ONCE ALL PRINCIPLES ARE UNDERSTOOD FOR A VALID ROMAN NUMERAL, THE CODE WILL BE IMPLEMENTED FURTHER     
            
            if (inputtedNumerals.length==2)  // checking number with 2 numerals
        {
            if (posValues[0][0]==posValues[1][0])  // if values identical straight forward conversion
            {
                
            System.out.println("Conversion is:" + (posValues[0][1] + posValues[1][1]));
            System.exit(0);
            }
           
        }
       
        
        System.out.println("numerals in the roman numeral:" + posValues.length);
        
        int valueConsecutiveOccurences[] = new int [posValues.length];
        
        // These values can only occur once in roman numeral. A counter is kept.
        int countV=0;   
        int countL=0;
        int countD=0;
        
        int zeroIndexCount=0;
        
        int singleSubtractiveNotation=0;
        
        // used for rule 4
         //Rule 4: Only I, X, and C can be used as subtractive numerals. 
            //There can be 6 combinations when we subtract. 
            //These are IV = 5 - 1 = 4; IX = 10 - 1 = 9; XL = 50 - 10 = 40; 
            // XC = 100 - 10 = 90; CD = 500 - 100 = 400; and CM = 1000 - 100 = 900
            
            //Another useful IMPORTANT information found on a site is that two subtractive numerals can not be adjacent such as:
            // CDCM since CM is higher however   CM CD is also invalid (range is 100-900)
            
            // The following is invalid:   IXIV even though IV is smaller than IX. This is because they are both in same range 1-9
            // In that respect,   XC XL is invalid..  both notations are  10-90
            // XCIV is ok
            
            //{'M','D','C','L','X', 'V','I'};
            
            // I have partially implemented the rule here since it is too complex.
        
        String IV =  "IV";
        String IX =  "IX";
        String XL =  "XL";
        String XC =  "XC";
        String CD=   "CD"; 
        String CM=   "CM";
        String [] subtractiveNumerals =  new String []{IV,IX,XL,XC,CD,CM};
        
        int sum1=0;
        int total1=0;
        boolean flagError=false;
        
        boolean result=false;
        int total2=0;
        
        int overallTotal=0;
        boolean twoSubtractiveNotations=false;
        
        
        //-----------------------------------------
        
        // This has been completed outside main loop because it is processing a string to check values
        
        System.out.println("In rule 4");
        for (int i=0; i<subtractiveNumerals.length; i++)   // this is going through all 6 combos IV, IX, XL.....
        {
            for (int j=0; j<subtractiveNumerals.length; j++ )   // this is going through all 6 combos IV, IX, XL.....
            {
                // NEED MORE LOGIC TO PREVENT IT FROM COMPARING AGAINST ITSELF.
                // OTHERWISE IT WILL PREVENT SINGLE OCCURENCE OF SUBTRACTIVE NOTATION FROM BEING PROCESSED
                
                if (j==i)
                {
                    continue;
                }
                
                // this ensures that there are matches of both in inputted numeral before processing
                if (numeralsToString.indexOf(subtractiveNumerals[i])!=-1 &&  numeralsToString.indexOf(subtractiveNumerals[j])!=-1) 
                {
                     twoSubtractiveNotations = true;
                    
                    
                    // this checks if subtractive notation lower value appears at index before higher subtractive notation
                    if (numeralsToString.indexOf(subtractiveNumerals[i]) < numeralsToString.indexOf(subtractiveNumerals[j]))
                    
                    {
                        System.out.println("Incorrect roman numeral. " +  subtractiveNumerals[i] + " should be after: " + subtractiveNumerals[j]);
                    }
                }
                
                // this now checks the subtractive notations in correct order
                
                if (numeralsToString.indexOf(subtractiveNumerals[i]) > numeralsToString.indexOf(subtractiveNumerals[j]))
                {
                    if (numeralsToString.indexOf(subtractiveNumerals[i])!=-1 &&  numeralsToString.indexOf(subtractiveNumerals[j])!=-1)
                    {
                        System.out.println("correct order");
                        
                       
                        
                         switch (subtractiveNumerals[i])
                        {
                            case "IV":
                                total2 = total2 + 4;
                                break;
                                
                            case "IX":
                                total2 = total2 + 9;
                                break;
                                
                            case "XL":
                                total2 = total2 + 40;
                                break;
                                
                            case "XC":
                                total2 = total2 + 90;
                                break;
                                
                            case "CD":
                                total2 = total2 + 400;
                                break;
                                
                            case "CM":
                                total2 = total2 + 900;
                                break;
                        }
                        
                        switch (subtractiveNumerals[j])
                        {
                            case "IV":
                                total2 = total2 + 4;
                                break;
                                
                            case "IX":
                                total2 = total2 + 9;
                                break;
                                
                            case "XL":
                                total2 = total2 + 40;
                                break;
                                
                            case "XC":
                                total2 = total2 + 90;
                                break;
                                
                            case "CD":
                                total2 = total2 + 400;
                                break;
                                
                            case "CM":
                                total2 = total2 + 900;
                                break;
                        }
                        
                    }
                    
                }
                
              
            }
            
            System.out.println("total after rule4:" + total2);
            // this confirms if a match is found.  -1 value is no match. 0 is a match.
            System.out.println(subtractiveNumerals[i] + "   " + numeralsToString.indexOf(subtractiveNumerals[i]));
            
            // this now is just simply going through all subtractive notations if there is no other existing in the CharSequence
            // this can not run if the above circumstance is true.
            
            if (!twoSubtractiveNotations)
            {
                if (numeralsToString.indexOf(subtractiveNumerals[i])!=-1)
                {
                        switch (subtractiveNumerals[i])
                        {
                            case "IV":
                                singleSubtractiveNotation = singleSubtractiveNotation + 4;
                                break;
                                
                            case "IX":
                                singleSubtractiveNotation = singleSubtractiveNotation + 9;
                                break;
                                
                            case "XL":
                                singleSubtractiveNotation = singleSubtractiveNotation + 40;
                                break;
                                
                            case "XC":
                                singleSubtractiveNotation = singleSubtractiveNotation + 90;
                                break;
                                
                            case "CD":
                                singleSubtractiveNotation = singleSubtractiveNotation + 400;
                                break;
                                
                            case "CM":
                                singleSubtractiveNotation = singleSubtractiveNotation + 900;
                                break;
                        }
                        
                        System.out.println("This should now print out instances like IX" + singleSubtractiveNotation);
                        twoSubtractiveNotations=true;
                        
            }
            }
            
        }
        //----------------------------------------------------------------
            
        //}
    //}
        
        //this will examine decimal number stored. If identical numerals in consecutive it will add to the total.
        
        for (int m=1; m<posValues.length; m++)  // this is starting not at zero index since compared to previous value
        {
            
             //posValues[m][0]=numeral position     //[m][1]=decimal
            // This section is best completed examining string of the character array of inputted numerals.
            
            // Rule 3: The letters V, L, and D are not repeated.
            // There are acceptedNumerals[1], acceptedNumerals[3], acceptedNumerals[5]
            // posValues[m][0] stores information relevant
            
            //{'M','D','C','L','X', 'V','I'};
            
            System.out.println("Going into rule 3");
            if (posValues[zeroIndexCount][0]==5)
            {
                countV++;
                System.out.println("found a V");
            }
            
            if (posValues[zeroIndexCount][0]==3)
            {
                countL++;
            }
            
            if (posValues[zeroIndexCount][0]==1)
            {
                countD++;
            }
                //Rule 1: When certain numerals are repeated, the number represented by them is their sum. For example, II = 1 + 1 = 2, or XX = 10 + 10 = 20, or, XXX = 10 + 10 + 10 = 30.
                
                if (posValues[m][1]==posValues[m-1][1])   // this is comparing decimal number for numeral against previous one
                {
                    
                 // Rule 2: It is to be noted that no Roman numerals can come together more than 3 times. For example, we cannot write 40 as XXXX
                 System.out.println("starting rule 1");
                 //if (m!=(posValues.length-2) && posValues.length>3)   // what does this rule mean, first part
                 
                 if (posValues.length>2)
                 
                 
                 // m is current position in the numerals array
                 
                    {
                        
                    if (m!=posValues.length)
                    {
                    
                    // UNKNOWN ERROR
                    
                    System.out.println("start of rule2");
                    
                    if (m+2<posValues.length)
                    {
                    
                    if (posValues[m-1][1]==posValues[m][1] && posValues[m][1]==posValues[m+1][1] && posValues[m][1]==posValues[m+2][1])
                    {
                        System.out.println("There are more than three consecutive same characters: " + acceptedNumerals[posValues[m][0]]);
                        System.out.println("This is invalid roman numeral");
                        System.exit(0);
                    }
                    }
                    
                    }
                }
                    
                    total=posValues[m][1]+posValues[m-1][1];  
                    sum=sum+total;    // they will be totalled if same
                    System.out.println("So far sum:" + sum);
                    
                    valueConsecutiveOccurences[m] = posValues[m][1];  //storing decimal value in array.
                    
                    consecutiveOccurrences=consecutiveOccurrences+2;
                    
                    // valueConsecutiveOccurences[m] this keeps a track of the roman numeral that has been repeating
                    //num++;
                   
                    // this checks if there has already been consecutive occurence of the numeral adjacently
                    //[m][0]=numeral position     //[m][1]=decimal
                    
                    
                    if (m!=(posValues.length-1))
                    {
                                            
                    if (valueConsecutiveOccurences[m]==posValues[m+1][1])
                    {
                        
                        System.out.println("does this happen");
                        sum=sum-(total/2);
                        //System.out.println("sum so far: " + sum);
                        total=0;
                    }
                }
                
                }
                
                
                //Rule 5: When a Roman numeral is placed after another Roman numeral of greater value, 
                //the result is the sum of the numerals. For example, VIII = 5 + 1 + 1 + 1 = 8, or, 
                //XV = 10 + 5 = 15,
                // This appears to be where the code has determined if numerals are in some decent order
                
                System.out.println("What is value of zeroindexcount: " + zeroIndexCount);
                
                if (posValues[m][1]<posValues[m-1][1])
                {
                    System.out.println(posValues[m][1]);
                    System.out.println(posValues[m-1][1]);
                    
                    sum1 = posValues[m][1] + posValues[m-1][1];
                    total1 = total1 + sum1;
                    sum1 = 0;
                    
                }
                
               //Rule 6: When a Roman numeral is placed before another Roman numeral of greater value, 
               //the result is the difference between the numerals. For example, IV = 5 - 1 = 4, or, XL = 50 - 10 = 40, 
               //or XC = 100 - 10 = 90
                
                System.out.println("Rule 6");
                if (posValues[zeroIndexCount][1]>posValues[zeroIndexCount+1][1])
                {
                    //System.out.println(posValues[m][1]);
                    //System.out.println(posValues[m-1][1]);
                    sum1 = posValues[m][1] - posValues[m-1][1];
                    total1 = total1 + sum1;
                    sum1 = 0;
                }
                
               // Rule 7: When a Roman numeral of a smaller value is placed between two numerals of greater value, 
               //it is subtracted from the numeral on its right. For example, XIV = 10 + (5 - 1) = 14, 
               //or, XIX = 10 + (10 - 1) = 19
                
                System.out.println("Rule 7");
                
                if (m!=posValues.length && posValues.length>2) // a numeral can not be in middle if it is the last in the numeral array
                // it also can not be in middle if the first numeral. Hence using m index notation.
                
                {
                    
                    //START FROM HERE AND TEST  XI
                    
                if (posValues[m][1]<posValues[m-1][1] && posValues[m][1]<posValues[m+1][1])
                {
                    //System.out.println("what " + (m-1));
                    
                    sum1 = posValues[m+1][1] - posValues[m][1];
                    total1 = total1 + sum1;
                    sum1 = 0;
                }
                }
                zeroIndexCount++;
                
                System.out.println("This is overall total:" + (total1));
        }
        
            // this is part of rule 3
            
            if (countD>1 || countL>1 || countV>1)
            {
                System.out.println("Invalid roman numeral. Numeral V or D or L has occured more than once");
                System.out.println("This is overall total:" + 0);
                //break;
            }
        
        //System.out.println("this is the sum: " + sum);
        
        
        // This is the best logic found on the internet for roman numeral conversion.
        // Logic will be coded one by one and see if it works overall
        
    /*
    
    It is necessary for us to remember the rules for reading and writing Roman numbers in order to avoid mistakes. Here is a list of the basic rules for Roman numerals.

    Rule 1: When certain numerals are repeated, the number represented by them is their sum. For example, II = 1 + 1 = 2, or XX = 10 + 10 = 20, or, XXX = 10 + 10 + 10 = 30.
    Rule 2: It is to be noted that no Roman numerals can come together more than 3 times. For example, we cannot write 40 as XXXX
    Rule 3: The letters V, L, and D are not repeated.
    Rule 4: Only I, X, and C can be used as subtractive numerals. There can be 6 combinations when we subtract. These are IV = 5 - 1 = 4; IX = 10 - 1 = 9; XL = 50 - 10 = 40; XC = 100 - 10 = 90; CD = 500 - 100 = 400; and CM = 1000 - 100 = 900
    Rule 5: When a Roman numeral is placed after another Roman numeral of greater value, the result is the sum of the numerals. For example, VIII = 5 + 1 + 1 + 1 = 8, or, XV = 10 + 5 = 15,
    Rule 6: When a Roman numeral is placed before another Roman numeral of greater value, the result is the difference between the numerals. For example, IV = 5 - 1 = 4, or, XL = 50 - 10 = 40, or XC = 100 - 10 = 90
    Rule 7: When a Roman numeral of a smaller value is placed between two numerals of greater value, it is subtracted from the numeral on its right. For example, XIV = 10 + (5 - 1) = 14, or, XIX = 10 + (10 - 1) = 19
    Rule 8: To multiply a number by a factor of 1000 a bar is placed over it.
    Rule 9: Roman numerals do not follow any place value system.
    Rule 10: There is no Roman numeral for zero (0).

*/
      
        
        
    }
    
   
}
