Added flag handling
Fully implemented sorting