refactoring of most of the code