fix crazy multi-iteration in building hierarchy + sort results
fix #598