adapt the code for multiple categories and improve alphabetical sort