further optimizations, may be buggy!