function timeplt_draw()
% TIMEPLT_DRAW:  Takes care of drawing routines.
%
% C. Sullivan 12/08/04, I have added 'align' to the subplot calls
%                       (ie: subplot(1,1,1,'align')).  This ensures 
%                       the panels on subplots are all the same size and
%                       prevents ML7 R14 from resizing them on you!
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use of this program is described in:
%
% Sullivan, C.M., Warner, J.C., Martini, M.A., Voulgaris, G., 
% Work, P.A., Haas, K.A., and Hanes, D.H. (2006) 
% South Carolina Coastal Erosion Study Data Report for Observations
% October 2003 - April 2004., USGS Open-File Report 2005-1429.
%
% Program written in Matlab v7.1.0 SP3
% Program ran on PC with Windows XP Professional OS.
%
% "Although this program has been used by the USGS, no warranty, 
% expressed or implied, is made by the USGS or the United States 
% Government as to the accuracy and functioning of the program 
% and related program material nor shall the fact of distribution 
% constitute any such warranty, and no responsibility is assumed 
% by the USGS in connection therewith."
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

global  timeplt_obj month_label oldxlabel

cmenu=uicontextmenu;
% uimenu(cmenu, 'Label', 'Black', 'Callback', 'linecontrol(''k'')');
uimenu(cmenu, 'Label', 'Red', 'Callback', 'linecontrol(''r'')');
uimenu(cmenu, 'Label', 'Green', 'Callback', 'linecontrol(''g'')');
uimenu(cmenu, 'Label', 'Cyan', 'Callback', 'linecontrol(''c'')');
uimenu(cmenu, 'Label', 'Yellow', 'Callback', 'linecontrol(''y'')');
uimenu(cmenu, 'Label', 'Magenta', 'Callback', 'linecontrol(''m'')');
uimenu(cmenu, 'Label', 'Aqua', 'Callback', 'linecontrol(''a'')');
uimenu(cmenu, 'Label', '--');
uimenu(cmenu, 'Label', 'Dot', 'Callback', 'linecontrol(''dot'')');
uimenu(cmenu, 'Label', 'Plus', 'Callback', 'linecontrol(''plus'')');
uimenu(cmenu, 'Label', 'Circle', 'Callback', 'linecontrol(''cir'')');
uimenu(cmenu, 'Label', 'Square', 'Callback', 'linecontrol(''sq'')');
uimenu(cmenu, 'Label', 'Line', 'Callback', 'linecontrol(''line'')');
uimenu(cmenu, 'Label', 'Dashed', 'Callback', 'linecontrol(''dashed'')');
uimenu(cmenu, 'Label', 'Line&Plus', 'Callback', 'linecontrol(''LP'')');
uimenu(cmenu, 'Label', 'Line&Circle', 'Callback', 'linecontrol(''LC'')');
uimenu(cmenu, 'Label', 'Line&Square', 'Callback', 'linecontrol(''LS'')');



month_label = [    'Jan'; ...
                'Feb';...
                'Mar';...
                'Apr';...
                'May';...
                'Jun';...
 
				'Jul';...
                'Aug';...
                'Sep';...
                'Oct';...
                'Nov';...
                'Dec'];

N = timeplt_obj_index;
xlabtext=[];
% N=99;
%%%%%%%%%%%%%%%%%%Added to accomadate cmgtool%%%%%%%
axhand=timeplt_obj{N}.plot_axes;
axhandlength=length(axhand);
numleg=[];
for i=1:length(axhand)
	txt{i}='';
	test=get(axhand(i),'chil');
	if ~isempty(findobj(test,'tag','Legend'))
		numleg=[numleg i];
	end;
	for j=1:length(test)
	   if strcmpi(get(test(j),'type'),'text')
		   txt{i}=get(test(j),'string');
		   txtpos{i}=get(test(j),'position');
		   break;
	   end;
	end;
	tit{i}=get(get(axhand(i),'title'),'string');
	ylab{i}=get(get(axhand(i),'ylabel'),'string');
	
	xlabtext{i}=get(axhand(i),'chil');
	legtxt(i).legend='';
end;

test2=findobj(gcf,'tag','legend');
test3=get(test2,'chil');
if ~iscell(test3)
	temp{1}=test3;
	test3=temp;
