added final implementation...some test cases remaining