Fix #528

Complete rewrite.

Fix #528