## Copyright (C) 200a, 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: gds_plotspectrum(GDSSTRUCT)
## usage: gds_plotspectrum(GDSSTRUCT, @FUNC)
##
## Calculates the spectrum from the oscilloscope waveform data in GDSSTRUCT,
## and plots the spectrum with logarithmic (dBV) amplitude. That is, 
## amplitude values are referenced to 1 Volt.
##
## See also: gds_csvread, gds_spectrum.

## Author: Thomas Weidenfeller
## Created: 2009-06-12
## Version: $Id: gds_plotspectrum.m,v 1.10 2010/12/31 13:05:40 tw Exp $
## Keywords: Oscilloscope, GDS-2000, gds2000tools, fft, spectrum

function gds_plotspectrum (gs, func)

	if(nargin < 1 || nargin > 2 || !isstruct(gs))
		print_usage();
	endif
	if(nargin == 1) 
		func = @hanning;
	endif

	[f, Yabs] = gds_spectrum(gs, func);

	dbflag = 1;	# TODO: Make this an argument to the function
	dbrange = 100;	# Clip dBV range to dbrange dBV
	if(dbflag)
		##
		## Calculate and plot in dBV
		## dBV: Reference is 1 Volt, and Yabs is already in Volts,
		## so no scaling needed.
		##
		YdB = 20 * log10(Yabs);
		plot(f, YdB);
		title(["Spectrum " gs.Source " " gs.Time  " (dBV); " func2str(func) " window" ]);
		ylabel("Amplitude / dBV");

		##
		## Make some room so DC component can be spotted
		## a little bit better. Also clip display to
		## a range of 120 dBV.
		##
		ymax = max(YdB);
		ymin = max([ min(YdB) (ymax - dbrange) ]);
		axis( [ -f(floor(length(f) / 128)) f(length(f)) ymin ymax ]);
	else
		##
		## Linear plot
		##
		plot(f, Yabs);
		title(["Spectrum " gs.Source " " gs.Time " (linear); " func2str(func) " window" ]);
		ylabel([ "Amplitude / " gs.Vertical_Units ]);

		##
		## make some room so DC component can be spotted
		## a little bit better
		##
		axis([-f(floor(length(f) / 128)) f(length(f))]);
	endif
	if(strcmp(gs.Horizontal_Units, "s"))
		xlabel("Frequency / Hz");
	else
		xlabel([ "1 /" gs.Horizontal_Units ]);
	endif
	axis("on");
	grid("on");
	##grid("minor", "on"); # fails in octave 3.0.1
endfunction

%!demo
%! ##gs = gds_csvread("DS0008.CSV"); ## read waveform from file
%! gs = __gds_demo_gs();      ## for now get a demo gds waveform data structure
%! gds_plotspectrum(gs);
