refactor code, check for invalid certificates