Bugfix 383, 897. Same as 918

Created a new PR because the previous on was messy. I've added a test case to ensure no regression.