Fix errors when we don't have enough data.

Also added some tests. Run with `trial tests`.