function [Vinstar,Iinstar,Pinwattsstar,RPMstar,PoutHP,EtaMotorMax,ifig]=MotorMaxEff(Poutwatts,Kv,Kt,R,Io,ifig)
% function [Vinstar,Iinstar,Pinwattsstar,RPMstar,PoutHP,EtaMotorMax,ifig]=MotorMaxEff(Poutwatts,Kv,Kt,R,Io,ifig)
% Computes Vinstar(volts), Iinstar(amps) from Poutwatts(watts) assuming that the 
% motor is running at the conditions for maximum efficiency.
%   Iin=sqrt(Io*Vin/R)
%
% Requires motor constants Kv,Kt,R,Io.
%   Kv= RPM/volt
%   Kt= inch-ounce per ampere
%   R= Ohms
%   Io= amperes
%
% Additional outputs include
%   Pinwattsstar =input power (watts)
%   RPMstar =RPM for motor running at most efficient conditions.
%   PoutHP =output power in HP
%   EtaMotorMax =maximum motor efficiency (non-dimensional)
%
% ifig in the current figure number and is updated if a figure is plotted.

Vinmat=1:.1:20;             % lets vary voltage over this range (volt)
Iinmat=sqrt(Io*Vinmat/R);   % current for max efficiency at Vinmat (amp)
Poutmat=(Iinmat-Io).*(Vinmat-Iinmat*R); % power at max efficiency conditions (watts)
% 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');  % finds voltage for appropriate amount of power (volts)
% The above solution technique solves for Vinstar using a graphical
% technique (table lookup).
Poutwatts2=interp1(Vinmat,Poutmat,Vinstar,'spline'); % double check (watts)
% 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); % triple check (watts)
PoutHP=Poutwatts/745.7; % hp
EtaMotorMax=((Iinstar-Io)/Iinstar)^2; % non-dimensional
RPMstar=Kv*(Vinstar-Iinstar*R); % RPM
