Various fixes and improvements to class flags

Fixes a couple of bugs (resolves #1211), adds class flag creation/modification time and scheduling status (resolves #1137), and improves query performance.
If you can think of a better name, can you rename ```i``` to something else? It's not really descriptive, and it also makes me think it's an index.

Many of the other important variables in this function also have undescriptive one-letter names. Can you consider renaming all of them, to reduce confusion?