many changes and optimizations

(not tested)