refactor, extracting more methods, defines. fixed some warnings.