Cleanup code some. Add comments to less intuitive parts.