fixed grammar to allow more than two terms and factors