use flag package; some restructuring