Working version with sort