General code cleanup, fixing some minor bugs