Code cleanup, bug fixes