cleanup and optimize some code