2002 subaru forester surges and hesitates

I should add that it was also sometimes idling so rough that it will stall out at stops or red lights. Sometimes it will run fine for a few miles, then start hesitating/running rough again. I’ve also found that it runs better when temperature (outside) is 40 degrees or above.