Some bug fixing and reorganization