Big cleanup, refactoring of data structures and bug fixing.