Change panic to log.Fatal
Refactor to share some code