# Name: Tristan Shabbick
# I pledge my honor that I have abided by the Stevens Honor System.


def ImageBuilder(args):
    binaryString = ""

    match args[0]:
        case "add":
            if len(args) != 4:
                raise ValueError("Invalid number of arguments for ADD instruction. Cannot continue.")

            else:
                if not args[3].isdigit():
                    raise ValueError("Invalid immediate number for ADD instruction. Cannot continue.")

                if int(args[3]) > 255 or int(args[3]) < 0:
                    raise ValueError(
                        "Immediate number for ADD instruction is not between 0 and 255 (inclusive)!. Cannot continue.")

                ImmediateNumber = bin(int(args[3]))  # Convert the immediate number to binary
                ImmediateNumberB = ImmediateNumber[2:]  # Remove the 0b from the binary number
                ImmediateNumberB = ImmediateNumberB.zfill(8)  # Pad the binary number with 0s to make it 16 bits long

                binaryString += ImmediateNumberB  # Add the immediate number to the binary string (8 bits)
                binaryString += "00"  # Add 00 because we are not using LDR or STR.
                binaryString += "0"  # Add 0 because the ADD instruction is being used.
                binaryString += "1"  # Add 1 because the instruction needs to write to a register

                ReadRegID = args[2]
                WriteRegID = args[1]

                if not ReadRegID[1].isdigit() or not WriteRegID[1].isdigit():
                    raise ValueError("Read/write register ID for ADD instruction is not a number! Cannot continue.")

                if int(ReadRegID[1]) > 3 or int(ReadRegID[1]) < 0 or int(WriteRegID[1]) > 3 or int(WriteRegID[1]) < 0:
                    raise ValueError(
                        "Read/write register ID for ADD instruction is not between 0 and 3 inclusive! Cannot continue.")


                ReadRegID = bin(int(ReadRegID[1]))  # Convert the write register ID to binary
                WriteRegID = bin(int(WriteRegID[1]))  # Convert the read register ID to binary

                ReadRegIDB = ReadRegID[2:]  # Remove the 0b from the binary number
                WriteRegIDB = WriteRegID[2:]  # Remove the 0b from the binary number

                ReadRegIDB = ReadRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long
                WriteRegIDB = WriteRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long

                binaryString += WriteRegIDB  # Add the write register ID to the binary string (2 bits)
                binaryString += ReadRegIDB  # Add the read register ID to the binary string (2 bits)
                return binaryString

        case "sub":
            if len(args) != 4:
                raise ValueError("Invalid number of arguments for SUB instruction. Cannot continue.")

            else:
                if not args[3].isdigit():
                    raise ValueError("Invalid immediate number for SUB instruction. Cannot continue.")

                if int(args[3]) > 255 or int(args[3]) < 0:
                    raise ValueError(
                        "Immediate number for ADD instruction is not between 0 and 255 inclusive!. Cannot continue.")

                ImmediateNumber = bin(int(args[3]))  # Convert the immediate number to binary
                ImmediateNumberB = ImmediateNumber[2:]  # Remove the 0b from the binary number
                ImmediateNumberB = ImmediateNumberB.zfill(8)  # Pad the binary number with 0s to make it 16 bits long

                binaryString += ImmediateNumberB  # Add the immediate number to the binary string (8 bits)
                binaryString += "00"  # Add 00 because we are not using LDR or STR.
                binaryString += "1"  # Add 1 because the SUB instruction is being used.
                binaryString += "1"  # Add 1 because the instruction needs to write to a register

                ReadRegID = args[2]
                WriteRegID = args[1]

                if not ReadRegID[1].isdigit() or not WriteRegID[1].isdigit():
                    raise ValueError("Read/write register ID for SUB instruction is not a number! Cannot continue.")

                if int(ReadRegID[1]) > 3 or int(ReadRegID[1]) < 0 or int(WriteRegID[1]) > 3 or int(WriteRegID[1]) < 0:
                    raise ValueError("Read/write register ID for SUB instruction is not between 0 and 3 inclusive! Cannot continue.")

                ReadRegID = bin(int(ReadRegID[1]))  # Convert the write register ID to binary
                WriteRegID = bin(int(WriteRegID[1]))  # Convert the read register ID to binary

                ReadRegIDB = ReadRegID[2:]  # Remove the 0b from the binary number
                WriteRegIDB = WriteRegID[2:]  # Remove the 0b from the binary number

                ReadRegIDB = ReadRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long
                WriteRegIDB = WriteRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long

                binaryString += WriteRegIDB  # Add the write register ID to the binary string (2 bits)
                binaryString += ReadRegIDB  # Add the read register ID to the binary string (2 bits)
                return binaryString

        case "str":
            if len(args) != 3:
                raise ValueError("Invalid number of arguments for STR instruction. Cannot continue.")

            else:
                if not args[2].isdigit():
                    raise ValueError("Invalid immediate number for STR instruction. Cannot continue.")

                if int(args[2]) > 255 or int(args[2]) < 0:
                    raise ValueError(
                        "Immediate number for STR instruction is not between 0 and 255 inclusive!. Cannot continue.")


                ImmediateNumber = bin(int(args[2]))  # Convert the immediate number to binary
                ImmediateNumberB = ImmediateNumber[2:]  # Remove the 0b from the binary number
                ImmediateNumberB = ImmediateNumberB.zfill(8)  # Pad the binary number with 0s to make it 16 bits long

                binaryString += ImmediateNumberB  # Add the immediate number to the binary string (8 bits)
                binaryString += "01"  # Add 01 because we are using STR
                binaryString += "0"  # Add 0 because the instruction needs to use add/sub, despite it doing nothing here.
                binaryString += "0"  # Add 0 because the instruction does not need to write to a register
                binaryString += "00"  # Add 00 because we are not using a write register

                ReadRegID = args[1]

                if not ReadRegID[1].isdigit():
                    raise ValueError("Read register ID for STR instruction is not a number! Cannot continue.")

                if int(ReadRegID[1]) > 3 or int(ReadRegID[1]) < 0:
                    raise ValueError(
                        "Read register ID for STR instruction is not between 0 and 3 inclusive! Cannot continue.")


                ReadRegID = bin(int(ReadRegID[1]))  # Convert the write register ID to binary
                ReadRegIDB = ReadRegID[2:]  # Remove the 0b from the binary number
                ReadRegIDB = ReadRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long

                binaryString += ReadRegIDB  # Add the read register ID to the binary string (2 bits)
                return binaryString

        case "ldr":
            if len(args) != 3:
                raise ValueError("Invalid number of arguments for LDR instruction. Cannot continue.")

            else:
                if not args[2].isdigit():
                    raise ValueError("Invalid immediate number for LDR instruction. Cannot continue.")


                if int(args[2]) > 255 or int(args[2]) < 0:
                    raise ValueError("Immediate number for LDR instruction is not between 0 and 255 inclusive!. Cannot continue.")

                ImmediateNumber = bin(int(args[2]))  # Convert the immediate number to binary
                ImmediateNumberB = ImmediateNumber[2:]  # Remove the 0b from the binary number
                ImmediateNumberB = ImmediateNumberB.zfill(8)  # Pad the binary number with 0s to make it 16 bits long

                binaryString += ImmediateNumberB  # Add the immediate number to the binary string (8 bits)
                binaryString += "10"  # Add 10 because we are using LDR
                binaryString += "0"  # Add 0 because the instruction needs to use add/sub, despite it doing nothing here.
                binaryString += "1"  # Add 0 because the instruction needs to write to a register

                WriteRegID = args[1]

                if not WriteRegID[1].isdigit():
                    raise ValueError("Invalid read register LDR for SUB instruction. Cannot continue.")

                if int(WriteRegID[1]) > 3 or int(WriteRegID[1]) < 0:
                    raise ValueError("Read register ID for LDR instruction is not between 0 and 3 inclusive! Cannot continue.")

                WriteRegID = bin(int(WriteRegID[1]))  # Convert the write register ID to binary
                WriteRegIDB = WriteRegID[2:]  # Remove the 0b from the binary number
                WriteRegIDB = WriteRegIDB.zfill(2)  # Pad the binary number with 0s to make it 2 bits long
                binaryString += WriteRegIDB  # Add the write register ID to the binary string (2 bits)

                binaryString += "00"  # Add 00 because we are not using a read register
                return binaryString

        case _: # Default case
            raise ValueError("Invalid instruction hit! Cannot continue.")

