move flattenTerms in java backend back to the beginning