; File name: basic.mac
; Version:   2.0 (Dec 1, 1997)
; Description: a collection of useful macros by Chee Yap,
;	for use in the class v22.0201 (Machine Org I).
;	Contains the macros in the text of Yu and Marut.
;	Note that some macro names may have changed,
;	e.g., "save_regs" is called "save" here,
;	since you could save non registers as well.

; useful ascii codes
ascii_equ macro
	beep 	equ 07h
	backsp	equ 08h
	LF	equ 0Ah
	CR	equ 0Dh
	endm

; initialize ds,es
initdata macro
	mov ax,@data 	; initialize ...
	mov ds,ax	;     ds 
	mov es,ax	;     and es
	endm

; exit to dos
exitdos macro
	mov ax,4c00h	; dos exit
	int 21h
	endm

; display message
dispmsg macro msg
	mov ah,9	; function 9=print string
	lea dx,msg	; load address of string
	int 21h
	endm

; display directly message
display_it macro msg
	local start,stg
      save <ax,dx,ds>
	jmp start
   stg	db msg,'$'
   start: mov ax,cs
	mov ds,ax	; set ds to code segment (cs)
	mov ah,9
	lea dx,stg
	int 21h
   ; restore reg
	restore <ds,dx,ax>
	endm

; newline
newline	macro
	mov ah,2
	mov dl,13
	int 21h
	mov dl,10
	int 21h
	endm

; newlines
newlines macro n
	mov ah,2
	rept n
	mov dl,13
	int 21h
	mov dl,10
	int 21h
	endm
	endm	

; copy string
copystg macro source,dest,len
	; ASSUMES ds,es have been initialized properly
	push si		; source for string copy macro
	push di		; dest for string copy macro
	push cx		; length for string copy macro
	lea si,source
	lea di,dest
	mov cx,len
	cld
	rep movsb
	pop cx		; restore registers for string copy macro
	pop di
	pop si
	endm

; save values
save	macro values	; values are comma separated inside <...>
	irp d,<values>
	push d
	endm
	endm

; restore values
restore macro values	; values are comma separated inside <...>
	irp d,<values>
	pop d
	endm
	endm

; convert input binary byte (0-15) to a hex digit
;    called by outhex macro
conv2hex macro bin
	local exit
	or bin,30h
	cmp bin,39h
	jbe exit
	add bin,7
   exit: endm

; displays contents of a byte in ascii
disp_char macro byt
	push ax
	mov ah,2
	mov dl,byt
	int 21h
	pop ax
	endm

; displays a byte in binary as 2 hex digits
outhex macro bin
	save <bx,cx,dx>
	mov bl,bin
	mov cl,4
	rept 2 
	mov dl,bl
	shr dl,cl
	conv2hex dl	; macro
	disp_char dl	; macro
	rol bl,cl
	endm
	restore <dx,cx,bx>
	endm
	
; displays a byte in binary as 4 hex digits
outhex2 macro bin
	push ax
	mov ax,bin
	outhex ah	; macro
	outhex al	; macro
	pop ax
	endm
	
; pause by waiting for a keyboard input
;	(typically, you first print a message because this)
; BUG: int 21h,fcn=1 does not eat up the typed character!
;	use int 16h,fcn=0 instead!
pause	macro stg
	display_it stg	; message
	push ax
	mov ah,0
	int 16h
	pop ax
	endm

; delay function
;	we use a doubly nested loop
;	inner and outer are binary unsigned word values
delay macro inner, outer
	local inloop, outloop
	save <bx,cx>
	mov cx,outer
   outloop: mov bx,inner
   inloop: dec bx
	jnz inloop
	dec cx
	jnz outloop
	restore <cx,bx>
	endm
	
