General code cleanup and improvement