Initial attempt at sorting logic
Additional error handling