def binary_to_hex(bstring):
    bstring = bstring.zfill(4)  # Pad the binary string with zeros if it has less than 4 bits
    hex_string = hex(int(bstring, 2))[2:]  # Convert the binary string to hexadecimal and remove the leading 0x

    return hex_string


def SendToFile(file_passer):
    file = open("output.txt", "w")  # Open the file in write mode
    file.write(file_passer)
    file.close()


def ProcessStart():
    try:
        file_name = input("Enter the file name: ")  # Ask for user input for the file name
        file = open(file_name, "r")  # Open the file for reading

        contents = file.read()  
        file.close()  # Contents are in memory now

        print("--—== Reading Instructions ==—--")
        print("--------------------")
        print(contents)  # Print the contents (DEBUG ONLY)
        print("--------------------")

        # Split the contents of the file into a list of lines
        lines = contents.split("\n")

        binary_instructions = []
        for line in lines:
            args = [arg.lower() for arg in line.split(
                " ")]  # Split the line into each individual argument AND make each argument lowercase to ignore case sensitivity
            binary_instruction = ImageBuilder(args)
            binary_instructions.append(binary_instruction)

        file_passer = "v3.0 hex words addressed\n"
        for i in range(0, 256, 16): 
            file_passer += f"{i:02x}: "
            for j in range(16):
                if i + j < len(binary_instructions):
                    hex_instruction = binary_to_hex(binary_instructions[i + j]).zfill(4)
                    file_passer += f"{hex_instruction}  "
                else:
                    file_passer += "0000  " # Fill/no data
            file_passer += "\n"

        SendToFile(file_passer)
        print("Successfully converted Shab-bot x16 instructions to a Logisim-evolution image file in this directory, named \"output.txt\"! ")

    except FileNotFoundError:  
        print(f"The specified file {file_name} was not found. Process terminating.")
        return


if __name__ == "__main__":
    ProcessStart()