This commit also fixes a bug caused by excessive use of copypaste, which was detected by the included test.