;
;	General sort routine, in memory
;
;
;
;
orig	org	0ab00h	;chance this for dif loc
n1:	equ	orig
m1:	equ	n1+2
k1:	equ	m1+2
j1:	equ	k1+2
i1:	equ	j1+2
ml1:	equ	i1+2
dj1:	equ	ml1+2
di1:	equ	dj1+2
;
	ds	16
;
	lhld	j1	;get st adr
	push	h	;save
	lhld	k1	;get length
	push	h	;save
div:	xra	a	;m1=m1/2
	lhld	m1
	mov	a,h
	rar
	mov	h,a
	mov	a,l
	rar
	mov	l,a
	shld	m1	;save new m1
;
	ora	h	;check if done
	jnz	ndon
	pop	b	;done, return
	pop	d
	ret
;
 	;set k1=n1-m1
;
ndon:	xchg		;m1 to de
	lhld	n1
	mov	a,l
	sub	e
	mov	l,a
	mov	a,h
	sbb	d
	mov	h,a
	shld	k1
;			
	lxi	h,1	;set & save i=j=1
	shld	j1	
	shld	i1	
;			
	;calc & save addr offset = m1*l1
;			
	dcr	l
	pop	b	;len of str=l1
	push	b
lp1:	dad	d
	dcx	b
	mov	a,b
	ora	c
	jnz	lp1
 	shld	ml1
;
	xchg		;calc & save d(j), d(i), d(i+m)
	pop	b
	pop	h
	push	h
	push	b
lp2:	shld	dj1
	shld	di1
	xchg
	dad	d
	xchg		;hl has d(i), de has d(i+m>
;
	;compare strings & switch
;
cp1:	pop	b	;len of string=l1
	push	b
lp3:	ldax	d	;compare ea byte
	sub	m
	jnz	neq
	inx	h	;if = compare next byte
	inx	d
	dcx	b
	mov	a,b
	ora	c
	jnz	lp3
	jmp	nsw	;if done, don' t switch
;			
neq:	jnc	nsw	;if d(i)<d(i+m) don't sw
			;chance to jc for descendindg
;
sw:	push	b	;sw bytes not =
	mov	b,m
	ldax	d
	mov	m,a
	mov	a,b
	stax	d
	inx	h
	inx	d
	pop	b
	dcx	b
	mov	a,b
	ora	c
	jnz	sw
;
	;str switched, ck if i1-m1<1
;
	lhld	m1
	mov	a,h
	cma
	mov	d,a
	mov	a,l
	cma
	mov	e,a
	lhld	i1
	dad	d	;if i1-m1<1 then jump to same
	jnc	nsw	;as no switch
;
	;calc new d (i), d(i+m)
;
	inx	h	;save new i1=i1-m1
	shld	i1
	lhld	di1	;old d(i)=new d(i+m)
	xchg
	lhld	ml1	;addr offset
	mov	a,e	;new d(i)=old d(i)-offset
	sub	l
	mov	l,a
	mov	a,d
	sbb	h
	mov	h,a
	shld	di1	;save new d(i)
	jmp	cp1	;goto compare strings
;
	;ck for j>k			
;	
nsw:	lhld	j1
	inx	h	;save new j=old j+1
	shld	j1
	shld	i1
	xchg
	lhld	k1
	mov	a,l
	sub	e
	mov	a,h
	sbb	d
	jc	div	;if j>k goto beginning divide m1
;
	;calc new d(j), d(i)
;
	lhld	dj1
	pop	d
	push	d
	dad	d	;new d(j)=old d(j+1)
	xchg
	lhld	ml1	;addr offset
	xchg
	jmp     lp2

	end

