Added a lot of code to wait for states to change before proceeding.