Added in code for glitch at the end. Various code cleanups.