First working version

The only thing missing is the simplification, which shouldn't be
too difficult.