function [] = cmos_inverter(kn, kp, vtn, vtp, data)
% cmos_inverter(kn, kp, vtn, vtp, data)
% the data is (are?) taken from the SPICE simulations
% Inverter Transfer Characteristic
% Written by Adem Kader, David Luong, Mark Piper
% November 26, 2005

% circuit parameters
vdd = 5;
kr = kn/kp;
vth = (vtn + sqrt(1/kr)*(vdd + abs(vtp)))/(1 + sqrt(1/kr));
% assume Wn/Ln = Wp/Lp
WLn = (1.106e-3)/(7.8e-6);
WLp = WLn;

vin=0:0.001:5;
vout=vin;

for i = 1:1:5001,
    if(vin(i) < vtn)
        vout(i) = vdd;
    elseif ( (vin(i) >= vtn) && (vin(i) <= vth))
        A = 1;
        B = -2*(vin(i)- abs(vtp));
        C = kr*WLn/WLp*(vin(i)- vtn)^2 + 2*(vin(i)- vdd - abs(vtp))* vdd + vdd^2;
       vout(i) = (-B + sqrt(B^2-4*A*C))/(2*A);
    elseif ( (vin(i) > vth) && (vin(i) < vdd + vtp))
        A = kn*WLn;
        B = -2*kn*WLn*(vin(i) - vtn);
        C = kp*WLn*(vin(i)-vdd-vtp)^2;
        vout(i) = (-B - sqrt(B^2-4*A*C))/(2*A);  
    else
        vout(i) = 0;
    end
end

plot(vin,vout);
axis([0 5 0 vdd+0.1]);
hold on

for j=1:1:501, 
    datain(j)=data(j,3); 
    dataout(j)=data(j,4); 
end

plot(datain, dataout,'r');

axis([0 5 0 vdd+0.1]);
adem =[0	4.97;
0.48	4.97;
0.78	4.92;
1.38	4.47;
1.67	3.97;
1.83	3.41;
1.92	2.61;
2	0.97;
2.26	0.46;
2.5	0.29;
2.85	0.17;
3.5	0.04;
4.97	0];

for k=1:1:13, ademin(k)=adem(k,1); ademout(k)=adem(k,2); end

plot(ademin, ademout, 'g');
legend('theoretical','simulation','experimental')
xlabel('V_i_n (V)')
ylabel('V_o_u_t (V)')
title(sprintf('Inverter Transfer Characteristics \nComparison of theoretical, simulation and experimental values'))
