Rewrote from scratch. Test version.