Automatic rem detection with adaptive threshold