/* *****

        Operative System for MIPS Written by Filip Ekberg at the Blekinge Institute Of Technology
        Contact: Filip@SmartIT.se

*** */

#include <iregdef.h>
#include <idtcpu.h>
        .text
        .globl  External
	.globl	Clock
/* *************************************************************************
        External Handler
		This code handles external exceptions,
		in our case a panel with buttons and a repeating exception

		If you read from 0xbf900000 you will get the value from how many "Pins" are on / off
		If you write to the same address 0xbf900000 you will output the value to the diods
************************************************************************* */
		.data
Clock: 		.word	0				// This is our counter
		.text
External: 
		mfc0	t0, C0_CAUSE			// We could aswell use 24(sp) to load CAUSE
		and	t0, t0, 0x02000			// Mask the CAUSE
		bnez	t0, Puls			// If the only character left is "not equal zero" jump to Puls

		j 	DisMiss				// Else jump to DisMiss
		
Puls:
		la	t0, 0xbfa00000			// Load the panel
		sb	zero, 0(t0)			// Send an "Ack" to the panel, THIS IS IMPORTANT, if you do not do this first, you will not be able to load anything.
		lb	t0, 0(t0)			// Load the 8 bits ( 1 Byte )
		and	t0, t0, 7			// We have a slot in which we are only interested in the last 3 positions (1, 2, 4) so mask the 7 first
		beq	t0, 1, Right			// If the value after the mask is 1 this means we pressed the Right button
		beq	t0, 2, Left			// If the value after the mask is 2 this means we pressed the Left button
		beq	t0, 4, Repeating		// Finaly if the value after the mask is 4 it's the repeating exception

		j	DisMiss				// Else just jump to dismiss

Left:
		la	t0, 0xbf900000			// Load the address
		lb	t1, 0(t0)			// Load the byte, hence its only 8 bits, 8 pins and 8 diods
		sb	t1, 0(t0)			// Save it to the same address, this will actually load the value from the pins and save it to the diods

		j	DisMiss				// Jump dismiss
Right:
		la      t0, Clock			// Load the address to the Clock
                lw      t1, 0(t0)			// Load the value in Clock
		la	t2, 0xbf900000			// Load the address to the diods
		sb	t1, 0(t2)			// Save ONE BYTE from the Clock to the diods, this means if the Clock number is greater than 1 byte it will just take the last byte and output it

		j	DisMiss				// Jump dismiss

Repeating:
		la	t0, Clock			// Load the address to the Clock
		lw	t1, 0(t0)			// Load the value
		addi	t1, 1				// Add 1 to the value
		sw	t1, 0(t0)			// Save the value to the Clock

		j	DisMiss				// Jump dismiss
