Copied code from D4P project. Tests more or less pass.