function [Objectives, motorProps, Objectives_pareto, Userdata] = evalDesigns_SMPMSM_example2(motorProps,settingsMagnetostatic,file,maxNumberOfProcesses,designParams,msg0,Userdata)
% designFunction for surface-mounted permanent magnet synchronous machine designs evaluation

initCurrent = Userdata.initCurrent;                         % initial current value (1 turn, no parallel paths)
if isempty(initCurrent)
    initCurrent=1;
end
targetSpeed = abs(Userdata.targetSpeed);                    % RPM
targetPower = abs(Userdata.targetPower)*1000;               % W
coilFillFactor = Userdata.coilFillFactor;                   % coil fill factor
machineMode = Userdata.machineMode;                         % either 'motor' or 'generator'

targetTorque = targetPower/(targetSpeed*2*pi/60);           % N*m
tic
% designParams = round(designParams*10000)/10000;   % use only 4 digits after point
nDesigns = size(designParams,1);

% Default Geometry setup
% motorProps=setParampm(motorProps,'Number Of Slots',54);
% motorProps=setParampm(motorProps,'Number Of Pole Pairs',31);
motorProps=setParampm(motorProps,'Stator Skew Angle',0);
motorProps=setParampm(motorProps,'Rotor Skew Angle',0);
% motorProps=setParampm(motorProps,'Number Of Magnet Segments',1);
motorProps=setParampm(motorProps,'Slot Bottom Corner Type','General');
motorProps=setParampm(motorProps,'Bottom Corner Radius',0);
motorProps=setParampm(motorProps,'Top Corner Radius',0);
motorProps = setParampm(motorProps,'Slot Opening Depth',0);
motorProps = setParampm(motorProps,'Slot Opening Width',0);
motorProps = setParampm(motorProps,'Tooth Tip Angle',20);
motorProps=setParampm(motorProps,'Tooth Edge Chamfer Depth',0);
motorProps=setParampm(motorProps,'Tooth Edge Chamfer Ratio',0);
motorProps=setParampm(motorProps,'Tooth Edge Chamfer Angle',0);
motorProps=setParampm(motorProps,'Slot Insulation Thickness',0);
motorProps=setParampm(motorProps,'Between Layers Insulation Thickness',0);
motorProps=setParampm(motorProps,'Magnet Fillet Radius',0);
motorProps=setParampm(motorProps,'Magnet Inset Depth',0);
motorProps=setParampm(motorProps,'Magnet Magnetization','Radial');
motorProps=setParampm(motorProps,'Retaining Sleeve Type','Non-conductive or no retaining sleeve');
motorProps=setParampm(motorProps,'Retaining Sleeve Thickness',0);

% Default Winding setup
motorProps=setParampm(motorProps,'Wire size method','Fill factor');
motorProps=setParampm(motorProps,'Coil fill factor',coilFillFactor);      % keep the same coil fill factor for all the designs
motorProps=setParampm(motorProps,'Number Of Parallel Paths',1);           % set number of parallel paths to 1
motorProps=setParampm(motorProps,'Number Of Turns',1);                    % set number of turns to 1 (winding losses do not depend on number of turns)
motorProps=setParampm(motorProps,'End Winding Inductance','Auto');
motorProps=setParampm(motorProps,'Phase Resistance','Auto');
motorProps=setParampm(motorProps,'End Winding Axial Overhang','Auto');
% motorProps=setParampm(motorProps,'Coil Span','Auto');
% motorProps=setParampm(motorProps,'Winding Layers Orientation','Left/Right');
% motorProps=setParampm(motorProps,'Winding Layout Method','Automatic');
motorProps=setParampm(motorProps,'Number Of Strands In Hand',1);
% motorProps=setParampm(motorProps,'Winding Layers','Double layer');
% motorProps=setParampm(motorProps,'Winding Connection','StarConnection');
% motorProps=setParampm(motorProps,'Strand Diameter',0.5);
% motorProps=setParampm(motorProps,'Wire Gauge Number','22 AWG');

