Also includes some misc fixes for bugs I ran into along the way.
Could use some work, but it works for now.