Refactored and fixed AI