end;
% nll=length(numleg);
nll=length(test2);
for i=1:nll
	k=0;
	temp=[];
	for j=1:length(test3{i}(:))
		if strcmpi(get(test3{i}(j),'type'),'text')
			dum=get(test3{i}(j),'string');
			if ~isempty(dum)
				k=k+1;
				temp{k}=dum;
			end;
		end;
	end;

% 	legtxt(numleg(nll-i+1)).legend=fliplr(temp);
	legtxt(nll-i+1).legend=fliplr(temp);
end;

for i=1:length(xlabtext)
	delete(xlabtext{i});
end;

%%%%%Added by jpx on 4-29-99%%%Modified on 5-12-99%%%% modified 10-14-99 %%%%

% eval ( 'delete ( timeplt_obj{N}.plot_axes );', '' );

%
% Redo all the axes.
num_axes = max(timeplt_obj{N}.istack(:) );

for i = 1:num_axes
%%%%%%%%%%%modified by c. sullivan 12-08-04%%%%%%%%%
%     h(i) = subplot(num_axes,1,i);
    h(i) = subplot(num_axes,1,i,'align');  
%%%%%%%%%%%modified by c. sullivan 12-08-04%%%%%%%%%    
    if ( ~isempty(timeplt_obj{N}.ylims) )
%%%%%%%%%%%modified by jpx on 12-27-99 %%%%%%%%%%%%%
%         set ( h, 'YLim', timeplt_obj{N}.ylims(i,:) );
        set ( h(i), 'YLim', timeplt_obj{N}.ylims(i,:) );
%%%%%%%%%%%modified by jpx on 12-27-99 %%%%%%%%%%%%%
    end

end

set ( h,     'NextPlot', 'add' );

            
h = flipud(h(:));




jd = timeplt_obj{N}.jd;
data = timeplt_obj{N}.data;
istack = timeplt_obj{N}.istack;


%
% colordef white color scheme line colors
defaultcmap = get ( 0, 'defaultaxescolororder' );
%%%%%%%%%%%modified by jpx on 11-29-2000 %%%%%%%%%%%%%
% if ( size(istack,1) > size(defaultcmap,1) )
%     cmap = jet(size(istack,1));
maxl=0;
for i=1:6
	dumy=length(find(istack==i));
	if dumy>maxl
		maxl=dumy;
	end;
end;

if maxl > size(defaultcmap,1) 
    cmap = jet(maxl);
%%%%%%%%%%%modified by jpx on 11-29-2000 %%%%%%%%%%%%%
else
    cmap = defaultcmap;
end;

axis_color_index = zeros(length(istack),1);


jd0 = gmin(jd(:));
jd1 = gmax(jd(:));

%
% Make the time axis always extend 5 percent past the
% data.
timediff = jd1 - jd0;
xlim = [(jd0 - timediff*0.05) (jd1 + timediff*0.05)];
set ( h, 'XLim', xlim );


%
% plot the data

%%%%%%% added by jpx on 7-20-99 %%%%%%%%%%%%
junky=diff(istack);
junky=[junky(:);1];

%%%%%%% added by jpx on 7-20-99 %%%%%%%%%%%%

for i = 1:length(istack)
    axes ( h(istack(i)) );

	%
	% set the index into the colormap correctly
	% each pane is to be the same as the order for regular matlab plots.
	% While I'm at it, I think I will cure world hunger. 
	axis_color_index(istack(i)) = axis_color_index(istack(i)) + 1;
	
    if ( isreal ( data(:,i) ) )
        graph = plot ( jd, data(:,i),'uicontextmenu',cmenu);
		
        if ( ~isempty(timeplt_obj{N}.ylims) )
            set ( gca, 'YLim', timeplt_obj{N}.ylims(istack(i),:) );
        end
		%%%%%%% added by jpx on 6-23-99 %%%%%%%%%%%%
		if junky(i)==1 & min(min(data(:,i)))<0
% 			if ~isempty(find(data(:,i)<=0))
				plot( [jd0 jd1],[0 0] ,'k');
% 			end;
		end;
		%%%%%%% modified by jpx on 7-20-99 %%%%%%%%%%%%
    else

        %
        % Retrieve the ylims.  If ylims were specified
        % in the timplt call, then it has already been
        % set in the gca.  Otherwise construct it from the
        % data.
