Parts of code reworked for it to be more correct and easier to read.