Code cleanup and fixed minor bugs