working version of multi-step sorting