Oops, I just found a bug. I had left an old block of code in there in which I had tried something out. And it results in shutdown not working, or working unexpectedly in some cases. Sorry.
I think I've fixed it, but haven't tested it a whole lot, since it's 4:30 a.m.
See updated version
here