// Decompile FUN_80076e2c which writes 0xD0000E49 — identify what this byte is
//@category Analysis

import ghidra.app.script.GhidraScript;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressFactory;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.FunctionManager;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.InstructionIterator;
import ghidra.program.model.listing.Listing;

public class DecompileWriter extends GhidraScript {
    @Override
    public void run() throws Exception {
        AddressFactory af = currentProgram.getAddressFactory();
        FunctionManager fm = currentProgram.getFunctionManager();
        Listing listing = currentProgram.getListing();

        long[] funcAddrs = { 0x80076e2cL, 0x800770ccL };

        for (long fa : funcAddrs) {
            Address fAddr = af.getAddress(Long.toHexString(fa));
            Function func = fm.getFunctionAt(fAddr);
            if (func == null) {
                println("Function not found at 0x" + Long.toHexString(fa));
                continue;
            }
            println("\n================================================================");
            println(String.format("FUNCTION %s @ 0x%s  size=0x%X",
                    func.getName(), func.getEntryPoint(), func.getBody().getNumAddresses()));
            println("================================================================");

            // Print all instructions
            println("--- ALL INSTRUCTIONS ---");
            InstructionIterator it = listing.getInstructions(func.getBody(), true);
            int count = 0;
            while (it.hasNext()) {
                Instruction ins = it.next();
                println(String.format("  0x%s: %s", ins.getAddress(), ins.toString()));
                count++;
                if (count > 80) { println("  ... truncated"); break; }
            }

            // Decompile
            println("--- DECOMPILED ---");
            DecompInterface decomp = new DecompInterface();
            decomp.openProgram(currentProgram);
            DecompileResults res = decomp.decompileFunction(func, 90, monitor);
            if (res.decompileCompleted()) {
                println(res.getDecompiledFunction().getC());
            } else {
                println("Decomp failed: " + res.getErrorMessage());
            }
            decomp.dispose();
        }
        println("\nDONE");
    }
}
