move defer calls to after error check to avoid panic
Merge pull request #17 from kvarga/deferfix

move defer calls to after error check to avoid panic