 LIST P=10F200, R=DEC
 INCLUDE "p10F200.inc"

 __CONFIG _MCLRE_OFF & _CP_OFF & _WDT_OFF

 CBLOCK 0x10      				; data segment             
 delay:3
 ENDC

 ORG 0          				; code segment            	
	movwf	OSCCAL				; load calibrated value for OCS

	movlw	b'1011'				; preset initial port values after power on
	btfss	STATUS, GPWUF		; initialize port output for power on only
	 movwf	GPIO				; disconnect data lines and power off	
	clrw
	tris	GPIO				; configure GPIO<2:0> for output 
				
	btfss	STATUS, GPWUF		; was it on pin change reset?
	 goto	wait4press			; NO - wait

wait2sec						; we get here if the button is pressed
	movlw	b'10011111'			; re-enable weak pull-ups
	option
	movlw	10					; composing a 2 sec delay by calling 10 times
	movwf 	delay+2				; a 0.2 sec delay
	call	delay200
	decfsz	delay+2, f
	 goto	$-2	

	btfsc	GPIO, 3				; is button still pressed?
	 goto 	wait4press			; NO - ignore the last press
	
	btfss	GPIO, 0				; toggle the connection state
	 goto	disconnect

connect
	bcf		GPIO, 1				; connect power to output
	call	delay200			; short delay
	bcf		GPIO, 0				; connect data lines
	goto	wait4release

disconnect
	bsf		GPIO, 0				; disconnect data lines
	call	delay200
	bsf		GPIO, 1				; disconnect power

wait4release					; wait for button release
	clrf 	delay			
	clrf	delay+1

	btfss	GPIO, 3				; button released?
	 goto 	wait4release		; NO - wait for release
	incf	delay, f
	btfsc	STATUS, Z
	 incf	delay+1, f
	btfss	delay+1, 6			; 130 msec button debouncing delay
	 goto	$-6

wait4press						; wait for button press
	movlw	b'00011111'			; enable weak pull-ups and wake-up on change
	option
	movf	GPIO, w				; read input pins (required for wake-up on change)
	sleep						; CPU off, wait for button press reset
	nop
	
	movlw	b'0100'
	btfss	GPIO, 3
	 goto	wait2sec
	xorwf	GPIO, f
	goto	$-3

delay200						; 200 msec delay
	movlw	200					
	movwf	delay+1				;  data lines

	movlw	250					; this block provides a 1 msec delay
	movwf	delay	
	nop							; this loop takes 4 usec for
	decfsz	delay, f			; PIC @ 4 MHz
	 goto	$-2

	decfsz	delay+1, f	
	 goto	$-6
	retlw	0					; emulation of normal return

 ORG 0x00FF
	movlw	0x24
 end	  