% Simple example of computer aided design (by Rowland Sammut and Claude Sammut)

% Design(LogicalExpression) will take logical expression and turn it into
% an equivalent expression using only nand's. This expression is then
% converted into a cicut desrciption suitable for use in an automatic
% wire-wrap machine.


op(700, xfx, =>)!
op(600, yfx, v)!
op(500, yfx, ^)!
op(400, fx, ~)!

translate(X, Y) :- 
	trans(X, A),
	terminate(X, A, Y).

trans(~A, nand(B, B)) :- !, translate(A, B).
trans(nand(nand(B, B), nand(B, B)), B):- !.
trans(A => B, nand(C, nand(D, D))) :- !,
	translate(A, C),
	translate(B, D).
trans(A ^ B, nand(nand(C, D), nand(C, D))) :- !,
	translate(A, C),
	translate(B, D).
trans(A v B, nand(nand(C, C), nand(D, D))) :- !,
	translate(A, C),
	translate(B, D).
trans(nand(A, B), nand(C, D)) :- !,
	translate(A, C),
	translate(B, D).
trans(A, A).

terminate(X, X, X) :- !.
terminate(X, Y, Z) :- translate(Y, Z).


wirit(nand(A, B), gate(M)/out, N, M) :- !,
	wirit(A, OutA, N, NA),
	wirit(B, OutB, NA, NB),
	M is NB + 1,
	print_nand(M, OutA, OutB).
wirit(X, X, N, N).

print_nand(GateNumber, Input1, Input2) :-
	print(gate(GateNumber), '	7400'),
	print('	in(1)	', Input1),
	print('	in(2)	', Input2).

design(X) :-
	translate(X, Y),
	wirit(Y, Final, 0, _),
	print('\nfinal	', Final).
