Added sorting functionality. Revamped output function.