Refactor TLS code and add some tests. The tests and expected results are: