[WIP] Porting analysis code

We'll need a lot of future iterations on this stuff, as there was a lot of code duplication.