Avoid making a copy of the input buffer

Avoid making a copy of the input buffer and fix some small leaks.
Better error checking in setupMagicCookie()