Fixed bugs (thanks to Mark Lane for testing)