Fix loop issues and better logging