added unit tests and optimized code