Complete rewrite from scratch, doesn't suck now.