Merged Mark and Ky's code.