## Copyright (C) 2009, 2010 Thomas Weidenfeller
## 
## This file is part of gds2000tools/gds-octave.
## 
## gds2000tools/gds-octave is free software: you can redistribute it
## and/or modify it under the terms of the GNU General Public License
## version 3 as published by the Free Software Foundation.
## 
## gds2000tools/gds-octave is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with gds2000tools/gds-octave.  If not,
## see <http://www.gnu.org/licenses/>.
##

## usage: [T0] = gds_zcross(GDSSTRUCT)
## usage: [T0] = gds_zcross(GDSSTRUCT, EPSILON)
## usage: gds_zcross(GDSSTRUCT)
## usage: gds_zcross(GDSSTRUCT, EPSILON)
##
## Calculate the points in time T0 where the waveform data in GDSSTRUCT
## crosses zero. 
##
## EPSILON indicates the margin (in volts) which are considered close
## enough to be counted as 0 V. If not provided, zero is assumed.
##
## Waveform data can be centered around zero by first using gds_ac().
##
## If no return value is requested then the data is plotted instead.
##
## Example:
##
## gs = gds_csvread("DS0084.CSV");
## gs_zcross(gs);
##
## See also: gds_csvread, gds_ac

## Author: Thomas Weidenfeller
## Created: 2009-07-19
## Version: $Id: gds_zcross.m,v 1.8 2010/12/31 13:05:40 tw Exp $
## Keywords: Oscilloscope, GDS-2000, gds2000tools, sign

function [ret] = gds_zcross(gs, epsilon)
	if(nargin < 1 || nargin > 2 || !isstruct(gs))
		print_uasage();
	endif

	if(nargin < 2)
		epsilon = 0;
	endif
	

	##
	## Determine sampling period
	##
	gs.Sampling_Period = __gds_sampling_period(gs);

	if(!isfield(gs, "Horizontal_Position"))
		gs.Horizontal_Position = 0.0;
	endif
	
	##
	## Convert from voltage to sampling units
	##
	epsilon = gds_val2wd(epsilon, gs.Vertical_Scale);

	##
	## Get the zero crossing positions and convert from indice
	## approximations to absolute time values
	##
	## NOTE: Older octave 'signal' packages like v1.0.7 don't contain
	##       a zerocrossing function. Later ones, e.g. v 1.0.11 do.
	##       To ensure gds_zcross() works on both, an own zerocrossing
	##	 function__gds_zcross() is used.
	##
	x_zero = __gds_zcross(gs.Waveform_Data, epsilon) .* gs.Sampling_Period .- gs.Horizontal_Position;

	if(nargout < 1)
		gds_plot(gs);

		oldhold = ishold();
		hold on;

		if(!isempty(x_zero))
			y = gds_wd2val(ones(1, length(x_zero)) .* max(gs.Waveform_Data) ./ 3,  gs.Vertical_Scale);
			stem(x_zero, y);
		endif
		legend(gs.Source, "Zero Crossings");

		if(!oldhold)
			hold off;
		endif
	else
		ret = x_zero;
	endif
endfunction

%!demo
%! ## gs = gds_csvread("DS0084.CSV");  ## read waveform from file
%! gs = __gds_demo_gs(); ## for now get a demo gds waveform data structure
%! subplot(1,1,1);
%! gds_zcross(gs);
