fixes the bugs spotted.
makes use of bitflags for performance optimization