Fix a  few bugs, some performance improvements