Tweaked processMessages function