/src/BlinkenFileSelect.java
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.io.IOException;
import java.util.Vector;
import java.util.Enumeration;

class LoadThread extends Thread {
	private BlinkenCPU blink;
	private String file;

	public LoadThread(BlinkenCPU b, String fn) {
		super();
		blink = b;
		file = fn;
	}

	public void run() {
		blink.loadFile(file);
	}
}


public class BlinkenFileSelect extends Thread implements CommandListener {
	private List fileSelect;
	private BlinkenCPU blink;
	private Display display;
	private BlinkenEngine engine;
	private String location;

	private static final Command load = new Command("Load", Command.OK, 1);
	private static final String[] locations = { "file:///other/", "file:///c:/other/", "file:///" };

	public BlinkenFileSelect(BlinkenCPU b, BlinkenEngine e, Display d) {
		super();
		blink = b;
		engine = e;
		display = d;
	}

	public void run() {
		FileConnection fc = null;
		Enumeration roots = FileSystemRegistry.listRoots();

		while (roots.hasMoreElements()) {
			location = "file:///" + roots.nextElement() + "other/";
			try {
				fc = (FileConnection) Connector.open(location, Connector.READ);
			} catch (IOException e) {
				blink.shitSauce("IO Error", "Could not open " + location);
				continue;
			}
			if (fc.isDirectory()) {
				break;
			} else {
				fc = null;
			}
		}
		if (fc == null) {
			blink.shitSauce("Directory not found", "No suitable directory found for data files");
			return;
		}

		Vector v = new Vector();
		Enumeration names;
		try {
			names = fc.list("*.bc", false);
		} catch (IOException e) {
			blink.shitSauce("IO Error", "Could not list directory");
			return;
		}
		while (names.hasMoreElements())
			v.addElement(names.nextElement());
		if (v.size() == 0) {
			display.setCurrent(new Alert("No files found"));
			return;
		}
		String[] files = new String[v.size()];
		v.copyInto(files);
		
		fileSelect = new List("Select Code", List.IMPLICIT, files, null);
		fileSelect.setSelectCommand(load);
		fileSelect.setCommandListener(this);
		display.setCurrent(fileSelect);
	}

	public void commandAction(Command c, Displayable d) {
		if (c == load) {
			LoadThread lt = new LoadThread(blink, location + fileSelect.getString(fileSelect.getSelectedIndex()));
			lt.start();
		}
	}
}