Big refactoring with many added tests.

Signed-off-by: Yoan Blanc <yoan.blanc@cern.ch>