bugfixes and code factorization