Merge most changes from whorfin's pull request and implement most of his logic.

Signed-off-by: srlefevre <slefevre@indy.rr.com>