Even though this section of the code is huge, the relevant parts were commented, so it wasn't so hard