terribly convoluted z sorting