Refactored get_levels function.