manual merge of fork, most of the code cleaned up