minor optimizations, fixes some bugs