Added sorting, cleaned up some code and added some comments