Various code fixes from static analysis

The code doesn't seem to pass a purely static compilation pass: some symbols are missing, etc. This is what I found using PyDev (untested).