fixes #805 and #281
re factored this a bit to make it extensible and reusable,.