function varargout = UnitConverter(varargin)
% UNITCONVERTER M-file for UnitConverter.fig
%      UNITCONVERTER, by itself, creates a new UNITCONVERTER or raises the existing
%      singleton*.
%
%      H = UNITCONVERTER returns the handle to a new UNITCONVERTER or the handle to
%      the existing singleton*.
%
%      UNITCONVERTER('Property','Value',...) creates a new UNITCONVERTER using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to UnitConverter_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      UNITCONVERTER('CALLBACK') and UNITCONVERTER('CALLBACK',hObject,...) call the
%      local function named CALLBACK in UNITCONVERTER.M with the given input
%      arguments.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help UnitConverter

% Last Modified by GUIDE v2.5 21-Apr-2004 15:22:13

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @UnitConverter_OpeningFcn, ...
                   'gui_OutputFcn',  @UnitConverter_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
               
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before UnitConverter is made visible.
function UnitConverter_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for UnitConverter
handles.output = hObject;
handles = loadData(hObject, handles);
handles = initialize(hObject, handles);

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes UnitConverter wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = UnitConverter_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in OKbut.
function OKbut_Callback(hObject, eventdata, handles)
% hObject    handle to OKbut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

OValDispHandle = findobj(gcbf,'Tag','OValDisp');
NValDispHandle = findobj(gcbf,'Tag','NValDisp');

input = str2num(get(OValDispHandle,'String'));

if(length(input) ~= 1)
    set(OValDispHandle,'String','Invalid Entry');
else
    if (handles.extraUnits == 0)
        answer = num2str(input * handles.conversion);
    else
        answer = 'Units do not match up!';
    end
    
    set(NValDispHandle,'String',answer);
end

guidata(hObject, handles);


