.include "m328pdef.inc"
.dseg
.org 0x100
tabla: .byte 20
resultado: .byte 1

.cseg
.equ tamtabla=6
.def resultlow=r2
.def resulthigh=r3
.def dividendol=r17
.def dividendoh=r18
.def divisorl=r19
.def divisorh=r20
.def cocientel=r24
.def cocienteh=r25
.def restol=r21
.def restoh=r22

	ldi xh,high(tabla)
	ldi xl,low(tabla)
	ldi zh,high(2*tablatemp)
	ldi zl,low(2*tablatemp)
			

			push xh
			push xl
    		ldi r16,tamtabla
copiatabla:	lpm r0,z+
			lpm r1,z+
			st x+,r0
			st x+,r1
			dec r16
			brne copiatabla
			pop xl
			pop xh

;pongo en r0 y r1 cada dato y le cambio el signo si procede

		ldi r17,tamtabla
suma:	ld r0,x+
		ld r1,x+
		sbrc r1,7
		call cambiasig
		add resultlow,r0
		adc resulthigh,r1
		dec r17
		brne suma
		
		mov dividendoh,resulthigh
		mov dividendol,resultlow
		ldi divisorh,0
		ldi divisorl,20
		call divide
		mov resulthigh,cocienteh
		mov resultlow,cocientel
fin: 	jmp fin
		
		
cambiasig:	mov r16,r0
			andi r16,$ff
			brne algununo
			neg r1
			ret
algununo:	neg r0
			com r1
			ret
			
divide: 	clr cocienteh
			clr cocientel
			mov	restoh,dividendoh
			mov restol,dividendol
siguediv:	sub restol,divisorl
			sbc restoh,divisorh
			brlt findiv
			adiw cocienteh:cocientel,1
			jmp siguediv
findiv: 	add restol,divisorl
			adc restoh,divisorh
			ret

				

	  
tablatemp: .dw 2,-1,-4,-250, 25,50


; Divide palabra entre palabra
