% Input:
% equation: string (containing the linear expression to parse)
% edges: matrix (encoding the automaton)
% expr: cell array of strings (containing the labels of the automaton edges as regular expression)

% Output:
% memory: cell array of structs (containing the parsed symbols)
function [memory] = executeAutomaton(equation,edges,expr)

        if ~isempty(regexp(equation,'\#','ONCE'))
            error('Syntax error: equation %s contains #',equation);
        end;
        equation = [equation '#'];
        memory = cell(0);
        buffer = [];
        state = 1;
                
        %parse equation
        for c=1:length(equation)    % sequential scan of the equation
            
            success = 0;
            consider_edges = edges(edges(:,1) == state,:);
            for k=1:size(consider_edges,1)
                if ~isempty(regexpi(equation(c),expr{consider_edges(k,2)}))
                    % found matching transition
                    
                    % change state
                    state = consider_edges(k,3);
                    % performe action (access to memory)
                    switch (consider_edges(k,4))
                        case 0 
                            %do nothing 
                            
                        case 1 %put constant
                            struct.type = 'const';
                            if strcmp(buffer,'+')
                                struct.value = 1;
                            elseif strcmp(buffer,'-')
                                struct.value = -1;
                            else
                            struct.value = str2double(buffer);
                            end;
                            memory = [memory struct];
                            buffer = [];
                            
                        case 2 %put variable
                            struct.type = 'var';
                            struct.value = buffer;
                            memory = [memory struct];
                            buffer = [];
                        case 3
                            struct.type = 'del';
                            struct.value = buffer;
                            memory = [memory struct];
                            buffer = [];
                    end;
                    % manipulate buffer
                    buffer = [buffer equation(c)];
                    
                    success = 1;
                    break;  % stop looking for matching transitions
                end;
            end;
            
            if state == 7
                error('Syntax error at position %d in flow equation %s',c,equation);
            end;
            
            if ~success && state ~= 6
                error('Equation %d contains an invalid character at position %d',equation,c);
            end;
        end;