Fixed #828. Added many other minor refactorings.