I know this is somewhat complicated so I commented it more thoroughly.