This line is getting very long, should probably extract some of this into other methods.