Removed duplicate code and added test