function h = timeplot(f,nrows,varargin)

import com.mathworks.toolbox.timeseries.*;
import java.awt.dnd.*

%% Create class instance
h = tsguis.timeplot;
if nargin==0
    return
end


%% Create axes
ax = axes('Parent',double(f),'Units','Normalized','Visible','off','ButtonDownFcn',...
        {@tsWindowButtonDownFcn h});
ax_plotedit = hggetbehavior(ax,'PlotEdit');
ax_plotedit.Enable = false;

%% Set the key press/key release callback
thisfig = ancestor(f,'figure');
jf = get(thisfig,'javaframe');
set(thisfig,'KeyPressFcn',{@tsKeyPressFcn h});
set(jf,'FigurePeerKeyEventCallback',{@tsKeyReleaseFcn h})
while isempty(get(jf,'FigurePeerKeyEventCallback'))
    drawnow expose
end

%% Generic property init
init_prop(h, ax, [nrows 1]);

%% User-specified initial values (before listeners are installed...)
%% Needed to set styleManager
h.set(varargin{1:end});

%% Initialize the handle graphics objects used in @timeplot class.
h.initialize(ax, [nrows 1]);

%% Customize behavior
h.setbehavior

%% Remove Amplitude from ylabel to improve figure packing and remove Tex
%% interpreters which distort underscore characters
h.Axesgrid.Ylabel = '';
h.Axesgrid.TitleStyle.Interpreter = 'None';
h.Axesgrid.XLabelStyle.Interpreter = 'None';
h.Axesgrid.RowLabelStyle.Interpreter = 'None';

%% Add a listener to create data xticks for absolute times
h.addlisteners(handle.listener(h.AxesGrid.Parent,'ResizeEvent',...
    {@localUpdateXticks h}));
h.addlisteners(handle.listener(h.AxesGrid,'Viewchanged',...
    {@localUpdateXticks h}));

%% Add a listener to keep the axesgrid units in sync with the @timeplot
%% TimeUnits.
h.addlisteners(handle.listener(h,h.findprop('Absolutetime'),'PropertyPostSet',...
    {@localUpdateTimeUnits h}));
h.addlisteners(handle.listener(h,h.findprop('Timeunits'),'PropertyPostSet',...
    {@localUpdateTimeUnits h}));
h.addlisteners(handle.listener(h,h.findprop('TimeFormat'),'PropertyPostSet',...
    {@localUpdateTimeUnits h}));


%% Add menus
menus = h.tsplotmenu('TimePlot');

%% Add char menus and set their tag so that findmenu can be used by the
%% char table to keep the menu checked status synched
mean_menu = h.addCharMenu(menus.Characteristics, 'Mean',...
    'tsguis.tsMeanData', 'tsguis.tsMeanView'); 
set(mean_menu,'Tag','Mean')
std_menu = h.addCharMenu(menus.Characteristics, 'STD',...
    'tsguis.tsMeanData', 'tsguis.tsStdView'); 
set(std_menu,'Tag','STD')
median_menu = h.addCharMenu(menus.Characteristics, 'Median',...
    'tsguis.tsMeanData', 'tsguis.tsMedianView'); 
set(median_menu,'Tag','Median')

%% Add a listener to the startdata/absolute time properties so that if changed the
%% responses will redraw
h.addlisteners(handle.listener(h,h.findprop('Startdate'),'PropertyPostSet',...
    {@localClearAbsTimeResps h}));
h.addlisteners(handle.listener(h,h.findprop('Absolutetime'),'PropertyPostSet',...
    {@localClearAbsTimeResps h}));
h.addlisteners(handle.listener(h,h.findprop('TimeUnits'),'PropertyPostSet',...
    {@localClearAbsTimeResps h}));

%% Intialize plot editor
h.PropEditor = tsguis.propeditor;
h.edit(h.PropEditor);


function localClearAbsTimeResps(es,ed,h)

%% Listener callback for chnages in the StartDate/TimeFormat/AbsolouteTime proeprty 

%% Clear the data from all responses
for k=1:length(h.Waves)        
    h.Waves(k).Data.clear
%     chardata = get(h.Waves(k).Characteristics,{'Data'});
%     tunitconv = tsunitconv(ed.NewValue,h.TimeUnits);
%     for j=1:length(chardata)
%         if ~isempty(chardata{j}.findprop('StartTime'))
%             set(chardata{j},'StartTime',chardata{j}.StartTime*tunitconv,...
%                 'EndTime',chardata{j}.EndTime*tunitconv)
%         end
%     end
end


function localUpdateXticks(eventSrc,eventData,h)

%% Get the axes
ax = h.getaxes;

%% Figure resize callback which modifes the default ticks to datestrs when
%% the time vector is absolute
[formatflag,absflag] = tsIsDateFormat(h.TimeFormat);
% Absolute time vector or formatted relative time
if formatflag && (strcmp(h.Absolutetime,'on') || ~absflag)
    % Figure units must be pixels
    oldFigUnits = get(h.AxesGrid.Parent,'Units');
    set(h.AxesGrid.Parent,'Units','Pixels');

    % Use the first axes to estimate the number of date labels which will
    % fit  
    pixelsize = get(h.Axesgrid.Parent,'Position').*get(ax(1),'Position');
    Hfontsize = h.axesgrid.axesstyle.Fontsize/2; 
    labelwidth = (length(h.TimeFormat)+2)*Hfontsize;
    numlabels = pixelsize(3)/labelwidth;
    
    % Create time vector of datestrs
    t = linspace(h.Axesgrid.getxlim{1}(1),h.Axesgrid.getxlim{1}(2),...
        numlabels); 
    if strcmp(h.Absolutetime,'on')
        tstr = datestr(datenum(h.StartDate)+tsunitconv('days',h.TimeUnits)*t,...
          h.Timeformat);
    else
        tstr = datestr(tsunitconv('days',h.TimeUnits)*t,...
          h.Timeformat);
    end
     
    % Overwrite the xticks with the new labels
    set(ax(end),'xticklabel',tstr,'xtick',t);

    % Reset the figure units
    set(h.AxesGrid.Parent,'Units',oldFigUnits);
else
   set(ax(end),'xTickMode','auto')
   set(ax(end),'xTickLabelMode','auto')
end

function localUpdateTimeUnits(eventSrc,eventData,h)

%% Listener callback which keeps the @axesgrid units syncronized with the
%% @timeplot TimeUnits property. Note that they are not identical for
%% absolute time vectors since in this case no units should appear on the
%% @axesgrid
 
[formatflag,absflag] = tsIsDateFormat(h.TimeFormat);
if strcmp(h.Absolutetime,'off') && ~formatflag
    h.Axesgrid.Xunits = h.TimeUnits;
else
    h.Axesgrid.Xunits = '';
end
