Fix some stupid bugs and split up the common bits