Code performance and logic fixes