; This program counts how many bits of the SWITCHES are set
; and outputs it in the 7 Segment Display

; For example: If switches are: 10101010
; There are 4 bits set (4 bits are 1)
; So the output in the LEDs will be: 00000100 (= 4 in dec).

BIT_COUNTER EQU B ; BIT_COUNTER will be Register B
BITS_LEFT EQU C ; How many bits we have left will be Register C

TEMP EQU D ; Temporary, so we can do calculations on accumulator
		   ; But keeping its value

SWITCHES EQU 20H ; Switches are at location 20H

START:

IN SWITCHES ; Get value of switches

MVI BIT_COUNTER,00H ; We start at 0
MVI BITS_LEFT,08H ; We are starting with 8 bits left

LOOP:
	MOV TEMP,A ; Save A

	ANI 00000001B ; Only keep LSB
	CPI 01 ; Is it 1?
	
	JNZ CONTINUE ; If not, CONTINUE
	
	INR BIT_COUNTER ; If yes, increase BIT_COUNTER
	
CONTINUE:

	MOV A,TEMP ; Get our A back
	RLC ; Rotate left, that way we go to our next bit.
	
	DCR BITS_LEFT ; Decrease BITS_LEFT because we just calculated one.
	JNZ LOOP ; If BITS_LEFT is NOT 0, we go to our LOOP again.
	
	
MOV A,BIT_COUNTER ; Get BIT_COUNTER to A
STA 0905H ; Arbitary memory location

LXI D,0900H ; So we can tell STDM where we saved it
; We go to 0900H instead of 0905H so that the result is the last number.

CALL STDM ; Moves memory location 0900H - 0905H to where 7 Segment Display can see it
; (The starting address of 0900H is according to double register DE)

CALL DCD ; Show it in the 7 segment display
	
JMP START ; Go to START and keep going forever