Major refactoring of cert handling