Made robust to stack manipulations and added test.