adds sanity check when stack has < 2 elements; adds minor refactorings;