function varargout = floatTrack(varargin)
% FLOATTRACK MATLAB code for floatTrack.fig
%      FLOATTRACK, by itself, creates a new FLOATTRACK or raises the existing
%      singleton*.
%
%      H = FLOATTRACK returns the handle to a new FLOATTRACK or the handle to
%      the existing singleton*.
%
%      FLOATTRACK('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FLOATTRACK.M with the given input arguments.
%
%      FLOATTRACK('Property','Value',...) creates a new FLOATTRACK or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before floatTrack_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to floatTrack_OpeningFcn via varargin.
%
%      *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 floatTrack

% Last Modified by GUIDE v2.5 21-Oct-2014 19:28:23

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @floatTrack_OpeningFcn, ...
                   'gui_OutputFcn',  @floatTrack_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(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 floatTrack is made visible.
function floatTrack_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   command line arguments to floatTrack (see VARARGIN)

% Choose default command line output for floatTrack
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

%misc setup stuff
clear functions

%Setup map axes
utmstruct = defaultm('utm'); 
utmstruct.zone = '10S';
wgs84 = wgs84Ellipsoid;
ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
utmstruct.geoid = ellipsoid; 
utmstruct = defaultm(utmstruct);
setappdata(hObject, 'utmstruct', utmstruct);

fprintf('Setup map axes \n');
%Define ship outline
shipLOA = 100;
shipBeam = 28;
shipShapeY = [0, shipBeam/2  shipBeam/2 -shipBeam/2 -shipBeam/2   0];
shipShapeX = [0 -(.3*shipLOA) -shipLOA,   -shipLOA     -(.3*shipLOA) 0];
shipShapeXY = [shipShapeX; shipShapeY];
setappdata(hObject, 'shipShapeXY', shipShapeXY);

%Define float marker outline
starScale = 40.0;
floatStarX = starScale * [0 .5 3 .5 0 -.5 -3 -.5 0];
floatStarY = starScale * [3 .5 0 -.5 -3 -.5 0 .5 3];
floatStarXY = [floatStarX; floatStarY];
setappdata(hObject, 'floatStarXY', floatStarXY);

fprintf('Loading MB15 data set \n');
load('mb15.mat');
%mb15 = evalin('base', 'mb15');fprintf('Setappdata MB15 \n');
setappdata(hObject, 'mb15', mb15);

mca.SClat = [(36+51/60) (36+51/60) (36 + 48/60) (36 + 48/60) (36 + 51/60)];
mca.SClon = [-(121+56/60) -(122+3.8/60) -(122+2.88/60) -(121 + 56/60) -(121 + 56/60)];
mca.PLlat = [(36+43/60) (36+43/60) (36 + 41/60) (36 + 41/60) (36 + 43/60)];
mca.PLlon = [-(121+56/60) -(122+1.3/60) -(122+0.8/60) -(121 + 56/60) -(121 + 56/60)];
[mca.SCeast, mca.SCnorth] = mfwdtran(utmstruct, mca.SClat, mca.SClon);
[mca.PLeast, mca.PLnorth] = mfwdtran(utmstruct, mca.PLlat, mca.PLlon);
setappdata(hObject, 'mcaData', mca);

% zone = '10S';
% wgs84 = wgs84Ellipsoid;
% ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];

axes(handles.chartAxes);
axesm utm
setm(gca,'zone', utmstruct.zone, 'geoid', ellipsoid, 'LabelUnits', 'dm', ...
    'FFill', 1000, 'FLineWidth', 0.5,  ...
    'meridianlabel','on','parallellabel','on', ...
    'MLineLocation', 0.016667, 'PLineLocation', 0.016667, ...
    'MLabelLocation', 0.083333, 'PLabelLocation', 0.083333);

[lat1, lon1] = minvtran(mb15.x(1), mb15.y(end));
[lat2, lon2] = minvtran(mb15.x(end), mb15.y(1));
setm(gca,'maplatlimit',[lat1 lat2], 'maplonlimit', [lon1 lon2]);

cm = haxby(256);
colormap(cm);
V = [0:20:100 200:100:4000];
V = -V;
fprintf('Starting contourf\n');
[C, hF] = contourf(mb15.x,mb15.y,mb15.z, V);
fprintf('contourf done \n');
% set(hF, 'ShowText', 'on', 'LabelSpacing', 1e6);
fillm(mca.SClat, mca.SClon, 'r');
fillm(mca.PLlat, mca.PLlon, 'r');
set(gca,'DataAspectRatio',[1 1 1]);
hFrame = framem('on');
hGrid = gridm('on');
set(hFrame,'Clipping','on');
set(hGrid,'Clipping','on');

setappdata(hObject, 'startStatus', 'false');
set(handles.startButton, 'BackgroundColor', [.941 .941 .941]);
SPTimer = timer('Name','Reminder',...
            'Period',5,...  % Update the time every 60 seconds.
            'TasksToExecute',inf,...  % number of times to update
            'ExecutionMode','fixedSpacing',...
            'TimerFcn',{@timerCallback, handles}); 
setappdata(hObject,'hSPTimer',SPTimer);

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

% --- Outputs from this function are returned to the command line.
function varargout = floatTrack_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;

function [] = timerCallback(varargin)
handles = varargin{3};
SP = serial( 'COM1', ...
    'BaudRate',9600, ...
    'Parity','none', ...
    'StopBits',1, ...
    'ReadAsyncMode','manual',...
    'Terminator','CR/LF', ...
    'InputBufferSize',8192);
fopen(SP)
  fprintf(SP, 'pos v7,4');
    fscanf(SP)
closeSP = onCleanup(@()fclose(SP));
delete(SP);

test = 0;
while test > 0
    try
        inString = fgets(SP);
        if strcmp(inString(1:6),  '$GPRMC');
            [shipLatDecDeg, shipLonDecDeg] = parseRMC(inString, handles);
            plotShip(handles, shipLatDecDeg, shipLonDecDeg, 10);
 
            %Read float log files
            persistent numLogFiles
            if isempty(numLogFiles)
                numLogFiles = 2;
            end
            path = '.\floatLogFiles\';
            directory = dir(strcat(path,'*.log'));
            if( length(directory) ~= numLogFiles)
                floatPos = readLogs(handles);
               
                latString = sprintf('%2.0f %8.5f', degrees2dm(abs(floatPos.latDecDeg(end))) );
                if (floatPos.latDecDeg(end) < 0.0)
                    latString = strcat(latString, ' S');
                end
                lonString = sprintf('%3.0f %8.5f', degrees2dm(abs(floatPos.lonDecDeg(end))) );
                if (floatPos.lonDecDeg(end) < 0.0)
                    lonString = strcat(lonString, ' W');
                end
                set(handles.floatLatMeter, 'String', latString);
                set(handles.floatLonMeter, 'String', lonString);
                plotFloat(handles, floatPos.latDecDeg(end), floatPos.lonDecDeg(end));
                
                %Calculate range and bearings
                wgs84 = wgs84Ellipsoid;
                ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
                [range, bearing] = distance([shipLatDecDeg shipLonDecDeg], ...
                                                [floatPos.latDecDeg(end) floatPos.lonDecDeg(end)], ellipsoid);
                set(handles.rangeMeter, 'String', sprintf('%.0f', range));
                set(handles.trueBearingMeter, 'String', sprintf('%.0f', bearing));
                
                mcaData = getappdata(handles.figure1, 'mcaData');
                [distSC, xSC, ySC] = p_poly_dist( floatPos.east(end), floatPos.north(end), mcaData.SCeast, mcaData.SCnorth);                                                    
                [distPL, xPL, yPL] = p_poly_dist( floatPos.east(end), floatPos.north(end), mcaData.PLeast, mcaData.PLnorth);                                                    
                line([floatPos.east(end) xSC], [floatPos.north(end) ySC], 'Parent', handles.chartAxes);
                line([floatPos.east(end) xPL], [floatPos.north(end) yPL], 'Parent', handles.chartAxes);
                set(handles.rangeSC, 'String', sprintf('%.0f', distSC));
                set(handles.rangePL, 'String', sprintf('%.0f', distPL));
                plot(handles.chartAxes, floatPos.east, floatPos.north)
                numLogFiles = length(directory);
                set(handles.numFloatFiles, 'String', num2str(numLogFiles));
            end
        end
    catch
        fprintf(1, 'Error reading GPS\r\n');
    end
    test = SP.BytesAvailable;
end
fclose(SP);

function [lat, lon] = parseRMC(RMCString, handles)
% $GPRMC,004438.00,A,3648.12994,N,12147.28449,W,0.072,,151112,,,A*67
[token, remain] = strtok(RMCString,',');
for i=1:2
    [token, remain] = strtok(remain, ',');
end

[shipLatString, remain] = strtok(remain, ',');
[shipNSString, remain] = strtok(remain, ',');
shipLatDegDecMin = [shipLatString(1:2), ' ', shipLatString(3:10), ' ', shipNSString];
temp = sscanf(shipLatString, '%2d%f');
shipLatDecDeg = temp(1) + temp(2)/60.0; 
if shipNSString == 'S'
    shipLatDecDeg = -1.0 * shipLatDecDeg;
end

[shipLonString, remain] = strtok(remain, ',');
[shipEWString, remain] = strtok(remain, ',');
shipLonDegDecMin = [shipLonString(1:3), ' ', shipLonString(4:11), ' ', shipEWString];
temp = sscanf(shipLonString, '%3d%f');
shipLonDecDeg = temp(1) + temp(2)/60.0;
if shipEWString == 'W'
    shipLonDecDeg = -1.0 * shipLonDecDeg;
end
lon = shipLonDecDeg;
lat = shipLatDecDeg;

set(handles.shipLatMeter, 'String', shipLatDegDecMin);
set(handles.shipLonMeter, 'String', shipLonDegDecMin);
set(handles.GPSString, 'String', RMCString(1:length(RMCString)-2));
temp = get(handles.RMCCtr, 'String');
RMCCtr = str2num(temp) + 1;
set(handles.RMCCtr, 'String', num2str(RMCCtr));

function plotShip(handles, lat, lon, heading)
persistent oldShipShapeX;
persistent oldShipShapeY;

persistent firstCall
if isempty(firstCall)
    firstCall = true;
end

persistent offset
if isempty(offset)
    offset = 0;
end

utmstruct = getappdata(handles.figure1, 'utmstruct');
[x, y] = mfwdtran(utmstruct, lat, lon);

M = makehgtform('zrotate', degtorad(heading));
M = M(1:2, 1:2);
shipShapeXY = getappdata(handles.figure1, 'shipShapeXY');
shipShapeXYRot = M * shipShapeXY;

shipShapeXYNew = [x + shipShapeXYRot(1,:); y + shipShapeXYRot(2,:) + offset];
offset = offset + 10;

if firstCall == true
    firstCall = false;
else
    fill(oldShipShapeX, oldShipShapeY, 'green', 'Parent',  handles.chartAxes, 'EraseMode', 'xor');
end
fill(shipShapeXYNew(1,:), shipShapeXYNew(2,:), 'green', 'Parent', handles.chartAxes, 'EraseMode','xor');

oldShipShapeX = shipShapeXYNew(1,:);
oldShipShapeY = shipShapeXYNew(2,:);

function plotFloat(handles, lat, lon)
persistent oldFloatStarX;
persistent oldFloatStarY;

persistent firstCall
if isempty(firstCall)
    firstCall = true;
end

persistent offset
if isempty(offset)
    offset = 0;
end

% utmstruct = defaultm('utm');
% utmstruct.zone = '10S';
% wgs84 = wgs84Ellipsoid;
% ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
% utmstruct.geoid = ellipsoid;
% utmstruct = defaultm(utmstruct);
utmstruct = getappdata(handles.figure1, 'utmstruct');
[x, y] = mfwdtran(utmstruct, lat, lon);

floatStarXY = getappdata(handles.figure1, 'floatStarXY');

floatStarXYNew = [x + floatStarXY(1,:); y + floatStarXY(2,:) + offset];
offset = offset + 10;

if firstCall == true
    firstCall = false;
else
    fill(oldFloatStarX, oldFloatStarY, 'blue', 'Parent',  handles.chartAxes, 'EraseMode', 'xor');
end
fill(floatStarXYNew(1,:), floatStarXYNew(2,:), 'blue', 'Parent', handles.chartAxes, 'EraseMode','xor');

oldFloatStarX = floatStarXYNew(1,:);
oldFloatStarY = floatStarXYNew(2,:);

% --- Executes on button press in startButton.
function startButton_Callback(hObject, eventdata, handles)
% hObject    handle to startButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
startStatus = getappdata(handles.figure1, 'startStatus');
if (strcmp(startStatus, 'false'))
    SPTimer = getappdata(handles.figure1, 'hSPTimer');
    start(SPTimer);
    set(handles.startButton, 'BackgroundColor', [.4 .8 0]);
    setappdata(handles.figure1, 'startStatus', 'true');
else
    SPTimer = getappdata(handles.figure1, 'hSPTimer');
    stop(SPTimer);
    set(handles.startButton, 'BackgroundColor', [.941 .941 .941]);
    setappdata(handles.figure1, 'startStatus', 'false');
end

% --- Executes on button press in ginputButton.
function ginputButton_Callback(hObject, eventdata, handles)
% hObject    handle to ginputButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[x, y] = ginput(1);
mb15 = getappdata(handles.figure1, 'mb15');
[xIndex xIndex] = min(abs(mb15.x - x))
[yIndex yIndex] = min(abs(mb15.y - y))
depth = mb15.z(yIndex, xIndex)
set(handles.depthMeter, 'String', depth);

function RangeMeter_Callback(hObject, eventdata, handles)
% hObject    handle to RangeMeter (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 RangeMeter as text
%        str2double(get(hObject,'String')) returns contents of RangeMeter as a double

% --- Executes during object creation, after setting all properties.
function RangeMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RangeMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function RelBearingMeter_Callback(hObject, eventdata, handles)
% hObject    handle to RelBearingMeter (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 RelBearingMeter as text
%        str2double(get(hObject,'String')) returns contents of RelBearingMeter as a double

% --- Executes during object creation, after setting all properties.
function RelBearingMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RelBearingMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

% --- Executes on button press in HUButton.
function HUButton_Callback(hObject, eventdata, handles)
% hObject    handle to HUButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
rotatem(handles.chartAxes,[0 0 1],30);

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

% Hint: place code in OpeningFcn to populate chartAxes

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

% --- Executes during object deletion, before destroying properties.

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

SPTimer = getappdata(hObject, 'hSPTimer');
try
    stop(SPTimer);
catch
end
try 
    delete(SPTimer);
catch
end    

function TrueBearingMeter_Callback(hObject, eventdata, handles)
% hObject    handle to trueBearingMeter (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 trueBearingMeter as text
%        str2double(get(hObject,'String')) returns contents of trueBearingMeter as a double

% --- Executes during object creation, after setting all properties.
function trueBearingMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to trueBearingMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function GPSString_Callback(hObject, eventdata, handles)
% hObject    handle to GPSString (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 GPSString as text
%        str2double(get(hObject,'String')) returns contents of GPSString as a double

% --- Executes during object creation, after setting all properties.
function GPSString_CreateFcn(hObject, eventdata, handles)
% hObject    handle to GPSString (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

function shipLat_Callback(hObject, eventdata, handles)
% hObject    handle to shipLat (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 shipLat as text
%        str2double(get(hObject,'String')) returns contents of shipLat as a double

% --- Executes during object creation, after setting all properties.
function shipLat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to shipLat (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit7_Callback(hObject, eventdata, handles)
% hObject    handle to edit7 (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 edit7 as text
%        str2double(get(hObject,'String')) returns contents of edit7 as a double

% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit7 (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function floatLat_Callback(hObject, eventdata, handles)
% hObject    handle to floatLat (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 floatLat as text
%        str2double(get(hObject,'String')) returns contents of floatLat as a double

% --- Executes during object creation, after setting all properties.
function floatLat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to floatLat (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function floatLon_Callback(hObject, eventdata, handles)
% hObject    handle to floatLon (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 floatLon as text
%        str2double(get(hObject,'String')) returns contents of floatLon as a double

% --- Executes during object creation, after setting all properties.
function floatLon_CreateFcn(hObject, eventdata, handles)
% hObject    handle to floatLon (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function shipLatMeter_Callback(hObject, eventdata, handles)
% hObject    handle to shipLatMeter (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 shipLatMeter as text
%        str2double(get(hObject,'String')) returns contents of shipLatMeter as a double

% --- Executes during object creation, after setting all properties.
function shipLatMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to shipLatMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function shipLonMeter_Callback(hObject, eventdata, handles)
% hObject    handle to shipLonMeter (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 shipLonMeter as text
%        str2double(get(hObject,'String')) returns contents of shipLonMeter as a double

% --- Executes during object creation, after setting all properties.
function shipLonMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to shipLonMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function floatLatMeter_Callback(hObject, eventdata, handles)
% hObject    handle to floatLatMeter (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 floatLatMeter as text
%        str2double(get(hObject,'String')) returns contents of floatLatMeter as a double

% --- Executes during object creation, after setting all properties.
function floatLatMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to floatLatMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function floatLonMeter_Callback(hObject, eventdata, handles)
% hObject    handle to floatLonMeter (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 floatLonMeter as text
%        str2double(get(hObject,'String')) returns contents of floatLonMeter as a double

% --- Executes during object creation, after setting all properties.
function floatLonMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to floatLonMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on mouse press over axes background.
function chartAxes_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to chartAxes (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
zoom2cursor();

% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

function RMCCtr_Callback(hObject, eventdata, handles)
% hObject    handle to RMCCtr (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 RMCCtr as text
%        str2double(get(hObject,'String')) returns contents of RMCCtr as a double

% --- Executes during object creation, after setting all properties.
function RMCCtr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RMCCtr (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function depthMeter_Callback(hObject, eventdata, handles)
% hObject    handle to depthMeter (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 depthMeter as text
%        str2double(get(hObject,'String')) returns contents of depthMeter as a double


% --- Executes during object creation, after setting all properties.
function depthMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to depthMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function [floatPosStruct]  = readLogs(handles);

path = '\\Atlas\chemwebdata\floats\8501\';
directory = dir(strcat(path,'*.log'));

posNum  = 1;
for fileNum=1:length(directory)
    fileName = strcat(path,directory(fileNum).name);
    fid = fopen(fileName);
    lineNum = 1;
    while ~feof(fid)
        inString = fgetl(fid);
        if (findstr('GPGGA', inString) > 0)
            %fprintf(1, 'fileNum: %d   lineNum: %d   inString: %s\n', fileNum, lineNum, inString);
            GGAString{fileNum,posNum} = inString;
            
            [token, remain] = strtok(GGAString{fileNum,posNum}, '$GPGGA');
            [header, remain] = strtok(remain, ',');
            [floatGPSTime, remain] = strtok(remain, ',');
            [floatLat, remain] = strtok(remain, ',');
            [floatNS, remain] = strtok(remain, ',');
            [floatLon, remain] = strtok(remain, ',');
            [floatEW, remain] = strtok(remain, ',');
            
           %logFile(posNum,:) = directory(fileNum).name;
            time(posNum,:) = inString(2:21);
            temp = sscanf(floatLat, '%2d%f');
            latDecDeg(posNum) = temp(1) + temp(2)/60.0;
            if floatNS == 'S'
                latDecDeg(posNum) = -1.0 * latDecDeg(posNum);
            end
            
            temp = sscanf(floatLon, '%3d%f');
            lonDecDeg(posNum) = temp(1) + temp(2)/60.0;
            if floatEW == 'W'
                lonDecDeg(posNum) = -1.0 * lonDecDeg(posNum);
            end
            
            posNum = posNum + 1;
        end
        lineNum = lineNum + 1;
    end
    fclose(fid);
end
%floatPos.logFile = logFile;
floatPosStruct.time = time;
floatPosStruct.latDecDeg = latDecDeg;
floatPosStruct.lonDecDeg = lonDecDeg;

utmstruct = getappdata(handles.figure1,'utmstruct');
% utmstruct = defaultm('utm');
% utmstruct.zone = '10S';
% wgs84 = wgs84Ellipsoid;
% ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
% utmstruct.geoid = ellipsoid;
% utmstruct  = defaultm(utmstruct);
[east, north] = mfwdtran(utmstruct, [floatPosStruct(:).latDecDeg], [floatPosStruct(:).lonDecDeg]);
floatPosStruct.east = east;
floatPosStruct.north = north;

%*******************************************************************************
% function:	p_poly_dist
% Description:	distance from point to polygon whose vertices are specified by the
%              vectors xv and yv
% Input:  
%    x - point's x coordinate
%    y - point's y coordinate
%    xv - vector of polygon vertices x coordinates
%    yv - vector of polygon vertices x coordinates
% Output: 
%    d - distance from point to polygon (defined as a minimal distance from 
%        point to any of polygon's ribs, positive if the point is outside the
%        polygon and negative otherwise)
%    x_poly: x coordinate of the point in the polygon closest to x,y
%    y_poly: y coordinate of the point in the polygon closest to x,y
%
% Routines: p_poly_dist.m
% Revision history:
%    03/31/2008 - return the point of the polygon closest to x,y
%               - added the test for the case where a polygon rib is 
%                 either horizontal or vertical. From Eric Schmitz.
%               - Changes by Alejandro Weinstein
%    7/9/2006  - case when all projections are outside of polygon ribs
%    23/5/2004 - created by Michael Yoshpe 
% Remarks:
%*******************************************************************************
function [d,x_poly,y_poly] = p_poly_dist(x, y, xv, yv) 

% If (xv,yv) is not closed, close it.
xv = xv(:);
yv = yv(:);
Nv = length(xv);
if ((xv(1) ~= xv(Nv)) || (yv(1) ~= yv(Nv)))
    xv = [xv ; xv(1)];
    yv = [yv ; yv(1)];
%     Nv = Nv + 1;
end

% linear parameters of segments that connect the vertices
% Ax + By + C = 0
A = -diff(yv);
B =  diff(xv);
C = yv(2:end).*xv(1:end-1) - xv(2:end).*yv(1:end-1);

% find the projection of point (x,y) on each rib
AB = 1./(A.^2 + B.^2);
vv = (A*x+B*y+C);
xp = x - (A.*AB).*vv;
yp = y - (B.*AB).*vv;

% Test for the case where a polygon rib is 
% either horizontal or vertical. From Eric Schmitz
id = find(diff(xv)==0);
xp(id)=xv(id);
clear id
id = find(diff(yv)==0);
yp(id)=yv(id);

% find all cases where projected point is inside the segment
idx_x = (((xp>=xv(1:end-1)) & (xp<=xv(2:end))) | ((xp>=xv(2:end)) & (xp<=xv(1:end-1))));
idx_y = (((yp>=yv(1:end-1)) & (yp<=yv(2:end))) | ((yp>=yv(2:end)) & (yp<=yv(1:end-1))));
idx = idx_x & idx_y;

% distance from point (x,y) to the vertices
dv = sqrt((xv(1:end-1)-x).^2 + (yv(1:end-1)-y).^2);

if(~any(idx)) % all projections are outside of polygon ribs
   [d,I] = min(dv);
   x_poly = xv(I);
   y_poly = yv(I);
else
   % distance from point (x,y) to the projection on ribs
   dp = sqrt((xp(idx)-x).^2 + (yp(idx)-y).^2);
   [min_dv,I1] = min(dv);
   [min_dp,I2] = min(dp);
   [d,I] = min([min_dv min_dp]);
   if I==1, %the closest point is one of the vertices
       x_poly = xv(I1);
       y_poly = yv(I1);
   elseif I==2, %the closest point is one of the projections
       idxs = find(idx);
       x_poly = xp(idxs(I2));
       y_poly = yp(idxs(I2));
   end
end

if(inpolygon(x, y, xv, yv)) 
   d = -d;
end

function numFloatFiles_Callback(hObject, eventdata, handles)
% hObject    handle to numFloatFiles (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 numFloatFiles as text
%        str2double(get(hObject,'String')) returns contents of numFloatFiles as a double


% --- Executes during object creation, after setting all properties.
function numFloatFiles_CreateFcn(hObject, eventdata, handles)
% hObject    handle to numFloatFiles (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function trueBearingMeter_Callback(hObject, eventdata, handles)
% hObject    handle to trueBearingMeter (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 trueBearingMeter as text
%        str2double(get(hObject,'String')) returns contents of trueBearingMeter as a double



function rangeMeter_Callback(hObject, eventdata, handles)
% hObject    handle to rangeMeter (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 rangeMeter as text
%        str2double(get(hObject,'String')) returns contents of rangeMeter as a double


% --- Executes during object creation, after setting all properties.
function rangeMeter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rangeMeter (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function rangePL_Callback(hObject, eventdata, handles)
% hObject    handle to rangePL (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 rangePL as text
%        str2double(get(hObject,'String')) returns contents of rangePL as a double


% --- Executes during object creation, after setting all properties.
function rangePL_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rangePL (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function rangeSC_Callback(hObject, eventdata, handles)
% hObject    handle to rangeSC (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 rangeSC as text
%        str2double(get(hObject,'String')) returns contents of rangeSC as a double


% --- Executes during object creation, after setting all properties.
function rangeSC_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rangeSC (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit23_Callback(hObject, eventdata, handles)
% hObject    handle to edit23 (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 edit23 as text
%        str2double(get(hObject,'String')) returns contents of edit23 as a double


% --- Executes during object creation, after setting all properties.
function edit23_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit23 (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


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