Finalized algorithm, added valid_algebra grammar encoding