Reimplementation of some of the functions to make it more readable and more efficient