Cleaned up code, added auto-sorting.