	title	REL-80 bit package
	name	('BITS')

; This package gets bits from input stream as defined
; by the MICROSOFT LINK-80 format

; Copyright (c)	Werner Cirsovius
;		Hohe Weide 44
;		D-20253 Hamburg
;		(+49)40/4223247

;		Version 1.0, September 1993

;
; The bitxx package : Get xx bits from stream
; EXIT	: Accu holds value
;
; Exeptions:	BIT1  - Carry reflects state of bit
;		BIT16 - Reg HL holds value

; Requires two addresses to be set externally:
; - DSKPC:  Address of disk byte read routine
; - BITERR: Address of disk read error routine

bits	equ	8

	entry	bit1,bit2,bit3,bit4,bit8,bit16
	entry	bitcnt,biterr,dskpc

	entry	AField,BField

bit16:
	call	bit8		; Get eight bits
	ld	l,a		; Save it as LO
	call	bit8		; Get next eight bits
	ld	h,a		; .. as HI
	ret
bit2:
	ld	a,2		; Two bits
	jr	bit..
bit3:
	ld	a,3		; Three bits
	jr	bit..
bit4:
	ld	a,4		; Four bits
	jr	bit..
bit8:
	ld	a,8		; Eight bits
bit..:
	push	bc
	ld	b,a		; Set count
	ld	c,0		; Reset result
nxtbit:
	call	bit1		; Get bit
	rl	c		; .. into reg
	djnz	nxtbit
	ld	a,c		; Get bit
	pop	bc
	ret
bit1:
	push	hl
	ld	hl,byte
	ld	a,(hl)		; Get byte
	inc	hl		; .. point to count
	inc	(hl)
	jr	nz,morebits	; .. test all got
	call	.dskget		; Get a byte
	jr	c,rederr
	ld	(hl),-bits	; Init bit count
morebits:
	add	a,a		; Shift byte into carry
	dec	hl
	ld	(hl),a
	pop	hl
	ret
rederr:
	ld	hl,(biterr)	; Get user error routine
	jp	(hl)		; .. jump
;
; Get two control bit fields followed by 16 bit
; EXIT	: Accu holds two bits
;	  Reg HL holds 16 bits
;
AField:
	call	bit2		; Get two bits
	push	af
	call	bit16		; .. and 16
	pop	af
	ret
;
; Get three control bit fields followed by characters
; ENTRY	: Reg HL points to name field
; EXIT	: Name field filled with
;		LEN,CH1,...,CH7,00
;
BField:
	call	bit3		; Get three bits as count
	or	a		; Test zero
	jr	nz,..BF
	inc	a		; .. 0 implies 1
..BF:
	ld	b,a
	ld	(hl),a		; Set length
namlop:
	call	bit8		; Get character
	inc	hl
	ld	(hl),a		; .. save it
	djnz	namlop
	inc	hl
	ld	(hl),b		; .. close field
	ret
;
; The byte get linkage
;
.dskget:
	jp	$-$		; Must be changed externally
dskpc	equ	$-2

	dseg

byte:
	ds	1		; Byte holder
bitcnt:
	db	-1		; Bit counter
biterr:
	dw	0

	end

