extensive refactoring of the code. preloading added.