some refactorings!
Needs debugging & test