% Default Mesh setup
motorProps=setParampm(motorProps,'Air Gap Mesh Quality','Medium');
motorProps=setParampm(motorProps,'Maximum Triangle Side','Auto');
motorProps=setParampm(motorProps,'Number Of Layers In Air Gap',3);
motorProps=setParampm(motorProps,'Number Of Slices',1);
motorProps=setParampm(motorProps,'Boundary Conditions','Auto');

if nargout==2
    % return only "motorProps" structure for saving to mxp-file from the Pareto plot
    motorProps = getMotorProps(motorProps,designParams,Userdata,1);
    Objectives = [];
    return
end
%%% assemble all designs first
cell_Geometry_ready = cell(nDesigns,1);
cell_Windings_ready = cell(nDesigns,1);
cell_Mesh_ready = cell(nDesigns,1);
cell_Materials_ready = cell(nDesigns,1);
cell_SubdomainProperty_ready = cell(nDesigns,1);
cell_Error_ready = cell(nDesigns,1);
cell_motorProps_output_ready = cell(nDesigns,1);
cell_Weight_ready = cell(nDesigns,1);
numberOfProcesses = 0; % current number of processes
i = 1;  % design number
% tic
initAssembleMXP_par();  % init design assembling in parallel
msg = [msg0 ' assembling designs...)']; disp(msg);
% keep number of processes equal to maxNumberOfProcesses
while 1
    if numberOfProcesses<maxNumberOfProcesses
        motorProps = getMotorProps(motorProps,designParams,Userdata,i);
        fprintf('%s assemble design #%i\n', msg, i);
        % assemble design in parallel - add one process
        runAssembleMXP_par(file, motorProps);
        numberOfProcesses = numberOfProcesses+1;
        i = i+1;
    end
    if numberOfProcesses==maxNumberOfProcesses
        % wait when one of processes finish assembling design
        while 1
            % check if any design(s) are already assembled
            [cell_Geometry, cell_Windings, cell_Mesh, cell_Materials, cell_SubdomainProperty,...
                cell_Error, cell_motorProps_output, cell_Weight, numberOfProcesses] = ...
                    getAssembleMXP_par();   % get assembled design(s)
            if numberOfProcesses<maxNumberOfProcesses
                break;
            end
            pause(1); % wait for 1 second
        end
        % put assembled design(s)
        for n = 1:length(cell_motorProps_output)
            if ~isempty(cell_motorProps_output{n})
                cell_Geometry_ready{n} = cell_Geometry{n};
                cell_Windings_ready{n} = cell_Windings{n};
                cell_Mesh_ready{n} = cell_Mesh{n};
                cell_Materials_ready{n} = cell_Materials{n};
                cell_SubdomainProperty_ready{n} = cell_SubdomainProperty{n};
                cell_Error_ready{n} = cell_Error{n};
                cell_motorProps_output_ready{n} = cell_motorProps_output{n};
                cell_Weight_ready{n} = cell_Weight{n};
            end
        end
    end
    if i>nDesigns
        break
    end
end

% get all (the rest) designs
numberOfProcesses0 = numberOfProcesses;
while numberOfProcesses>0
    % check if any design(s) are finished assembling
    [cell_Geometry, cell_Windings, cell_Mesh, cell_Materials, cell_SubdomainProperty,...
        cell_Error, cell_motorProps_output, cell_Weight, numberOfProcesses] = ...
        	getAssembleMXP_par();   % get assembled design(s)
    if numberOfProcesses~=numberOfProcesses0  % if new design(s) are finished assembling (number of processes changed)
        % put assembled design(s)
        for n = 1:length(cell_motorProps_output)
            if ~isempty(cell_motorProps_output{n})
                cell_Geometry_ready{n} = cell_Geometry{n};
                cell_Windings_ready{n} = cell_Windings{n};
                cell_Mesh_ready{n} = cell_Mesh{n};
                cell_Materials_ready{n} = cell_Materials{n};
                cell_SubdomainProperty_ready{n} = cell_SubdomainProperty{n};
                cell_Error_ready{n} = cell_Error{n};
                cell_motorProps_output_ready{n} = cell_motorProps_output{n};
                cell_Weight_ready{n} = cell_Weight{n};
            end
        end
        numberOfProcesses0 = numberOfProcesses;
    end
    pause(1); % wait for 1 second
