Pulled from existing code with some clean up. currently untested