package miggy.cpu.genpoet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import miggy.cpupoet.MacroPLA;

public class CoreVerifier {
	public static final Pattern OP_PATTERN2 = Pattern.compile("^(\\S+)\\s+(\\S+)\\s+([\\S.]+)\\s+([\\S.]+)\\s+(\\S+).*");

	public static void main(String[] args) throws NumberFormatException, IOException {
		InputStream res = CoreVerifier.class.getResourceAsStream("m68000.lst");
		BufferedReader in = new BufferedReader(new InputStreamReader(res, StandardCharsets.UTF_8));
		
		try {
			String line = null;

			while((line = in.readLine()) != null) {
				Matcher matcher = OP_PATTERN2.matcher(line);

				if (matcher.find()) {
					String opname = matcher.group(3);
					int opcode = Integer.parseInt(matcher.group(1), 16);
					int mask = Integer.parseInt(matcher.group(2), 16);
					String ea1 = matcher.group(4);
					String ea2 = matcher.group(5);

					StringBuilder builder = new StringBuilder();

					builder.append(opname.replace('.', '_'));
					if (!"-".equals(ea1)) {
						builder.append('_');
						builder.append(ea1);
					}
					if (!"-".equals(ea2)) {
						builder.append('_');
						builder.append(ea2);
					}
					
					String mnemonic = builder.toString();
					boolean found = false;
					
					for(MacroPLA entry : MacroPLA.values()) {
						if ((opcode == entry.opcode) && (mask == entry.opmask)) {
							found = true;
							
							if (!mnemonic.equals(entry.name())) {
								System.out.println(String.format("mismatch for opcode 0x%04x (mask: 0x%04x) want '%s', got '%s'", opcode, mask, mnemonic, entry.name()));
							}
							
							break;
						}
					}
					
					if (!found) {
						System.out.println(String.format("opcode '%s' 0x%04x (mask: 0x%04x) not found", mnemonic, opcode, mask));
					}
				}
			}
		} finally {
			in.close();
		}
	}


}
