added Lu's new code, more refactoring