Tidy up logic
Increase robustness, add support for arbitary flags