Removed unused code. Some refactoring and bug fixes.