Working version, but somewhat unelegant.
Code beautified.