Code cleanup, added a few flags to better control logic flows.