mostly working sort method, needs touching up.