Fixed infinite loop in code caused by unstable states, and other minor changes