Several bugs fixed and some refactorization

pre 1.4