end
% check if any design failed assembling and try again
for i = 1:nDesigns
    if isempty(cell_Geometry_ready{i}) || ~isempty(cell_Error_ready{i})
        motorProps = getMotorProps(motorProps,designParams,Userdata,i);
        try
            [Geometry, Windings, Mesh, Materials, SubdomainProperty, Error, motorProps_output, Weight] = assembleMXP(file,motorProps);
        catch ME
           rethrow(ME)
        end
        if isempty(Geometry)
            cell_Error_ready{i} = 'Unknown error';
        else
            cell_Geometry_ready{i} = Geometry;
            cell_Windings_ready{i} = Windings;
            cell_Mesh_ready{i} = Mesh;
            cell_Materials_ready{i} = Materials;
            cell_SubdomainProperty_ready{i} = SubdomainProperty;
            cell_Error_ready{i} = Error;
            cell_motorProps_output_ready{i} = motorProps_output;
            cell_Weight_ready{i} = Weight;
        end
    end
end
% toc
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Save each step solution',0);
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Compute cogging torque',0);
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Convergence tolerance',0.01);
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Current waveform','Sinusoidal');
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Mechanical speed',targetSpeed);           % RPM
if strcmp(machineMode,'motor')
    settingsMagnetostatic=setParampm(settingsMagnetostatic,'Advance angle',0);           % motor mode 
elseif strcmp(machineMode,'generator')
    settingsMagnetostatic=setParampm(settingsMagnetostatic,'Advance angle',180);         % generator mode 
end
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Simulation time','One electrical period');
settingsMagnetostatic=setParampm(settingsMagnetostatic,'RMS supply current',initCurrent);     
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Number of points',1);
speed = targetSpeed*2*pi/60;      % rad/s
arr_Current = initCurrent*ones(nDesigns,1);
arr_Current_prev = arr_Current;
arr_Torque = zeros(nDesigns,1);
if strcmp(machineMode,'generator')
    arr_Rs = zeros(nDesigns,1);                      % stator winding resistance
    D = zeros(nDesigns,1);
end
arr_Torque_eachiter=[];
arr_Current_eachiter=[];
arr_OutputElectricalPower_eachiter=[];
arr_OutputElectricalPower = zeros(nDesigns,1);
enableRun = ones(nDesigns,1);
enableRun=logical(enableRun);
for n = 1:nDesigns
    if ~isempty(cell_Error_ready{n})
        enableRun(n) = 0;
    end
end

