https://trac.torproject.org/projects/tor/ticket/12085
Made some changes here and there on meejah's suggestions.
TODO: Get rid of the renundant code
TODO: Write unit tests