Intermittant problem

I have a 2003 Subaru Forester, bought it this past January. Got 163,000 miles on it, and we’ve driven it mostly around town. Over the last month, it has developed an intermittant problem with stalling and rough “putt-putt” runing, and will only keep running if the gas pedal gets pumped. This seems to happen about every other time we turn it on, but without a pattern. It can be running fine, and then switch mode, as it were, to running rough and tending to stall. I’ve gotten ignition codes (check engine light came on and I had my guy check it out on the computer) twice. My mechanic (a long-term Subaru mechanic) has checked out the injectors, and replaced the head gasket, but the problem has not changed. I’m thinking that this may be an electronics issue or possibly somethhng in the gas tank/line, but Id like some other thoughts on this.

Thanks.

Can you tell us what codes the check engine light came on for.

What engine is in this.

Yosemite