% Determine current required to produce target torque for each design
msg = [msg0 ' calculating stator currents...)']; disp(msg);
iter = 1;
cell_Private_ready = cell(nDesigns,1);
while 1
    [cell_Results, cell_Timesteppingdata, cell_Private] = ...
        runMStimestepping_batch(cell_Private_ready,cell_Geometry_ready,cell_Windings_ready,cell_Mesh_ready,cell_Materials_ready,cell_SubdomainProperty_ready,cell_Error_ready,...
                                settingsMagnetostatic,arr_Current,enableRun,maxNumberOfProcesses,msg);
    for n = 1:length(cell_Results)
        if enableRun(n)
            if isempty(cell_Results{n})
                error(['Simulation results for design #' num2str(n) ' are empty (1)']);
            end
            if arr_Current(n)>arr_Current_prev(n) && abs(cell_Results{n}.torque)<arr_Torque(n)
                % if current increases, but torque decreases (saturation is extremely high,
                % so the FEA-DQ method does not work correctly - bad design anyways)
                enableRun(n) = 0;   % stop current iterations for this design
                % arr_Current(n) = arr_Current_prev(n);   % keep previous current
            else
                if strcmp(machineMode,'motor')
                    arr_Torque(n) = cell_Results{n}.torque;          % motor mode 
                    if 100*abs((arr_Torque(n)-targetTorque)/targetTorque)<1          % 1% torque error tolerance
                        enableRun(n) = 0;
                    end
                elseif strcmp(machineMode,'generator')
                    if iter==1
                        arr_Rs(n) = cell_Results{n}.Ps/(arr_Current(n)^2);
                    end
                    arr_Torque(n) = -cell_Results{n}.torque;          % - keep torque positive (generator mode)
                    arr_OutputElectricalPower(n) = -(cell_Results{n}.Pmech + cell_Results{n}.Ps);
                    if 100*abs((arr_OutputElectricalPower(n)-targetPower)/targetPower)<1          % 1% power error tolerance
                        enableRun(n) = 0;
                    else
                        k = arr_Torque(n)./arr_Current(n);
                        D(n) = (k*speed)^2-4*arr_Rs(n)*targetPower;
                    end
                end
            end
            if isempty(cell_Private_ready{n})
                cell_Private_ready{n} = cell_Private{n};
            end
        end
    end
    arr_Torque_eachiter=[arr_Torque_eachiter arr_Torque];
    arr_Current_eachiter=[arr_Current_eachiter arr_Current];
    arr_OutputElectricalPower_eachiter=[arr_OutputElectricalPower_eachiter arr_OutputElectricalPower];
    arr_Current_prev = arr_Current;
    if any(enableRun)
        if strcmp(machineMode,'motor')
            arr_Current(enableRun) = (targetTorque./arr_Torque(enableRun)).*arr_Current(enableRun);
        elseif strcmp(machineMode,'generator')    
            K = arr_Torque./arr_Current;
            for n = 1:length(cell_Results)
                if enableRun(n)
                    if D(n)>=0
                        I1 = (K(n)*speed+sqrt(D(n)))/(2*arr_Rs(n));
                        I2 = (K(n)*speed-sqrt(D(n)))/(2*arr_Rs(n));
                        if I2>=0
                            arr_Current(n) = I2;
                        else
                            arr_Current(n) = I1;
                        end
                    else
                        arr_Current(n) = arr_Current(n)/2;   % reduce current
                    end
                end
            end
        end
    else
        break
    end
    iter = iter+1;
    if iter>7
        break
    end
end
% run magnetostatic simulation for 6 points and 1/6th of electrical period
speed = getParampm(settingsMagnetostatic,'Mechanical speed')*2*pi/60;      % rad/s
nPolePairs = getParampm(motorProps,'Number of pole pairs');                % Number of pole pairs
Ns = getParampm(motorProps,'Number Of Slots');                             % Number of stator slots
f1 = speed*nPolePairs/(2*pi);                                              % supply frequency
T1 = 1/f1;
numberOfRotorPositions = setNumberOfPoints('Low accuracy',nPolePairs,Ns);
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Simulation time','One electrical period');
settingsMagnetostatic=setParampm(settingsMagnetostatic,'Number of points',numberOfRotorPositions);
% settingsMagnetostatic=setParampm(settingsMagnetostatic,'Simulation time','Define time interval');
% settingsMagnetostatic=setParampm(settingsMagnetostatic,'Time from',0);
% settingsMagnetostatic=setParampm(settingsMagnetostatic,'Time to',T1/6);    % 1/6th of electrical period
enableRun = ones(nDesigns,1);
for n = 1:nDesigns
    if ~isempty(cell_Error_ready{n})
        enableRun(n) = 0;
    end
end
if strcmp(machineMode,'generator')
    for n = 1:nDesigns
        if D(n)<0
            % if design is not able to generate the targer electrical power "targetPower"
            enableRun(n) = 0;
        end
    end
end
msg = [msg0 ' running simulations...)']; disp(msg);
[cell_Results, cell_Timesteppingdata, cell_Private] = ...
        runMStimestepping_batch(cell_Private_ready,cell_Geometry_ready,cell_Windings_ready,cell_Mesh_ready,cell_Materials_ready,cell_SubdomainProperty_ready,cell_Error_ready,...
                                settingsMagnetostatic,arr_Current,enableRun,maxNumberOfProcesses,msg);
