Code cleanup taken from the LEX codebase.  Could be for 0.12, but let's just merge now.