Merge of Jacob's and Mark's code.