Add formula_spec and fix error in flatten
Factor out formula parser