This function does a lot of state changes, add comments to explain what's up.