/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Export;

import API.ExportInterface;
import API.Utils;
import common.Block;
import common.Code;
import common.Instruction;
import java.util.Map;
import tools.mips.Memory;
import tools.mips.MipsSettings;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class Simulation implements ExportInterface {

    protected MipsSettings settings;

    public Simulation(tools.mips.MipsSettings settings) {
        this.settings = settings;

    }

    @Override
    public void Exec(Code IR, Code Target) throws Exception {
        String bin;

        Memory memory = new Memory(
                settings.Get("memory.instruction"),
                settings.GetInt("memory.instruction.size")
        );

        memory.SetIO(new MemoryInitializationFile());

        for (Map.Entry<String, Block> x : Target.stmts.entrySet()) {
            for (Instruction instr : x.getValue().Instructions()) {
                bin = instr.Get("inst.bin");

                if (bin.equals("")) {
                    continue;
                }
                // Divide os bytes da instrução binaria e escreve na memoria
                for (String sbyte : Utils.SplitEach(bin, 8)) {
                    memory.WB(sbyte);
                }
            }
        }

        // Grava resutlado no arquivo de memoria do simulador
        memory.Save();

        // Instancia um simulador, executa e salva a memoria
        new tools.mips.MipsProcessor(settings)
                .Run()
                .Persist();
    }

}
