refactoring

bug correctiong and reorganization of code.