include	clib.inc
include	clip.inc
include	conio.inc
include	malloc.inc
include	string.inc

	public	clipbsize
	public	clipboard
	public	ClipboardCopy
	public	ClipboardPaste
	public	ClipboardFree

_DATA	SEGMENT

winoldap  dw ?
clipbsize dw ?
clipboard dd ?

_DATA	ENDS

_TEXT	SEGMENT

OpenClipboard PROC
	mov ax,winoldap
	.if ax
	    mov ax,1701h	; OPEN CLIPBOARD
	    int 2Fh		; nonzero success, else already open
	    inc ax
	.endif
	ret
OpenClipboard ENDP

CloseClipboard PROC
	push dx
	push ax
	mov ax,1708h	; INT 2F - MS Windows - CloseClipboard
	int 2Fh
	pop ax
	pop dx
	ret
CloseClipboard ENDP

ClearClipboard PROC
	xor ax,ax
	mov clipbsize,ax
	.if word ptr clipboard+2 != ax
	    pushm clipboard
	    stoso clipboard,ax,ax
	    call free
	.endif
	ret
ClearClipboard ENDP

ClipboardFree proc DIST
	call ClearClipboard
	ret
ClipboardFree endp

ClipboardCopy proc DIST pascal uses si di string:dword, len:word
	mov di,len
	call ClearClipboard
	.if console & CON_CLIPB
	    call	OpenClipboard
	    .if !ZERO?
		mov ax,1702h	; EMPTY CLIPBOARD
		int 2Fh		; AX nonzero clipboard has been emptied
		mov dx,1		; set type to text
		mov cx,di		; SI:CX = size of data
		xor si,si		; HSIZE = 0
		les bx,string	; ES:BX = data
		mov ax,1703h	; SET CLIPBOARD DATA
		int 2Fh
		call CloseClipboard
		or ax,ax		; nonzero data copied into the Clipboard
		mov ax,di
		jnz @F
	    .endif
	.endif
	mov ax,di
	inc ax
	invoke malloc, ax
	.if ax
	    stom clipboard
	    mov es,dx
	    mov bx,ax
	    mov clipbsize,di
	    add bx,di
	    mov byte ptr es:[bx],0
	    invoke memcpy, dx::ax, string, di
	    mov ax,di
	.endif
    @@:
	ret
ClipboardCopy endp

ClipboardPaste proc dist
	.if !(console & CON_CLIPB)
	    .if clipbsize
		lodm clipboard
	    .else
		xor ax,ax
		cwd
	    .endif
	.else
	    mov ax,1701h	; OPEN CLIPBOARD
	    int 2Fh		; nonzero success, else already open
	    mov dx,1		; DX = clipboard format supported
	    mov ax,1704h	; GET CLIPBOARD DATA SIZE
	    int 2Fh		; DX:AX = size of data in bytes
	    call CloseClipboard
	    .if dx
		xor ax,ax
		cwd
	    .endif
	    .if !ax || ax >= MAXCLIPSIZE
		xor ax,ax
		.if clipbsize != ax
		    lodm clipboard
		.endif
	    .else
		push ax
		push ax
		call ClearClipboard
		call malloc
		pop cx
		.if ax
		    mov clipbsize,cx
		    stom clipboard
		    invoke memzero, dx::ax, cx
		    mov ax,1701h
		    int 2Fh
		    mov dx,1
		    les bx,clipboard
		    mov ax,1705h
		    int 2Fh
		    call CloseClipboard
		    lodm clipboard
		.endif
	    .endif
	.endif
	or ax,ax
	ret
ClipboardPaste endp

Install PROC
	.if console & CON_CLIPB
	    mov ax,1700h
	    int 2Fh
	    mov dx,ax
	    xor ax,ax		; AX <> 1700h
	    .if dx != 1700h   	; - AL = WINOLDAP major version
		inc ax		; - AH = WINOLDAP minor version
	    .endif
	    mov winoldap,ax
	.endif
	ret
Install ENDP

_TEXT	ENDS

_INIT_	SEGMENT
	dw	Install
_INIT_	ENDS

	END
