; [ Wave ] 64-byte intro
; (c) 2019 by Jin X (Telegram: @jinxonik / jin_x@list.ru)

%define SONG_NUMBER	1			; song number (1..3)
%assign ALLOW_EXIT	1			; 0 - infinite playback, 1 - allow exit
%define VIDEO_SHIFT	0;16			; video page start shift (0xA000-0x9FFF)*16

;-----------------------------------------------------------------------------------------------------------------------

use16
org	0x100

		; Set video mode
		mov	al,0x13
		int	0x10
%if	VIDEO_SHIFT == 0
		push	0xA000
		pop	es
%else
		les	bp,[bx]			; es=0x9FFF (as a rule)
%endif

		; Tune timer
		inc	ax			; al = 0x14 - set lower byte only
		out	0x43,al
		lodsb				; first byte of code = 0xB0
		out	0x40,al			; PIT counter divisor (1193182 / 0xB0 = 6779 Hz)

	mainloop:
		; Calculate sample
%if	SONG_NUMBER == 1
		; t & (t>>8)
		mov	al,bl			; al = t
		and	al,bh			; al = t & t>>8
		inc	bx			; increase counter
%elif	SONG_NUMBER == 2
		; t * (t>>10 & 42)
		shld	ax,bx,16-10		; al = t>>10
		and	al,42			; al = t>>10 & 42
		mul	bl			; al *= t
		inc	bx			; increase counter
%elif	SONG_NUMBER == 3
		; t * ((t>>12 | t>>8) & t>>4 & 63)
		shld	eax,ebx,32-4		; al = t>>4, ah = t>>12
		or	ah,bh			; ah = t>>12 | t>>8
		and	al,ah			; al = (t>>12 | t>>8) & t>>4
		and	al,63			; al = (t>>12 | t>>8) & t>>4 & 63
		mul	bl			; al *= t
		inc	ebx			; increase counter
%endif

		mov	di,32 + (36+128)*320 + VIDEO_SHIFT ; Y = 164
		movzx	dx,bl
		add	di,dx			; X = 32 + dl
		mov	cl,128
	.next:	cmp	al,cl
		xchg	dx,ax
		salc
		and	al,bh			; 0 or bh
		stosb
		xchg	ax,dx
		sub	di,321
		loop	.next

		; Play sample
%if	SONG_NUMBER == 1
		sub	al,1
		salc
%else
                shr	al,6
%endif
;		and	al,2			; can be omitted for economy :)
		out	0x61,al			; set speaker position

		; Delay and loop or exit
		hlt				; delay
%if	!ALLOW_EXIT
		jmp	mainloop		; infinite loop :)
%else
		mov	ah,1
		int	0x16
		jz	mainloop		; loop if no key is pressed

		; Restore timer
		mov	al,0x24
		out	0x43,al
		xor	al,al
		out	0x40,al
		
		ret
%endif
