package projet

import chisel3._

class RegFile(sim: Boolean = false) extends Module {
    val io = IO(new Bundle {
        val rs1_addr = Input(UInt(5.W))
        val rs2_addr = Input(UInt(5.W))
        val rd_addr = Input(UInt(5.W))
        val rd_data = Input(UInt(64.W))
        val we = Input(Bool())
        val rs1_data = Output(UInt(64.W))
        val rs2_data = Output(UInt(64.W))

        val x31 = Output(UInt(64.W))
        val valid_x31 = if (sim) Some(Output(Bool())) else None
    })

    val regs = Mem(32, UInt(64.W))

    if (sim) {
        when(reset.asBool) {
            for (i <- 0 to 32) {
                regs(i.U) := 0.U
            }
        }
    }

    when(io.we && io.rd_addr =/= 0.U) {
        regs(io.rd_addr) := io.rd_data
    }

    io.rs1_data := regs(io.rs1_addr)
    io.rs2_data := regs(io.rs2_addr)

    // Simulation stuff
    if (sim) {
        io.valid_x31.get := false.B
        io.x31 := "hDEADC0DE".U
        when(io.we && io.rd_addr === 31.U) {
            io.x31 := io.rd_data
            if (sim) {
                io.valid_x31.get := true.B
            }
        }
    } else {
        io.x31 := regs(31.U)
    }
}
