% main program
disp('*************************')
disp('Welcome to BMI calculator')
choice = 0;
while choice<3
    choice = input_main_menu();
    if choice==1
        h = input_measure('height', 'meters', 1, 2.5);
        w = input_measure('weight', 'kilograms', 40, 300);
        make_plot(h, w)
    elseif choice==2
        h = input_measure('height', 'meters', 1, 2.5);
        make_plot(h)
    end
end
disp('Bye!')


function i = input_main_menu()
disp('')
disp('What would you like to do?')
disp('Type 1, 2, or 3 followed by enter:')
disp('1. Compute and display BMI from weight and height.')
disp('2. Compute and display a normal BMI range from height.')
disp('3. Quit')
s = input('Choice: ', 's');
i = str2num(s);
while isempty(i) || ~any(i == [1,2,3])
    disp(['You typed ', s])
    disp('You should type 1, 2 or 3 followed by enter.')
    s = input('Choice: ', 's');
    i = str2num(s);
end
end


function m = input_measure(measure_type, units, m_min, m_max)
disp('')
s = input(['Type ', measure_type, ' followed by enter: '], 's');
m = str2double(s);
while isnan(m) || m<m_min || m>m_max
    disp(['You typed ', s])
    disp(['Type a valid ', measure_type, ' in ', units, '.'])
    s = input(['Type ', measure_type, ' followed by enter: '], 's');
    m = str2double(s);    
end
end


function make_plot(height, weight)
close all
figure
hold on
h = linspace(1.3, 2.2);
plot(h, 30*h.^2, 'r')
plot(h, 25*h.^2, 'm')
plot(h, 18.5*h.^2, 'g')
if nargin==1
    wmin = 18.5*height^2;
    wmax = 25*height^2;
    plot([height, height], [wmin, wmax], 'k')
    d = ['Normal range [',num2str(wmin,'%.2f'),' ',num2str(wmax,'%.2f'),']'];
else
    plot(height, weight, 'ko')
    d = ['BMI ',num2str(weight/(height^2),'%.2f')];
end
legend('Obese to overweight', 'Overweight to normal',...
    'Normal to underweight', d)
xlabel('Height')
ylabel('Weight')
title('BMI plot')
end