Add unload() function

Also factored out some state initialization into separate function.