code cleanup and optimization on several functions