%%%%%%%%%%%modified by jpx on 12-27-99 %%%%%%%%%%%%%
        if ( isempty(timeplt_obj{N}.ylims) )
            y0 = min ( gmin(imag(data(:,i))), 0);
            y1 = max ( gmax(imag(data(:,i))), 0);
            ylim = [y0 y1];
            set ( gca, 'YLim', ylim );
        else
%             ylim = get ( gca, 'ylim' );
%             set ( gca, 'YLim', ylim );
			ylim=timeplt_obj{N}.ylims(istack(i),:); 
			set ( gca, 'YLim',ylim );
		end;
%%%%%%%%%%%modified by jpx on 12-27-99 %%%%%%%%%%%%%
        %
        % Construct the scaling factor to accurately do
        % stick plots.
        old_units = get ( gca, 'Units' );
        set ( gca, 'Units', 'Pixels' );
        pos = get ( gca, 'Position' );
        set ( gca, 'Units', old_units );

        scale_factor = (diff(xlim)/diff(ylim)) * (pos(4)/pos(3));

        u_data = scale_factor * real(data(:,i));
        v_data = imag(data(:,i));

        x=jd;
        xp=x;
        yp=zeros(size(xp));
        xplot=ones(length(xp),2);
        yplot=xplot;
        xplot(:,1)=x(:);
        xplot(:,2)=xp(:)+u_data(:);
        xplot(:,3)=x(:);
        yplot(:,1)=yp(:);
        yplot(:,2)=yp(:)+v_data(:);
        yplot(:,3)=yp(:)*nan;
        xplot=xplot';
        yplot=yplot';
        if(~isempty(find(finite(u_data(:)))))
            graph(1) = plot( [jd0 jd1],[0 0],'k' );
            graph(2) = plot ( xplot(:), yplot(:),'uicontextmenu',cmenu);...
        end
            
        
    end
% 	get(graph,'color')
%	index = mod(i-1, length(cmap))+1;
%    set ( graph, 'color', cmap(index,:) );
	set ( graph, 'color', cmap(axis_color_index(istack(i)),:) );

end
		



%
% We want to do our own labels, thank you very much.
set ( h, 'XTickLabel', [] );

%
% What's the separation of the ticks?
xt = get(gca,'XTick' );
xt_sep = max(diff(xt(:)));

axes(h(1));
if (timeplt_obj{N}.year_cut_specified)
    gregax( timeplt_obj{N}.jd,h(1),'year' );
elseif (timeplt_obj{N}.month_cut_specified)
    gregax( timeplt_obj{N}.jd,h(1),'month' );
elseif (timeplt_obj{N}.day_cut_specified)
    gregax( timeplt_obj{N}.jd,h(1),'day' );
elseif (timeplt_obj{N}.hour_cut_specified)
    gregax( timeplt_obj{N}.jd,h(1),'hour' );
elseif (timeplt_obj{N}.minute_cut_specified)
    gregax( timeplt_obj{N}.jd,h(1),'minute' );
elseif ( xt_sep > timeplt_obj{N}.year_cut )
    gregax( timeplt_obj{N}.jd,h(1),'year' );
    timeplt_obj{N}.year_cut_specified = 1;
elseif (xt_sep > timeplt_obj{N}.month_cut) 
    gregax( timeplt_obj{N}.jd,h(1),'month' );
    timeplt_obj{N}.month_cut_specified = 1;
elseif (xt_sep > timeplt_obj{N}.day_cut)
    gregax( timeplt_obj{N}.jd,h(1),'day' );
    timeplt_obj{N}.day_cut_specified = 1;
elseif (xt_sep > timeplt_obj{N}.hour_cut)
    gregax( timeplt_obj{N}.jd,h(1),'hour' );
    timeplt_obj{N}.hour_cut_specified = 1;
else
    gregax( timeplt_obj{N}.jd,h(1),'minute' );
    timeplt_obj{N}.minute_cut_specified = 1;
end


%
% Now make sure that all axes have the same tick marks as the first.
set ( h, 'XTick', get(h(1), 'XTick' ) );

%%%% Modified by jpx %%%%%%
set ( h, 'Box', 'on' );
% The above line is added so boxes are drawn after resizing
%%%% Dec. 4 1998 %%%%%%%%%%    

    
timeplt_obj{N}.plot_axes = h;

