implemented endgame (not fully tested)