Improved logging, error handling and duplication avoidance.
Fixed error handling.
Added ai.