motorWeight = NaN*ones(nDesigns,1);
motorLoss = NaN*ones(nDesigns,1); 
motorLoss_norm = NaN*ones(nDesigns,1);   % normalized to the same mechanical power
motorTorque = NaN*ones(nDesigns,1); 
motorEfficiency = NaN*ones(nDesigns,1); 
% one_minus_PowerFactor = NaN*ones(nDesigns,1); 
for n=1:nDesigns  
    Results = cell_Results{n};
    if enableRun(n)
        if isempty(Results)
            error(['Simulation results for design #' num2str(n) ' are empty (2)'])
        end
        Weight = cell_Weight_ready{n};
        motorWeight(n) = Weight.statoriron + Weight.rotoriron + Weight.statorwinding + Weight.magnet + Weight.conductor;
        motorLoss(n) = Results.Ps + Results.Piron_hyst + Results.Piron_eddy + Results.MagnetLoss + Results.OtherECloss;
        motorTorque(n) = Results.torque;
        if strcmp(machineMode,'motor')
            motorEfficiency(n) = Results.Pmech/(Results.Pmech+motorLoss(n));            % motor mode
        elseif strcmp(machineMode,'generator')    
            motorEfficiency(n) = (Results.Pmech+motorLoss(n))/Results.Pmech;            % generator mode
        end
        motorLoss_norm(n) = (targetPower*(1-motorEfficiency(n)))/motorEfficiency(n);
        if motorLoss_norm(n)<0
            motorLoss_norm(n) = Userdata.errLoss;
        end
    end
end
penaltyLossThreshold = Userdata.penaltyLossThreshold;       % penalty loss threshold
motorWeight_penalized = motorWeight;
for n=1:nDesigns  
    if motorLoss_norm(n)>penaltyLossThreshold
        % Penalize design if losses exceed the penalty loss threshold - increase the design weight
        penaltyCoef = (motorLoss_norm(n)-penaltyLossThreshold)/targetPower+1;  % penalty coefficient is proportional to degree of violation
        motorWeight_penalized(n) = motorWeight(n)*penaltyCoef;
    end
end
Objectives = [1000*motorWeight_penalized motorLoss_norm arr_Current zeros(nDesigns,1)];         % [Weight_penalized(grams), Losses(W), Current(A), Error]
Objectives_pareto = [1000*motorWeight motorLoss_norm arr_Current zeros(nDesigns,1)];            % [Weight(grams), Losses(W), Current(A), Error]
toc
for n=1:nDesigns  
    if isnan(Objectives(n,1))
        % if there was an error while assembling the design
        Objectives(n,1) = Userdata.errWeight;
        Objectives(n,2) = Userdata.errLoss;
        Objectives(n,3) = 0;
        Objectives(n,4) = 1;
        Objectives_pareto(n,1) = Userdata.errWeight;
        Objectives_pareto(n,2) = Userdata.errLoss;
        Objectives_pareto(n,3) = 0;
        Objectives_pareto(n,4) = 1;
    end
end
if any(any(isnan(Objectives)))
    error('result is NaN');
end
if any(any(isinf(Objectives)))
    error('result is Inf');
end
end

%________________________________________________________________________________________________________________________


function [cell_Results_ready, cell_Timesteppingdata_ready, cell_Private_output] = ...
    runMStimestepping_batch(cell_Private_input,cell_Geometry,cell_Windings,cell_Mesh,cell_Materials,cell_SubdomainProperty,cell_Error,...
                            settingsMagnetostatic,arr_Current,enableRun,maxNumberOfProcesses,msg)
