# gcc -nostdinc -nostdlib -Wl,-Ttext,0x7c00 a.s
# objcopy -O binary a.out
# dd if=a.out of=/dev/ad4s2 count=1
	.text
	.code16
	.org	0
	cli
	# Enable A20
	mov	$0x64,%dx
1:	in	%dx,%al
	test	$2,%al
	jne	1b
	mov	$0xd1,%al
	out	%al,%dx
1:	in	%dx,%al
	test	$2,%al
	jne	1b
	mov	$0xdf,%al
	out	%al,$0x60
1:	in	%dx,%al
	test	$2,%al
	jne	1b
	mov	$0xff,%al
	out	%al,%dx
	# Go to big-real mode
	lgdt	gdtr
	mov	%cr0,%eax
	inc	%eax
	mov	%eax,%cr0
	mov	$8,%bx
	mov	%bx,%ds
	mov	%bx,%es
	mov	%bx,%fs
	mov	%bx,%gs
	mov	%bx,%ss
	dec	%eax
	mov	%eax,%cr0
	ljmp	$0,$1f
gdtr:	.short	0xf
	.long	gdtr
	.short	0
	.quad	0x008f93000000ffff
1:	xor	%bx,%bx
	mov	%bx,%ds
	mov	%bx,%es
	mov	%bx,%fs
	mov	%bx,%gs
	mov	%bx,%ss
	mov	$1b,%sp
	sti
	cld
	# print menu
menu:	mov	$msgmenu,%si
	call	print
	call	input
	mov	0x8000,%al
	cmp	$'1',%al
	je	search
	cmp	$'2',%al
	je	dump
	jmp	menu
########
# search a keyword
search:
	# input keyword
	call	input
	mov	%di,%dx
	sub	$0x8001,%dx
	# search it
	mov	0x8000,%bl
	mov	$0x00100000,%esi
1:	cmp	$0x80000000,%esi
	jae	fin
	test	$0x0fffffff,%esi
	jne	2f
	mov	$0x0e00+'.',%ax
	int	$0x10
2:	addr32	lodsb
	cmp	%bl,%al
	jne	1b
	push	%esi
	mov	$0x8001,%edi
	mov	%dx,%cx
	repe	addr32	cmpsb
	pop	%esi
	jne	1b
	# found
	addr32 lea	-1(%esi),%eax
	call	printhex
	mov	$0xe20,%ax
	int	$0x10
	jmp	1b
fin:	jmp	menu
########
# dump
dump:	call	input
	mov	$0x8000,%si
	xor	%ebx,%ebx
1:	cmp	%si,%di
	je	1f
	lodsb
	and	$0x1f,%al
	sub	$0x10,%al
	jnb	2f
	add	$0x19,%al
2:	shl	$4,%ebx
	or	%al,%bl
	jmp	1b
1:	mov	%ebx,%eax
	call	printhex
	mov	$1024,%cx
3:	addr32	mov	(%ebx),%al
	inc	%ebx
	cmp	$32,%al
	jb	1f
	cmp	$127,%al
	jbe	2f
1:	mov	$' ',%al
2:	mov	$0xe,%ah
	int	$0x10
	loop	3b
	jmp	menu
########
# input
input:	mov	$0x8000,%di
1:	mov	$0,%ah
	int	$0x16
	cmp	$13,%al
	je	enter
	cmp	$8,%al
	je	bs
	stosb
	mov	$0xe,%ah
	int	$0x10
	jmp	1b
bs:	dec	%di
	jns	input
	mov	$msgbs,%si
	call	print
	jmp	1b
enter:	cmp	$0x8000,%di
	je	input
	mov	$msgret,%si
	jmp	print

########
# print
1:	mov	$0xe,%ah
	int	$0x10
print:	lodsb
	test	%al,%al
	jne	1b
	ret

########
# printhex
printhex:
	ror	$16,%eax
	call	printhex16
	ror	$16,%eax
printhex16:
	xchg	%ah,%al
	call	printhex8
	xchg	%ah,%al
printhex8:
	ror	$4,%al
	call	printhex4
	ror	$4,%al
printhex4:
	push	%ax
	and	$0xf,%al
	add	$0x90,%al
	daa
	adc	$0x40,%al
	daa
	mov	$0xe,%ah
	int	$0x10
	pop	%ax
	ret

msgmenu:
	.ascii	"\r\n1.search 2.dump"
msgret:	.string	"\r\n"
msgbs:	.string	"\b \b"
	.org	510
	.byte	0x55,0xaa
