refactored to accomodate some changes suggested by @briantemple