US stocks end midweek with gains, S&P 500 hits record level