Fix various bugs, improve performance