rewrite

Performance optimized and bugs fixed