Refactor to use states and transitions; also fixes #5