Some minor refactorings and a fix for a logic error.