Fixed bug in median computation.
Refactored code, fixed bugs and added unit tests.