$mod51
$nosymbols
$nolist
$include(i51ctrl.inc)
$list
$include(i51hedr.inc)

	org	codeaddr
start:	jmp	main
$include(i51init.asm)		; initialization
$include(i51misc.asm)		; misc functions
$include(i51sprm.asm)		; parameters
$include(i51file.asm)		; file i/o routines
$include(i51strf.asm)		; string functions
$include(i51spck.asm)		; send packet
$include(i51rpck.asm)		; receive packet
$include(i51getv.asm)
$include(i51sakn.asm)

main:	call	initialize
;=========================================
RECV:	call	getvp		; get valid packet
	mov	a,TYP
	cjne	a,#'S',L2035
	sjmp	L2040
L2035:	mov	flags,#0ffh
	mov	dptr,#GDA
	mov	a,TYP
	movx	@dptr,a
	inc	dptr
	clr	a
	movx	@dptr,a
	call	strcat
	db	' Packet in S State',0
	jmp	L9500
;
; here on correct packet type
L2040:	mov	dptr,#pktdat
	call	strlen
	push	acc		; save packet length
;
; if pktlen > 4 then EOL=asc(mid$(pktdat,5,1) else EOL=13
	cjne	a,#4,L2042
L2042:	jc	L2044		; > 4
	mov	dpl,#4
	movx	a,@dptr
	unchar
	mov	EOL,a
	sjmp	L2050
L2044:	mov	EOL,#13		; <= 4
L2050:	pop	acc		; get packet length
; if pktlen > 5 then CTL=asc(mid$(pktdat,5,1) else CTL="#"
	cjne	a,#5,L2052
L2052:	jc	L2054
	mov	dpl,#5
	movx	a,@dptr
	mov	CTL,a
	sjmp	L2070
L2054:	mov	CTL,#'#'
; 
L2070:	mov	TYP,#'Y'
	call	send		; send local parameters

;=========================================
; get a File Header packet. If a B packet comes, we're all done
L3000:	call	getvp
	mov	a,TYP
	cjne	a,#'B',L3030
	call	sakn		; send acknowledge
	jmp	L9900
L3030:	cjne	a,#'F',L3035
	sjmp	L3040
L3035:	mov	dptr,#GDA	
	mov	a,TYP
	movx	@dptr,a
	inc	dptr
	clr	a
	movx	@dptr,a
	call	strcat
	db	' Packet in F State',0
	jmp	L9500
L3040:	call	fopen		; open the file
L3060:	call	sakn		; send acknowledge
;=========================================
; get data packets. If a Z packet comes, the file is complete.
L4000:	call	getvp
L4020:	mov	a,TYP
	cjne	a,#'Z',L4030
	call	fclose		; close the file
	call	sakn		; send acknowledge
	jmp	L3000
L4030:	cjne	a,#'D',L4035
	sjmp	L4040		; we have data !
L4035:	mov	dptr,#GDA	
	mov	a,TYP
	movx	@dptr,a
	inc	dptr
	clr	a
	movx	@dptr,a
	call	strcat
	db	' Packet in D State',0
	jmp	L9500
L4040:	call	fwrite		; write to file
L4060:	call	sakn		; send acknowledge
L4070:	jmp	L4000

; Error handler
L9000:	

;=========================================
; Error packet sender
L9500:	mov	dptr,#GDA
	call	strlen
	mov	TYP,#'E'
	call	spack		; send packet
; Normal exit point
L9900:	call	fclose
	jmp	sys_warm
;
;=========================================
;
$include(i51data.asm)		; ram data
;
	end

