Commented and cleaned up so it should be a little easier to understand