Refactoring

Some changes and bug fixes resulting from peer review.