%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%function plotStruct
%  Always keep 'Custom' first and 'Expert' last in review set list
function plotStruct(expert)
	global reviewsets

% this sets the global reviewsets
plotDefaults;

% choose a review set
if ~nargin,
	[setIndex,v] = mylistdlg('Name','Select review set:','ListString',reviewsets, ...
		'SelectionMode','single','InitialValue',getReviewSetIndex('General'), ...
		'WindowStyle','normal');
else
	setIndex = length(reviewsets);
end

res = 0;
if isempty(setIndex),
	return
elseif setIndex == getReviewSetIndex('Expert'),
	try, res = myExpertPlot; catch, errorbox('Expert review failed.'), end
elseif setIndex == getReviewSetIndex('Timing')
	try, plotTiming, catch, errorbox('Timing review failed.'), end
elseif setIndex == getReviewSetIndex('Syslog')
	try, plotSyslog, catch, errorbox('Syslog review failed.'), end
else
	try, myDefaultPlot(setIndex), catch, errorbox('Default review failed'), end
end

% once in expert mode, recurse
if res, plotStruct(1), end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = myDefaultPlot(setIndex)
if ~nargin, setIndex = getReviewSetIndex('Custom'); end
defaults = plotDefaults;
sval = find([defaults.reviewset] == setIndex);
if setIndex == getReviewSetIndex('Custom'),
	str = {defaults.plotName};
	[sval,v] = mylistdlg('Name','Select plots:','ListString',str,...
		'WindowStyle','normal');
end
if isempty(sval), return, end

for jj=1:length(sval),
	makeSinglePlot(defaults(sval(jj)))
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function makeSinglePlot(plotStr)
	global logName, global plotName, global decii
	
[str,logName] = getSinglePlot(plotStr.name,plotStr.fields);

% decimate if large
decii = setDecimate(str,decii);

if isempty(str), return, end
plotName = plotStr.plotName;
logName = strtok(strip(strtok(logName,'.'),'_'),' ');
minTime = str.time(1);
try, plotVsTimeSameFigure(str,plotStr.fields,minTime,plotStr.newFig)	
catch, errorbox(['Unable to make figure ' plotStr.plotName]), end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = myExpertPlot()
	global logName, global decii, global plotName

% init values
res = 0;
logName = '';
plotName = '';

% load the log file
[str,logName] = loadStruct;
if isempty(str), return, end
if ~isfield(str,'time'), disp('Log file missing time'), return, end

% grab the minimum time
minTime = str.time(1);

% select fields for plotting
fields = sort(fieldnames(str));
iiTime = indexof(fields,'time');
if iiTime > 0,
	fields(iiTime) = [];
	fields = [{'time'}; fields];
	iiTime = 1;
end
[selection,ok] = mylistdlg('ListString',fields,'Name','Select fields to plot:',...
	'InitialValue',1,'WindowStyle','normal');
if ~length(selection) | ~ok, return, end

% decimate if large
decii = setDecimate(str,decii);

% choose plot
if find(selection == iiTime)
	if length(selection) == 1,
		plotTimeDiff(str,fields(selection),minTime);
	else
		plotVsTime(str,fields(selection),minTime)
	end
else
	plotVsTimeSameFigure(str,fields(selection),minTime,length(selection) > 1)	
end

% outputs one if successful
res = 1;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [str,logName] = getSinglePlot(name,fields);
str = [];
logName = '';
d = dir(['*' name '*.mat']);
if isempty(d), 
	lasterr('')
	errorbox([name ' not found. Unable to create plot.'])
	return
end
logName = d(1).name;
str = load(d(1).name);
f = fieldnames(str);
str = getfield(str,f{1});


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [str,logName] = loadStruct
str = [];
logName = [];
d = dir('*.mat');
if ~length(d),
	msgbox('No log files found.','Log Plot Error:')
	return,
end
fields = sort({d.name});
[selection,ok] = mylistdlg('ListString',fields,'SelectionMode','single',...
	'Name','Select Log File:','WindowStyle','normal');
