classdef SCDclass_mdswgsigarray1 < SCDclass_mdswg
    % This class loads an array of signals from MDS+, linearly indicized
    % linear signal rempping between source and destination can be 
    % specified as a optional parameter, if not present no remapping
    % takes place
    
    properties 
        srcinterval
        dstinterval
        srcstartidx
        srcstopidx
        deststartidx
        deststopidx
    end
    
    methods
    
        %function obj=SCDclass_mdswgsigarray1(srcsrv, srctree, srctdi, modelname, destwavegen, tbstart, tbdt, tbstop, srcstartidx, srcstopidx, deststartidx, deststopidx)
        function obj=SCDclass_mdswgsigarray1(srctdi, destwavegen, srcinterval, varargin)
            obj@SCDclass_mdswg(); 
        
            intervalchecker=@(x) isnumeric(x) && min(diff(x))==1 && max(diff(x))==1; 
            assert(intervalchecker(srcinterval));
            
            obj.cparser.addParameter('destinterval',srcinterval,intervalchecker);
            
            %p=inputParser;
            %p.addParameter('destinterval',srcinterval,intervalchecker);
            %parse(p,varargin{:});
            
            obj=obj.parseconstructor(srctdi, destwavegen, varargin);
            
            dstinterval=obj.cparser.Results.destinterval;
              
            obj.srcstartidx=srcinterval(1);
            obj.srcstopidx=srcinterval(end);
            obj.deststartidx=dstinterval(1);
            obj.deststopidx=dstinterval(end);
            
            obj.classname=mfilename;        
            obj.marteclassname='MDSWgSigArray1';
        end
       
    end
        
    methods 
        
        function actualizedata(obj, shot)
            try
                mdsconnect(obj.mdsserver);
                mdsopen(obj.mdstree, shot);

                targetfullexpansion=[obj.wavegenbasestruct,'.',obj.wavegentarget];

                if obj.verbose==1
                    fprintf('Actualizing wavegen: ''%s'' [%d,%d] <- ''%s'' [%d,%d] (%s, shot %d)\n', ...
                        targetfullexpansion, obj.deststartidx, obj.deststopidx, ...
                        obj.tdiexpr, obj.srcstartidx, obj.srcstopidx, ...
                        obj.classname, shot);
                end

                sourceidxs=obj.srcstartidx:obj.srcstopidx;
                destidxs=obj.deststartidx:obj.deststopidx;            
                assert(numel(sourceidxs)==numel(destidxs), 'SCDclass_mdswgsigarray1: destination channel count is different w.r.t. source');

                value=obj.getdata();

                baseparam=obj.wavegenbasestruct;
                structparam=obj.wavegentarget;

                wgentryval=evalin('base',baseparam);

                getcurrenttssize =sprintf('ddtssamples=numel(wgentryval.%s.Time);',structparam);
                eval(getcurrenttssize);
                if(ddtssamples~=numel(value.Time))
                    % the dd timeseries has different dims w.r.t. the signals
                    % to be loaded, we have to load the timeseries as it is

                    assigncmd   =sprintf('wgentryval.%s=value;',structparam);
                    eval(assigncmd);
                else
                    % the dd timeseries has the same size than the signals
                    % to be loaded, we can do a partial loading

                    assigncmdtime    =sprintf('wgentryval.%s.Time=value.Time;',structparam);
                    assigncmddata    =sprintf('wgentryval.%s.Data(:,%d:%d)=value.Data;',structparam,obj.deststartidx,obj.deststopidx);

                    eval(assigncmdtime);
                    eval(assigncmddata);
                end

                assignin('base','temp',wgentryval);
                assigncmd=sprintf('%s=temp;',baseparam);
                evalin('base',assigncmd);
                evalin('base','clear temp');
            catch ME
                warning('SCDclass_mdswgsigsingle:actualizationerror','Actualization error for wavegen %s. Actualization skipped. Error is:\n%s',obj.wavegentarget,getReport(ME));                
            end
        end        
                     
        function value=getdata(obj)
            value=timeseries;
            
            % Getting the timebase of the model
            tstart=obj.timebasestart;
            dt=obj.timebasedt;
            tstop=obj.timebasestop;
            
            timebase=tstart:dt:tstop;
            sourceidxs=obj.srcstartidx:obj.srcstopidx;
                        
            value.Time = timebase;
            value.Data = single(zeros(numel(timebase), numel(sourceidxs)));
 
            for ii=1:numel(sourceidxs)
               mdschannel=sprintf(obj.tdiexpr,  sourceidxs(ii));
               
               %data=tdi(mdschannel);
               %value.Data(:,ii)= single(interp1(data.dim{1},data.data,timebase,'linear',0));               
            
                dbdata=mdsvalue(mdschannel);
                dbtime=mdsvalue(['dim_of(' mdschannel ')']);
                
                value.Data(:,ii) = single(interp1(dbtime,dbdata,timebase,'linear',0))';
                firstindexes=find(timebase<dbtime(1));
                lastindexes=find(timebase>dbtime(end));
                value.Data(firstindexes,ii)=single(dbdata(1));
                value.Data(lastindexes,ii)=single(dbdata(end));
                
            end    
                
        end
        
        function out=gettargetwavegen(obj)
            if(isempty(obj.wavegenbasestruct))
                out=sprintf('%s[%d,%d]',obj.wavegentarget, obj.deststartidx, obj.deststopidx);
            else
                out=sprintf('%s.%s[%d,%d]',obj.wavegenbasestruct,obj.wavegentarget, obj.deststartidx, obj.deststopidx);
            end                
        end
        
        function printinfo(obj)
            printinfo@SCDclass_mdswg(obj);
            if(obj.srcstartidx~=obj.deststartidx || obj.srcstopidx~=obj.deststopidx)
                fprintf('  Remapping: source interval [%d,%d] remapped into dest. interval [%d,%d]\n', obj.srcstartidx, obj.srcstopidx, obj.deststartidx, obj.deststopidx);         
            end
        end       
        
        function entrystring = genMARTe2entry(obj, shot)            
            if(obj.srcstartidx~=obj.deststartidx || obj.srcstopidx~=obj.deststopidx)
                error('SCDclass_mdswgsigarray1:genMARTe2entry','Signal position remapping not yet implemented in the MARTe version of this class');
            end
            entrystring=obj.genMARTe2entry@SCDclass_mdswg(obj,shot);
            entrystring=[entrystring ' StartIdx=' num2str(obj.srcstartidx) ' StopIdx=' num2str(obj.srcstopidx) ' }'];
        end
       
        
