Refined implementation and added test cases