Optimization and bugs fixed