working code with about 60% of the test cases..