Cleaning up code. Improved robustness; added additional state checking.