Big cleanup, logic fixes