APW.  This is pretty messy, and could do with a lot of cleaning up.

Feel free to jump in.