#!/usr/bin/python
import fileinput
import RPi.GPIO as GPIO
import sys
from math import pow
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(16, GPIO.IN)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.output(12,GPIO.HIGH)
GPIO.output(25,GPIO.HIGH)



def setadr( address ):
	lst = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
	for x in range (0,16):
		GPIO.output(24,GPIO.LOW)
		x = int(x)
		y = int(pow(2,x));
		a = int(address)
		b = (y & a)
		if (b > 0):
			GPIO.output(23,GPIO.HIGH)
			lst[x] = 1
		else:
			GPIO.output(23,GPIO.LOW)
			lst[x] = 0
		GPIO.output(24,GPIO.HIGH)
#	print "Address: ", address ," Binary: ",str(list(reversed(lst)))


def setdata( value ):
	lst = [0,0,0,0,0,0,0,0]
	for x in range (0,8):
		GPIO.output(21,GPIO.LOW)
		x = int(x)
		y = int(pow(2,x));
		a = int(value)
		b = (y & a)
		if (b > 0):
			GPIO.output(20,GPIO.HIGH)
			lst[x] = 1
		else:
			GPIO.output(20,GPIO.LOW)
			lst[x] = 0
		GPIO.output(21,GPIO.HIGH)
#	print "Value:   ",value," Binary: ",str(list(reversed(lst)))


def getdata ():
	GPIO.output(17,GPIO.LOW)
	GPIO.output(17,GPIO.HIGH)
	val = 0
	lst = [0,0,0,0,0,0,0,0]
	for x in range (0,8):
		bit = 0
		x = int(x)
		y = int(pow(2,x));
		if GPIO.input(16):
			val = val + y
			lst[x] = 1
		else:
			lst[x] = 0
		GPIO.output(4,GPIO.LOW)
		GPIO.output(4,GPIO.HIGH)
#	print "Value:   ",val," Binary: ",str(list(reversed(lst)))
	return val


def setEEPROM(address,value):
	setadr(address)
	setdata(value)
	GPIO.output(25,GPIO.HIGH)
	GPIO.output(12,GPIO.LOW)
	sleep(0.01)
	GPIO.output(12,GPIO.HIGH)
	sleep(0.01)

def readEEPROM(address):
	setadr(address)
	GPIO.output(25,GPIO.LOW)
	sleep(0.01)
	val = getdata()
	GPIO.output(25,GPIO.HIGH)
	return val

def readall():
	for y in range (0,256):
		res = [0,0,0,0,0,0,0,0]
		for x in range (0,8):
			ad = x + y * 8
			r = readEEPROM(ad)
			res[x] = '{:02X}'.format(r)
		base = y*8
		print "Addr: ",'{:03X}'.format(base)," - ",base," - ",str(res)

if len(sys.argv) > 2:
	setEEPROM(sys.argv[1],sys.argv[2])
if len(sys.argv) > 1:
	print readEEPROM(sys.argv[1])
	exit()

for line in fileinput.input():
	x = line.split()
	setEEPROM(x[0],x[1])

readall()

