Code cleanup and speedup