improve resource managing and code cleanup