Added advanced logging. Refactor.