Moved sort_r function def to top of file