Refactor code and add retry support, fixes #2