Automatic segmentation of REM sleep into three substages