classdef FunctionGenerator < Equipment
    %FUNCTION_GENERATOR Summary of this class goes here
    %   Detailed explanation goes here
    
    properties (Dependent)
		waveform
		frequency
		voltage
		unit
		offset
		load
    end
    
    methods
		function fg = FunctionGenerator(ipAddress,port,channel)
			fg@Equipment(ipAddress,port,channel);
		end

		function w = get.waveform(fg)
			w = FunctionGenerator.getWave(fg.query('FUNCtion:SHAPe?'));
		end
		
		function f = get.frequency(fg)
			f = str2num(fg.query('FREQuency?'));
		end
		
		function v = get.voltage(fg)
			v = str2num(fg.query('VOLTage?'));
		end
		
		function u = get.unit(fg)
			u = FunctionGenerator.getUnit(fg.query('VOLTage:UNIT?'));
		end
		
		function o = get.offset(fg)
			o = str2num(fg.query('VOLTage:OFFSet?'));
		end
		
		function l = get.load(fg)
			o = FunctionGenerator.getLoad(fg.query('OUTPut:LOAD?'));
		end
		
		function fg = set.waveform(fg,w)
			fg.write(['FUNCtion:SHAPe ' FunctionGenerator.getWave(w)]);
		end
		
		function fg = set.frequency(fg,f)
			Equipment.forceNum(f);
			fg.write(['FREQuency ' num2str(f)]);
		end
		
		function fg = set.voltage(fg,v)
			Equipment.forceNum(v);
			fg.write(['VOLTage ' num2str(v)]);
		end
		
		function fg = set.unit(fg,u)
			fg.write(['VOLTage:UNIT ' FunctionGenerator.getUnit(u)]);
		end
		
		function fg = set.offset(fg,o)
			Equipment.forceNum(o);
			fg.write(['VOLTage:OFFSet ' num2str(o)]);
		end
		
		function fg = set.load(fg,l)
			fg.write(['OUTPut:LOAD ' FunctionGenerator.getLoad(l)]);
		end
    end
	
	methods (Static)
		function w = getWave(win)
			w = regexp(num2str(win), '(si|sq|mi|ma|[trndu1-7]|s)', 'match', 'once', 'ignorecase');

			if isempty(w)
				error(['Invalid waveform: ' win]);
			end

			w = regexprep(w, {'^(1|si|(?-i)s)$', '^(2|sq|(?-i)S)$', '^[3t]$', '^[4r]$', '^[5n]$', '^[6d]$', '^[7u]$', '^mi$', '^ma$'}, ...
                {'sinusoid', 'square', 'triangle', 'ramp', 'noise', 'dc', 'user', 'minimum', 'maximum'}, 'ignorecase');
		end
		
		function u = getUnit(uin)
			u = regexp(num2str(uin), '([1-4]|vp|vr|db|de)', 'match', 'once', 'ignorecase');

			if isempty(u)
				error(['Invalid voltage unit: ' uin]);
			end

			u = regexprep(u, {'^(1|vp)$', '^(2|vr)$', '^(3|db)$', '^(4|de)$'}, ...
                {'Vpp', 'Vrms', 'dBm', 'default'}, 'ignorecase');
		end
		
		function l = getLoad(lin)
			l = regexp(num2str(lin), '([12]|50|in|mi|ma)', 'match', 'once', 'ignorecase');

			if isempty(l)
				error(['Invalid load: ' lin]);
			end

			u = regexprep(l, {'^(1|50)$', '^(2|in)$', '^mi$', '^ma$'}, ...
                {'50', 'infinity', 'minimum', 'maximum'}, 'ignorecase');
		end
	end
    
end

