First complete version of the greedy algorithm.

Needs more testing.