/*
 * 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 target.mips;

import API.Instruction;
import IntermediaryCode.Block;
import IntermediaryCode.Code;
import IntermediaryCode.CodeProcessing;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author EUGENIO CARVALHO
 */
class UpdateAddressProcessor implements CodeProcessing {

    public UpdateAddressProcessor() {
    }

    /*
     (parseInt("2c",10) * 4).toString(16)
     */
    @Override
    public void Exec(Code c, LinkedHashMap<String, CodeProcessing> cp) throws Exception {

        for (Map.Entry<String, Block> x : c.getBlocks().entrySet()) {
            for (Instruction y : x.getValue().Instructions()) {
                // atualiza o indice da instrução de pc + 4
                if (y.isNumber("global.position")) {
                    y.S("block.position", y.getInt("block.position") * 4);
                    y.S("global.position", y.getInt("global.position") * 4);
                } else if (y.eq("type", "label")) {
                    // atualiza o endereco dos labels
                    y.S("reference.position", y.getInt("reference.position") * 4);
                    y.S("global.reference.position", y.getInt("global.reference.position") * 4);
                }
            }
        }
        String[] parts;
        int index;
        // Update address of labels
        for (Map.Entry<String, ArrayList<String>> entry : c.labels.entrySet()) {
            ArrayList<String> labeldata = entry.getValue();
            labeldata.set(0, (Integer.parseInt(labeldata.get(0)) * 4) + "");
            try {
                parts = labeldata.get(1).split("(\\+)");
                if (parts.length > 1) {
                    index = Integer.parseInt(parts[1]);
                    labeldata.set(1, parts[0] + "+" + (index * 4));
                }
            } catch (Exception e) {
            }
        }
    }

}
