Lots of refactoring, and now median works