C-----------------------------------------------------------------
C	Exit Handler for DM
C-----------------------------------------------------------------
	Subroutine DM_Exit_Handler
	Integer*2 K
	Real Terminal_Delay
	Include 'Common.Dat'

	Data Terminal_Delay /0.05/

C-----------------------------------------------------------------
	Have_DCL_Setup = .FALSE.  ! Can't Close Mbx from Exit_Handler,
C				    But it will go away anyway.
	Call Cancel_DCL  ! Get rid of subprocess.
	Call SMG$Set_Cursor_Mode (Pasteboard_ID, 0)
	Call SMG$Set_Broadcast_Trapping (PasteBoard_ID,%Val(0)) !Disabled
	Call SMG$Delete_PasteBoard (PasteBoard_ID,1)
  	Call SMG$Delete_Virtual_Keyboard (Keyboard_ID)

C		Under some conditions, this is needed.
	Call Lib$Wait(Terminal_Delay)
	Call WriteTerm (LargeScreen)
C	Call WriteTerm (Cursor_On)
	Call Restore_Entering_Terminal ! Put the tube back the way it was.
	Call WriteTerm (CSI//'1;1H')   ! Cursor at 1,1

	If (Exit_Com(1:4) .EQ. 'zzzz') then
		Stat = Lib$Set_Symbol('DM$command', 'goto getout')
C			NOTE: The following two instructions are not exactly
C			"honest".  See Normal_Keys.for for what the
C			'X' command does (Original_x = Current_x)
		If (Current_Device .NE. Original_Device) then
		   Call Str$Trim (%Descr(Original_Device)
	1		,%Descr(Original_Device),%Ref(K))
		   Call Lib$Set_Logical('SYS$DISK',Original_Device(:K))
		End If
	      	Call Sys$SetdDir( Original_Dir, %Val(0), %Val(0) ) 
	Else
		Call Save_Stack       ! Save current environment
		Stat = Lib$Set_Symbol('DM$command', exit_com)
	End If 

C 
C Display any broadcast messages we might have
C 
	If (Num_Message .GT. 0) then
	
	  Open (Unit=6, File='SYS$OUTPUT', RECL=4096, Status='OLD')
	
	  If (Num_Message .EQ. 1) then
	    Write (6,1000) 
	1     CSI//'1;4m '//
	2'While you were using DM you received the following message:'
	3     //CSI//'0m'
	  Else
	    Write (6,1000) 
	1     CSI//'1;4m '//
	2'While you were using DM you received the following messages:'
	3     //CSI//'0m'
	  End If
	
	  Write (6,1000)
1000	     Format(1X,A)
	
	  Do 10 I=1, Num_Message
		Write (6,1000)	Message(Msgstart(i):Msgstart(i+1)-1)
10	  Continue
	
C 		If exiting, we need to hold the screen for a while.
	  If (Exit_Com(1:4) .EQ. 'zzzz') then
	  	Write (6,1000)
	  	Write (6,1000)' [End of Messages]'
		Call Lib$Get_Input 
	1	  (Broadcast_Msg,
	2	   CSI//'1m Press Return to Exit from DM:'//
	3	   CSI//'0m')
	  	Write (6,1000) CSI//'2J'
	  End If
	
	  Close (Unit=6)
	
C The following are not necessary, because we will reload common after exit.
C	  Msgstart(1) = 1
C	  Msgstart(2) = 1
C	  Num_Message = 0
C	  Have_Broadcast = .FALSE/
	
	End If
	
	
C		GO OUT TO DCL  (DM.COM) AND RUN A COMMAND
C		Will run 'exit_com' unless it's value is 'GOTO GETOUT'

	Return
	End
