Part of the code that I wrote for my PhD