%  *         S_uint8 = {
%  *             NodeName = "S_uint8" // node of the tree node
%  *             Type = "uint8" //Can be any of the node supported types
%  *             NumberOfElements = 32
%  *             DataManagement = 0 //could be 0, 1 or 2
%  *             HoleManagement = 1 //could be 0 or 1
%  *         }
        function expentries = genMARTe2entryexpanded(obj, shot)
            %entrystring=obj.genMARTe2entrycommon(shot);
            
            expentries='';
            for ii=obj.srcstartidx:obj.srcstopidx
               expandedtdi = sprintf(obj.tdiexpr, ii);
               martename=expandedtdi;
               sigentry=sprintf(' %s={ NodeName=%s Type=float32 NumberOfElements=%d DataManagement=0 HoleManagement=1 }\n',martename, expandedtdi); 
               expentries=[expentries sigentry]; 
            end                   
        end
        
        function autopopulatemds(obj, shot)
            baseparam=strrep(obj.wavegenbasestruct,'SCDsimdata','SCDrefdata'); % name of base workspace structure
            
            structparam=obj.wavegentarget; % name of target field
            wgentryval = evalin('base',baseparam); % structure of wavegen in base workspace
                           
            sourceidxs=obj.srcstartidx:obj.srcstopidx;
            destidxs=obj.deststartidx:obj.deststopidx;            
            assert(numel(sourceidxs)==numel(destidxs), 'SCDclass_mdswgsigarray1: destination channel count is different w.r.t. source');

            for ii = obj.deststartidx:obj.deststopidx
                data = wgentryval.(structparam).Data(:,ii);
                dim = wgentryval.(structparam).Time;
                units = wgentryval.(structparam).DataInfo.Units;
                mdschannel=sprintf(obj.tdiexpr,  sourceidxs(ii));
                
                autopopulatemds@SCDclass_mdswg(obj, shot, mdschannel, dim, data, units, [baseparam '.' structparam '[' num2str(ii) ']']);
            end
        end
        
        function out = castdata(obj, in)
            out = single(in);
        end
        
    end
end

