changed sorting code to run much slower but never fail