%%%%%%%%%%%%%%%%%%Added to accomadate cmgtool%%%%%%%%
for i=1:axhandlength;
   axes(h(i));
	temp=get(h(i),'ylabel');
   set(temp,'string',ylab{i});
   temp=get(h(i),'title');
   set(temp,'string',tit{i});
   if ~isempty(legtxt(i).legend)
	   legend(h(i),char(legtxt(i).legend));
   end;
   if ~isempty(txt{i})
	   text(txtpos{i}(1),txtpos{i}(2),txt{i},'units','norm','color','k');
   end;
end;

%%%%%%%%%%%%%%%%%%Added by jpx on 4-29-99%%%%%%%%%%%


return;

function gregax( jd,xhandle, flags )
month_label = ['Jan';'Feb';'Mar';'Apr';'May';'Jun';...
                'Jul';'Aug';'Sep';'Oct';'Nov';'Dec'];

% First figure out the height of the bottom plot in points.
% Then allow for 3 lines to fit here.
old_units = get ( xhandle, 'Units' );
set ( xhandle, 'Units', 'Points' );
pos = get(xhandle, 'Position' );
set ( xhandle, 'Units', old_units )
height = pos(2);

% Fontsize should be the same as the ylabel.
fsize = get ( get(xhandle,'YLabel'), 'Fontsize' );

% Now figure the height of the bottom plot in user coords.
ylim = get ( xhandle, 'YLim' );
cfactor = diff(ylim) / pos(4);

xt = get ( xhandle, 'XTick' );
greg = gregorian ( xt(:) );
xlim = get(xhandle,'xlim');

% Make sure that the minute ticks start right on the day,
% and not in the middle.
% Stop the ticks somewhere around the end of xlim.  Don't really
% care so much about this.
jd0 = gmin(jd(:)); 
jd1 = xlim(2);
start = gregorian(jd0);
stop = gregorian(jd1);

% We need to know how many labels to write.
% Assume that we want a maximum of 50 pts between labels.
max_width = 40;
point_width = pos(3);  
dx = diff(xlim);
scale_factor = dx/point_width;  % number of days per point

switch flags
case 'day'
	start = [start(1:3) 0 0 0];
	tics = max ( max_width*scale_factor, 1 );
	tics = ceil(tics);
	if ( (tics >= 4) & (tics <6) )
	    tics = 5;
	elseif ( (tics >= 6) & (tics <8.5) )
	    tics = 7;
	elseif ( (tics >= 8.5) & (tics <12) )
	    tics = 10;
	elseif ( (tics >= 12) & (tics <16) )
	    tics = 14;
	end
	jd0 = julian(start);
	xt = [jd0:tics:jd1];
case 'hour'	
	start = [start(1:4) 0 0];
	tics = max_width*scale_factor;
	tics=ceil(tics*24)/24;
	jd0 = julian(start);
	xt = [jd0:tics:jd1];
case 'minute'	
	start = [start(1:5) 0];
	tics = max_width*scale_factor;
	tics=ceil(tics*24*60)/24/60;
	jd0 = julian(start);
	xt = [jd0:tics:jd1];
case 'month'	
	start = [start(1:2) 1 0 0 0];
	tics = ceil(max_width*scale_factor/31);
	gticks = start;
	last_gtick = gticks;
	last_jtick = julian(last_gtick);
	while ( last_jtick <= xlim(2) )
		this_month = last_gtick(2);
		this_year = last_gtick(1);
		if ( (this_month - 1 + tics) >= 12 )
			this_year = this_year+1;
		end
		next_month = mod ( this_month -1 + tics, 12) + 1;
		last_gtick = [this_year next_month 1 0 0 0];
		last_jtick = julian(last_gtick);
		gticks = [gticks; last_gtick ];
	end
	xt = julian(gticks);
case 'year'	
	start1=start(1);
	tics = ceil(max_width*scale_factor/365.24);
	if tics==5 & mod(start1,5)>0
		start1=start1+5 - mod(start1,5);
	elseif tics==10 & mod(start1,10)
		start1=start1+10 - mod(start1,10);
	end;	
	start = [start1 1  1 0 0 0];
	if tics>3 & tics <=5
		tics=5;
	elseif tics>5
		tics=10;
	end;
	gyears = start;
	last_gyear = start; 
	last_jyear = julian(start);
	while ( last_jyear <= jd1 )
		last_gyear(1) = last_gyear(1) + tics;
		last_jyear = julian(last_gyear);
		gyears = [gyears; last_gyear];
	end
	xt = julian(gyears);
