Debugging this was fun! Comment here if you can figure out how it works (what it does is pretty simple). I'll upload the spoilerised version later.
Making it compile under MSVC++ (or, indeed, anything outside of gcc-4) is left as an exercise for the reader.