Major rewrite
Optimized some code