public Automaton convert(Automaton utf32) {if (utf32.getNumStates() == 0) {return utf32;}int[] map = new int[utf32.getNumStates()];Arrays.fill(map, -1);List<Integer> pending = new ArrayList<>();int utf32State = 0;pending.add(utf32State);utf8 = new Automaton.Builder();int utf8State = utf8.createState();utf8.setAccept(utf8State, utf32.isAccept(utf32State));map[utf32State] = utf8State;Transition scratch = new Transition();while (pending.size() != 0) {utf32State = pending.remove(pending.size()-1);utf8State = map[utf32State];assert utf8State != -1;int numTransitions = utf32.getNumTransitions(utf32State);utf32.initTransition(utf32State, scratch);for(int i=0;i<numTransitions;i++) {utf32.getNextTransition(scratch);int destUTF32 = scratch.dest;int destUTF8 = map[destUTF32];if (destUTF8 == -1) {destUTF8 = utf8.createState();utf8.setAccept(destUTF8, utf32.isAccept(destUTF32));map[destUTF32] = destUTF8;pending.add(destUTF32);}convertOneEdge(utf8State, destUTF8, scratch.min, scratch.max);}}return utf8.finish();}

public Automaton Convert(Automaton utf32){if (utf32.IsSingleton){utf32 = utf32.CloneExpanded();}State[] map = new State[utf32.GetNumberedStates().Length];List<State> pending = new List<State>();State utf32State = utf32.GetInitialState();pending.Add(utf32State);Automaton utf8 = new Automaton();utf8.IsDeterministic = false;State utf8State = utf8.GetInitialState();utf8States = new State[5];utf8StateCount = 0;utf8State.number = utf8StateCount;utf8States[utf8StateCount] = utf8State;utf8StateCount++;utf8State.Accept = utf32State.Accept;map[utf32State.number] = utf8State;while (pending.Count != 0){utf32State = pending[pending.Count - 1];pending.RemoveAt(pending.Count - 1);utf8State = map[utf32State.number];for (int i = 0; i < utf32State.numTransitions; i++){Transition t = utf32State.TransitionsArray[i];State destUTF32 = t.to;State destUTF8 = map[destUTF32.number];if (destUTF8 == null){destUTF8 = NewUTF8State();destUTF8.accept = destUTF32.accept;map[destUTF32.number] = destUTF8;pending.Add(destUTF32);}ConvertOneEdge(utf8State, destUTF8, t.min, t.max);}}utf8.SetNumberedStates(utf8States, utf8StateCount);return utf8;}
