Version of the code that gets very close to working