with more test cases and some optimizations