%%% run magnetostatic FE simulations for "nDesigns" designs in parallel
nDesigns = length(arr_Current);
cell_Results_ready = cell(nDesigns,1);
cell_Timesteppingdata_ready = cell(nDesigns,1);
cell_Private_output = cell(nDesigns,1);
numberOfProcesses = 0; % current number of processes
i = 1;
initMStimestepping_par(); % init running magnetostatic FE simulations in parallel
% keep number of processes equal to maxNumberOfProcesses
while 1
    if numberOfProcesses<maxNumberOfProcesses
        Geometry = cell_Geometry{i};
        Windings = cell_Windings{i};
        Mesh = cell_Mesh{i};
        Materials = cell_Materials{i};
        SubdomainProperty = cell_SubdomainProperty{i};
        Error = cell_Error{i};
        if ~isempty(cell_Private_input{i})
            Private = cell_Private_input{i};
        else
            Private = [];
        end
        if isempty(Error) && enableRun(i) % && cmpstruct(motorProps,motorProps_output)
            settingsMagnetostatic=setParampm(settingsMagnetostatic,'RMS supply current',arr_Current(i));
            fprintf('%s run simulation #%i\n', msg, i);
            % run magnetostatic FE simulation in parallel - add one process
            runMStimestepping_par(Private,Geometry,Mesh,Windings,settingsMagnetostatic,Materials,SubdomainProperty,[]);
            numberOfProcesses = numberOfProcesses+1;
        end
        i = i+1;
    end
    if numberOfProcesses == maxNumberOfProcesses
        % wait when one of processes finish calculation
        while 1
            % check if any results are ready
            [cell_Results, cell_Timesteppingdata, ~, cell_Private, numberOfProcesses] = getMStimestepping_par();   % get magnetostatic analysis results
            if numberOfProcesses<maxNumberOfProcesses
                break;
            end
            pause(1); % wait for 1 second
        end
        % put results
        k = 1;
        for n = 1:length(cell_Results)
            while enableRun(k) == 0
                k = k+1;
            end
            if ~isempty(cell_Results{n})
                cell_Results_ready{k} = cell_Results{n};
                cell_Timesteppingdata_ready{k} = cell_Timesteppingdata{n};
                cell_Private_output{k} = cell_Private{n};
            end
            k = k+1;
        end
    end
    if i>nDesigns
        break
    end
end

% get all (the rest) results
numberOfProcesses0 = numberOfProcesses;
while numberOfProcesses>0
    % check if any results are ready
    [cell_Results, cell_Timesteppingdata, ~, cell_Private, numberOfProcesses] = getMStimestepping_par();
    if numberOfProcesses ~= numberOfProcesses0  % if new results are ready (number of processes changed)
        % put results
        k = 1;
        for n = 1:length(cell_Results)
            while enableRun(k) == 0
                k = k+1;
            end
            if ~isempty(cell_Results{n})
                cell_Results_ready{k} = cell_Results{n};
                cell_Timesteppingdata_ready{k} = cell_Timesteppingdata{n};
                cell_Private_output{k} = cell_Private{n};
            end
            k = k+1;
        end
        numberOfProcesses0 = numberOfProcesses;
    end
    pause(1); % wait for 1 second
end
% check if any simulation failed and try again
for i = 1:nDesigns  
    Error = cell_Error{i};
    if isempty(Error) && enableRun(i)
        if isempty(cell_Results_ready{i})
            Geometry = cell_Geometry{i};
            Windings = cell_Windings{i};
            Mesh = cell_Mesh{i};
            Materials = cell_Materials{i};
            SubdomainProperty = cell_SubdomainProperty{i};
            settingsMagnetostatic=setParampm(settingsMagnetostatic,'RMS supply current',arr_Current(i));
            try
                [Results, Timesteppingdata] = runMStimestepping([],Geometry,Mesh,Windings,settingsMagnetostatic,Materials,SubdomainProperty,0); % run magnetostatic analysis
            catch ME
                rethrow(ME)
            end
            cell_Results_ready{i} = Results;
            cell_Timesteppingdata_ready{i} = Timesteppingdata;
        end
    end
end
        
end

%________________________________________________________________________________________________________________________


function motorProps = getMotorProps(motorProps,designParams,Userdata,i)

motortype = Userdata.motortype;                  % either 'InnerRotor' or 'OuterRotor'
outerDiameter = Userdata.outerDiameter;          % machine outer diameter, mm
laminationLength = Userdata.laminationLength;    % machine lamination length, mm
airGap = Userdata.airGap;                        % machine air gap length, mm
innerDiameter = Userdata.innerDiameter;          % machine inner diameter, mm
slotopeningDepth = Userdata.slotopeningDepth;    % slot opening depth

