Recode BuildClassesMap, FindNearestRivalDistnaces, OrderClassesMap functions, write tests and a lot of small fixes