An algorithm for sums of squares of real polynomials