cleanup and some optimizations