Add comments and minor refactoring