Optimize: replaced booleans with a flagset
Optimize: do not use closures