Code cleanup, minor fixes to logic