end; % of switch	

ifind = find((xt>=xlim(1)) & (xt<=xlim(2)));
if ~isempty(ifind)
	xt = xt(ifind);
	set ( xhandle, ...
	        'XTick', xt, ...
	        'XTickLabel', [] );
	
	greg = gregorian(xt);
	% Now label the xticks
	year_str = num2str(greg(1,1));
	day_str = sprintf ( '%s %2.0f', month_label(greg(1,2),:), greg(1,3) );
	switch flags
	case 'day'
		dum=3;
		gt_string = {     num2str(greg(1,3)); ...
		                month_label(greg(1,2),:); ...
		                num2str(greg(1,1)) };
	case 'hour'
		dum=4;				
		hour_str = sprintf ( '%02i:00', greg(1,4) );
		gt_string = { hour_str; day_str; year_str };
	case 'minute'
		dum=5;
		min_str = sprintf ( '%.0f:%02i', greg(1,4), greg(1,5) );
		gt_string = { min_str; day_str; year_str };
	case 'month'
		dum=2;
		month_str = month_label(greg(1,2),:);
		gt_string = { month_str; year_str };
	end;
	ypoint = ylim(1) - 0.5*fsize*cfactor;
	if isequal(get(xhandle,'ydir'),'reverse')
		ypoint = ylim(2) + 0.5*fsize*cfactor;
	end;
	if isequal(flags,'year')
		year_labels = num2str(greg(:,1));
		set ( xhandle, 'XTickLabel', year_labels );
		return; %DON NOT REMOVE THIS LINE
	else	
		xt_label(1) = text ( xt(1), ypoint, 0, gt_string );
	end;
	
	% Keep track of where to put a label for a new month or year
	% by differencing the gregorian dates.  Any entry that is not zero
	% means that the entry changed from the previous.
	tdiff = diff(greg(:,1:dum));
	thislong=size(tdiff,2);
	for i = 2:length(xt)
	    if ( tdiff(i-1,1)  )
	        year_str = num2str(greg(i,1));
	    else
	        year_str = '';
	    end;
		if thislong>1
		    if ( tdiff(i-1,2)  )
		        month_str = month_label(greg(i,2),:);
		    else
		        month_str = '';
		    end
		end;
		if thislong>2
		    if ( tdiff(i-1,3) )
		        day_str = num2str(greg(i,3));
		    else
		        day_str = '';
		    end
		end;
		if thislong>3
			if ( tdiff(i-1,4)  )
				hour_str = sprintf ( '%02i:00', greg(i,4) );
			else
				hour_str = '';
			end
		end;
		if thislong>4
			if ( tdiff(i-1,5) )
				min_str = sprintf ( '%.0f:%02i', greg(i,4), greg(i,5) );
			else
				min_str = '';
			end
		end;
		switch flags
		case 'day'
		    gt_string = { day_str; month_str; year_str };
		case 'hour'
		    gt_string = { hour_str; day_str; year_str };
		case 'minute'
		    gt_string = { min_str; day_str; year_str };
		case 'month'
		    gt_string = { month_str; year_str };
		end;
	    xt_label(i) = text ( xt(i), ypoint, 0, gt_string );
	end
	set ( xt_label, ...
	        'Fontsize', fsize, ...
	        'HorizontalAlignment', 'Center', ...
	        'VerticalAlignment', 'cap', ...
			'Tag', 'xtick labels');

end;
return;


function xnew=gmin(x)
%function xnew=gmin(x)
% just like min, except that it skips over bad points
[imax,jmax]=size(x);

for j=1:jmax
   good=find(finite(x(:,j)));
   if length(good)>0
       xnew(j)=min(x(good,j));
   else
       xnew(j)=NaN;
   end
end


function xnew=gmax(x)
%function xnew=gmax(x)
% just like max, except that it skips over bad points
[imax,jmax]=size(x);

for j=1:jmax
       good=find(finite(x(:,j)));
       if length(good)>0
          xnew(j)=max(x(good,j));
       else
          xnew(j)=NaN;
       end
end

