add tests and small optimizations