Refactor and minor bug fixes.