Code for the first chapter of my phd