Fixed some type errors, avoided accessing global state directly.