if isempty(outerDiameter)
    index = Userdata.index_outerDiameter;
    outerDiameter = designParams(i,index);       % machine outer diameter is defined as a variable
end
if isempty(laminationLength)
    index = Userdata.index_laminationLength;
    laminationLength = designParams(i,index);    % machine lamination length is defined as a variable
end
if isempty(airGap)
    index = Userdata.index_airGap;
    airGap = designParams(i,index);              % machine air gap length is defined as a variable
end
if isempty(innerDiameter)
    index = Userdata.index_innerDiameter;
    innerDiameter = designParams(i,index);       % machine inner diameter is defined as a variable
end

toothWidth = designParams(i,1);                  % Tooth width
ratio_statorBackIronDepth = designParams(i,2);   % Stator back iron depth ratio to tooth width
ratio_rotorBackIronDepth = designParams(i,3);    % Rotor back iron depth to stator back iron depth ratio
slotopeningWidth = designParams(i,4);            % Slot opening width
toothTipAngle = designParams(i,5);               % Tooth tip angle
magnetDepth = designParams(i,6);                 % Magnet depth
magnetAngle = designParams(i,7);                 % Magnet angle   

statorBackIronDepth = ratio_statorBackIronDepth*toothWidth;
rotorBackIronDepth = ratio_rotorBackIronDepth*statorBackIronDepth;

% use only 4 digits after point
outerDiameter = round(outerDiameter*10000)/10000;   
innerDiameter = round(innerDiameter*10000)/10000;    
airGap = round(airGap*10000)/10000;    
laminationLength = round(laminationLength*10000)/10000;    
statorBackIronDepth = round(statorBackIronDepth*10000)/10000;  
rotorBackIronDepth = round(rotorBackIronDepth*10000)/10000;  
toothWidth = round(toothWidth*10000)/10000;    
slotopeningDepth = round(slotopeningDepth*10000)/10000;    
slotopeningWidth = round(slotopeningWidth*10000)/10000;   
magnetDepth = round(magnetDepth*10000)/10000;    
% use only 2 digits after point for angles
magnetAngle = round(magnetAngle*100)/100;    
toothTipAngle = round(toothTipAngle*100)/100;  

slotDepth = (outerDiameter-innerDiameter)/2-rotorBackIronDepth-magnetDepth-airGap-statorBackIronDepth;

if strcmp(motortype,'InnerRotor')
    motorProps = setParampm(motorProps,'Stator Inner Diameter',outerDiameter-2*(statorBackIronDepth+slotDepth));
    motorProps = setParampm(motorProps,'Stator Outer Diameter',outerDiameter);
    motorProps = setParampm(motorProps,'Rotor Inner Diameter',innerDiameter);
    motorProps = setParampm(motorProps,'Rotor Outer Diameter',innerDiameter+2*(rotorBackIronDepth+magnetDepth));
elseif strcmp(motortype,'OuterRotor')
    motorProps = setParampm(motorProps,'Stator Inner Diameter',innerDiameter);
    motorProps = setParampm(motorProps,'Stator Outer Diameter',innerDiameter+2*(statorBackIronDepth+slotDepth));
    motorProps = setParampm(motorProps,'Rotor Inner Diameter',outerDiameter-2*(rotorBackIronDepth+magnetDepth));
    motorProps = setParampm(motorProps,'Rotor Outer Diameter',outerDiameter);    
end
motorProps = setParampm(motorProps,'Air Gap',airGap);
motorProps = setParampm(motorProps,'Lamination Stack Length',laminationLength);
motorProps = setParampm(motorProps,'Slot Depth',slotDepth);
motorProps = setParampm(motorProps,'Tooth Width',toothWidth);
motorProps = setParampm(motorProps,'Slot Opening Depth',slotopeningDepth);
motorProps = setParampm(motorProps,'Slot Opening Width',slotopeningWidth);
motorProps = setParampm(motorProps,'Tooth Tip Angle',toothTipAngle);
motorProps = setParampm(motorProps,'Magnet Depth',magnetDepth);
motorProps = setParampm(motorProps,'Magnet Angle',magnetAngle);
end  



