function [Vinstar,Iinstar,Pinwattsstar,RPMstar,PoutHP,EtaMotorMax,ifig]=MotorMaxEff(Poutwatts,Kv,Kt,R,Io,ifig)
Vinmat=1:.1:20;
Iinmat=sqrt(Io*Vinmat/R);
Poutmat=(Iinmat-Io).*(Vinmat-Iinmat*R);
% Poutmat2=sqrt(Io/R)*Vinmat.^(3/2)-2*Io*Vinmat-sqrt(Io^3*R)*Vinmat.^.5; % this has a bug in it
% ifig=ifig+1; figure(ifig)
% plot(Poutmat,Vinmat)
% hold on; plot(Poutmat2,Vinmat,':'); hold off
% xlabel('Power output (watts)')
% ylabel('Input voltage (volts)')
% title('Motor performance for maxmum efficiency')
% YI = INTERP1(X,Y,XI,'spline')
Vinstar=interp1(Poutmat,Vinmat,Poutwatts,'spline');
Poutwatts2=interp1(Vinmat,Poutmat,Vinstar,'spline');
% hold on
% plot([Poutwatts,Poutwatts],[0,Vinstar],'r:',[0,Poutwatts],[Vinstar,Vinstar],':')
% hold off
Iinstar=sqrt(Io*Vinstar/R);   % Input current in amperes
Pinwattsstar=Iinstar*Vinstar; % Input power in watts
Poutwatts3=(Iinstar-Io)*(Vinstar-Iinstar*R);
PoutHP=Poutwatts/745.7;
EtaMotorMax=((Iinstar-Io)/Iinstar)^2;
RPMstar=Kv*(Vinstar-Iinstar*R);