if ~length(selection) | ~ok, return, end
logName = fields{selection};
str = load(logName);
logName = strtok(strip(strtok(logName,'.'),'_'),' ');
f = fieldnames(str);
str = getfield(str,f{1});
if ~isstruct(str),
	msgbox('Invalid file.','Log Plot Error');
	str = [];
	return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotTimeDiff(str,fields,minTime)
	global logName, global decii
%disp('plotTimeDiff')
%fields

figure
subplot(2,1,1)
dt = diff(str.time);
plot(str.time(1:decii:end)-minTime,[dt(1:decii:end);0],'.-')
grid on
ylabel([logName '::time diff'])
title([strip(pwd,'\','/') ' \copyright Bluefin Robotics'])
xlabel(['Start time ' num2str(minTime) '(seconds)'])

subplot(2,1,2)
hist(dt,100)
grid on
ylabel('Counts')
xlabel('Seconds')


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotVsEachOther(str,fields)
	global logName, global decii
%disp('plotVsEachOther')
%fields

figure
val1 = getfield(str,fields{2});
val2 = getfield(str,fields{1});
plot(val1(1:decii:end),val2(1:decii:end),'.-')
xlabel([logName '::' strip(fields{2},'_')])
ylabel([logName '::' strip(fields{1},'_')])
grid on
title([strip(pwd,'\','/') ' \copyright Bluefin Robotics'])


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotVsTime(str,fields,minTime)
	global logName, global decii
%disp('plotVsTime')
%fields

if ~isfield(str,'time'),
	disp('Time is not a field')
	str
	return
end

for ii=1:length(fields),
	figure
	val = getfield(str,fields{ii});
	plot(str.time(1:decii:end)-minTime,val(1:decii:end),'.-')
	xlabel(['Start time ' num2str(minTime)])
	ylabel([logName '::' strip(fields{ii},'_')])
	title([strip(pwd,'\','/') ' \copyright Bluefin Robotics'])
	grid on
	set(gcf,'UserData','plotStruct')
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotVsTimeSameFigure(str,fields,minTime,newFig)
	global logName, global decii, global plotName
%disp('plotVsTimeSameFigure')
%fields

if ~isfield(str,'time'),
	disp('Time is not a field')
	str
	return
end

if nargin == 3, newFig = 0; end
if isempty(get(0,'CurrentFigure')) | newFig,
	figure
elseif strcmp(get(gcf,'UserData'),'plotStruct'),
	figure(gcf), hold on
else
	figure
end
ic = length(get(gca,'Children'));
iiTime = [];
h = [];
ud = get(gca,'UserData');
if ~isempty(ud),
	minTime = ud;
end

for ii=1:length(fields),
	if strcmp(fields{ii},'time'), iiTime = ii; continue, end
	val = getfield(str,fields{ii});
	h = [h;plot(str.time(1:decii:end)-minTime,val(1:decii:end),[cm '.-'])];
	hold on
	fields{ii} = [logName '::' strip(fields{ii},'_')];
end
xlabel(['Start time ' num2str(minTime)])
if ~isempty(iiTime), fields(iiTime) = []; end
[legh,objh,outh,outm] = legend;
legend([outh; h],[outm fields(:)'])
title([strip(pwd,'\','/') ' \copyright Bluefin Robotics'])
grid on
set(gcf,'Name',plotName)
set(gca,'UserData',minTime)
set(gcf,'UserData','plotStruct')


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%mystrip
function decii = setDecimate(str,decii)
if nargin == 1 | isempty(decii), decii = 10; end
maxArrayLength = 1000000;
if length(str.time) > maxArrayLength,
	prompt={'The log file is very big.  Please specify decimation:'};
	def={int2str(decii)};
	dlgTitle='Data Decimation Recommended';
	lineNo=1;
	answer=inputdlg(prompt,dlgTitle,lineNo,def);
	if ~isempty(answer) & length(answer{1}),
		tmp = sscanf(answer{1},'%d');
		if tmp > 0 & tmp < 100, decii = tmp;
		else decii = setDecimate(str,decii); end
	end
end

