Final Working Code with Test Cases