% --- Executes on button press in ClrBut.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to ClrBut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles = initialize(hObject, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function OUlist_CreateFcn(hObject, eventdata, handles)
% hObject    handle to OUlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


% --- Executes on selection change in OUlist.
function OUlist_Callback(hObject, eventdata, handles)
% hObject    handle to OUlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns OUlist contents as cell array
%        contents{get(hObject,'Value')} returns selected item from OUlist

numHandle = findobj(gcbf,'Tag','OUNrad');
listHandle = findobj(gcbf,'Tag','OUlist');
OUNdispHandle = findobj(gcbf,'Tag','OUNdisp');
OUDdispHandle = findobj(gcbf,'Tag','OUDdisp');

level = handles.OunitLevel;
numerator = get(numHandle,'Value');
listStr = get(listHandle,'String');
listVal = get(listHandle,'Value');
choice = listStr(listVal);

if (level == 1)
    unitIndex = strmatch(listVal, handles.unitTypes, 'exact');
    newString = {'...'};
    newString(2:length(unitIndex)+1) = handles.unitNames(unitIndex);
    set(listHandle, 'String', newString, 'Value', 1);
    handles.OunitLevel = 2;
elseif (level == 2)
    if (listVal == 1)
        set(listHandle, 'String', handles.unitTypeNames,'Value',1)
        handles.OunitLevel = 1;
    elseif (numerator == 1)
        unitIndex = strmatch(choice, handles.unitNames, 'exact');
        typeIndex = handles.unitTypes(unitIndex);
        handles.oldUnits(unitIndex) = handles.oldUnits(unitIndex) + 1;
        handles.extraUnits(typeIndex) = handles.extraUnits(typeIndex) + 1;
        handles.conversion = handles.conversion * handles.convFactors(unitIndex);
    elseif (numerator == 0)
        unitIndex = strmatch(choice, handles.unitNames, 'exact');
        typeIndex = handles.unitTypes(unitIndex);
        handles.oldUnits(unitIndex) = handles.oldUnits(unitIndex) - 1;
        handles.extraUnits(typeIndex) = handles.extraUnits(typeIndex) - 1;
        handles.conversion = handles.conversion / handles.convFactors(unitIndex);
    end
end

dispStr = createDispStrings(handles.unitNames, handles.oldUnits);
set(OUNdispHandle,'String',dispStr(1));
set(OUDdispHandle,'String',dispStr(2));

guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function NUlist_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NUlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


% --- Executes on selection change in NUlist.
function NUlist_Callback(hObject, eventdata, handles)
% hObject    handle to NUlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns NUlist contents as cell array
%        contents{get(hObject,'Value')} returns selected item from NUlist

numHandle = findobj(gcbf,'Tag','NUNrad');
listHandle = findobj(gcbf,'Tag','NUlist');
NUNdispHandle = findobj(gcbf,'Tag','NUNdisp');
NUDdispHandle = findobj(gcbf,'Tag','NUDdisp');

level = handles.NunitLevel;
numerator = get(numHandle,'Value');
listStr = get(listHandle,'String');
listVal = get(listHandle,'Value');
choice = listStr(listVal);

if (level == 1)
    unitIndex = strmatch(listVal, handles.unitTypes, 'exact');
    newString = {'...'};
    newString(2:length(unitIndex)+1) = handles.unitNames(unitIndex);
    set(listHandle, 'String', newString, 'Value', 1);
    handles.NunitLevel = 2;
elseif (level == 2)
    if (listVal == 1)
        set(listHandle, 'String', handles.unitTypeNames,'Value',1)
        handles.NunitLevel = 1;
    elseif (numerator == 1)
        unitIndex = strmatch(choice, handles.unitNames, 'exact');
        typeIndex = handles.unitTypes(unitIndex);
        handles.newUnits(unitIndex) = handles.newUnits(unitIndex) + 1;
        handles.extraUnits(typeIndex) = handles.extraUnits(typeIndex) - 1;
        handles.conversion = handles.conversion / handles.convFactors(unitIndex);
    elseif (numerator == 0)
        unitIndex = strmatch(choice, handles.unitNames, 'exact');
        typeIndex = handles.unitTypes(unitIndex);
        handles.newUnits(unitIndex) = handles.newUnits(unitIndex) - 1;
        handles.extraUnits(typeIndex) = handles.extraUnits(typeIndex) + 1;
        handles.conversion = handles.conversion * handles.convFactors(unitIndex);
    end
end

dispStr = createDispStrings(handles.unitNames, handles.newUnits);
set(NUNdispHandle,'String',dispStr(1));
set(NUDdispHandle,'String',dispStr(2));

guidata(hObject, handles);


% --- Executes on button press in OUNrad.
function OUNrad_Callback(hObject, eventdata, handles)
% hObject    handle to OUNrad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of OUNrad

OUNradHandle = findobj(gcbf,'Tag','OUNrad');
OUDradHandle = findobj(gcbf,'Tag','OUDrad');

val = get(OUNradHandle,'Value');

if (val == 0)
    set(OUDradHandle,'Value',1);
else
    set(OUDradHandle,'Value',0);
end

guidata(hObject, handles);


% --- Executes on button press in OUDrad.
function OUDrad_Callback(hObject, eventdata, handles)
% hObject    handle to OUDrad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of OUDrad

OUDradHandle = findobj(gcbf,'Tag','OUDrad');
OUNradHandle = findobj(gcbf,'Tag','OUNrad');

val = get(OUDradHandle,'Value');

if (val == 0)
    set(OUNradHandle,'Value',1);
else
    set(OUNradHandle,'Value',0);
end

guidata(hObject, handles);


% --- Executes on button press in NUNrad.
function NUNrad_Callback(hObject, eventdata, handles)
% hObject    handle to NUNrad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of NUNrad

NUNradHandle = findobj(gcbf,'Tag','NUNrad');
NUDradHandle = findobj(gcbf,'Tag','NUDrad');

val = get(NUNradHandle,'Value');

if (val == 0)
    set(NUDradHandle,'Value',1);
else
    set(NUDradHandle,'Value',0);
end

guidata(hObject, handles);


% --- Executes on button press in NUDrad.
function NUDrad_Callback(hObject, eventdata, handles)
% hObject    handle to NUDrad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of NUDrad

NUDradHandle = findobj(gcbf,'Tag','NUDrad');
NUNradHandle = findobj(gcbf,'Tag','NUNrad');

val = get(NUDradHandle,'Value');

if (val == 0)
    set(NUNradHandle,'Value',1);
else
    set(NUNradHandle,'Value',0);
end

guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function NValDisp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to OValDisp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


function NValDisp_Callback(hObject, eventdata, handles)
% hObject    handle to OValDisp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of OValDisp as text
%        str2double(get(hObject,'String')) returns contents of OValDisp as a double

% --- Executes during object creation, after setting all properties.


function OValDisp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to OValDisp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


function OValDisp_Callback(hObject, eventdata, handles)
% hObject    handle to OValDisp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of OValDisp as text
%        str2double(get(hObject,'String')) returns contents of OValDisp as a double


function newHandles = loadData(hObject, handles)
numUnitTypes = 6;
numUnits = 13;

handles.numUnitTypes = numUnitTypes;
handles.numUnits = numUnits;

handles.convFactors = zeros(numUnits,1);
handles.unitTypes = zeros(numUnits,1);
handles.unitTypeNames = zeros(numUnitTypes,1);
handles.unitNames = zeros(numUnits,1);

handles.unitTypeNames = {'Length','Time','Volume','Mass','Force','Energy'};
handles.unitNames = {'km','m','mm','h','min','s','l','ml','kg','g','N','kJ','J'};
handles.unitTypes = [1 1 1 2 2 2 3 3 4 4 5 6 6]';
handles.convFactors = [1e3 1 1e-3 3600 60 1 1e-3 1e-6 1 1e-3 1 1e3 1]';
    
newHandles = handles;


function newHandles = initialize(h0bject, handles)

set(handles.OValDisp,'String',0);
set(handles.NValDisp,'String',0);
set(handles.OUlist,'String',handles.unitTypeNames,'Value',1);
set(handles.OUNrad,'Value',1);
set(handles.OUNdisp,'String','');
set(handles.OUDdisp,'String','');
set(handles.OUDrad,'Value',0);
set(handles.NUlist,'String',handles.unitTypeNames,'Value',1);
set(handles.NUNrad,'Value',1);
set(handles.NUNdisp,'String','');
set(handles.NUDdisp,'String','');
set(handles.NUDrad,'Value',0);

numUnitTypes = handles.numUnitTypes;
numUnits = handles.numUnits;

handles.extraUnits = zeros(numUnitTypes,1);
handles.oldUnits = zeros(numUnits,1);
handles.newUnits = zeros(numUnits,1);
handles.NunitLevel = 1;
handles.OunitLevel = 1;
handles.conversion = 1;

newHandles = handles;


function dispStrs = createDispStrings(unitNames, unitPowers)

numUnits = length(unitNames);

numerator = ' ';
denominator = ' ';

for i=1:numUnits,
    if (unitPowers(i) == 1)
        numerator = [numerator char(unitNames(i)) ' '];
    elseif (unitPowers(i) > 1)
        numerator = [numerator char(unitNames(i)) '^' num2str(unitPowers(i)) ' '];
    elseif (unitPowers(i) == -1)
        denominator = [denominator char(unitNames(i)) ' '];
    elseif (unitPowers(i) < -1)
        denominator = [denominator char(unitNames(i)) '^' num2str(-unitPowers(i)) ' '];
    end
end 

dispStrs = {numerator, denominator};