An assload of null checking for keys

also went through and cleaned up some code issues, redundant casts,
unnecessary local variables and the like