Fixed various bugs

These fixes are all tested.