## 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: [GDSSTRUCT_SIGN] = gds_sign(GDSSTRUCT)
## usage: [GDSSTRUCT_SIGN] = gds_sign(GDSSTRUCT, EPSILON)
## usage: gds_sign(GDSSTRUCT)
## usage: gds_sign(GDSSTRUCT, EPSILON)
##
## Create a waveform GDSSTRUCT_SIGN, which is 1 V where the waveform 
## in GDSSTRUCT is greater 0 V + EPSILON, -1 V where it is lower
## 0 V - EPSILON, and 0 V otherwise.
##
## EPSILON indicates the margin (in volts) which are considered close
## enough to be counted as 0 V. If not provided, zero is assumed.
##
## If no return value is requested then the data is plotted instead.
##
## Example:
##
## gs = gds_csvread("DS0084.CSV");
## sgn = gds_sign(gs);
## subplot (2,1,1);
## gds_plot(gs);
## subplot (2,1,2);
## gds_plot(sgn);
##
## See also: gds_csvread, gds_csvwrite, gds_ac.

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

function [gsout] = gds_sign(gs, epsilon)
	if(nargin < 1 || nargin > 2 || !isstruct(gs))
		print_usage();
	endif

	if(nargin < 2)
		epsilon = 0;
	endif

	VOLT = 1;

	## Volt to waveform data
	epsilon = gds_val2wd(epsilon, gs.Vertical_Scale);

	##
	## Check if we have the data we should have
	##
	L = __gds_memory_length(gs);

	wd = gs.Waveform_Data;
	pos_ndx = find(wd > epsilon);
	neg_ndx = find(wd < epsilon);

	wdval = gds_val2wd(VOLT, gs.Vertical_Scale);
	gs.Waveform_Data = zeros(L, 1);
	gs.Waveform_Data(pos_ndx) = wdval;
	gs.Waveform_Data(neg_ndx) = -wdval;

	gs.Trigger_Level = 0;	# TODO: should this set to 'dc'?
	gs.Vertical_Position = 0;
	gs.Source = [ gs.Source "-Sign"];

	if(nargout < 1)
		gds_plot(gs);
	else
		gsout = gs;
	endif
endfunction

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