function [cost_tran, cost_state, state, tran, trans_list, transitions]=fsm_sim(connectionMat, states, transitions, name)

% INPUT: fsm_connect - connection matric; Ecost, transition vector
% OUTPUT: 

if ~exist('name', 'var')||isempty(name),
  name = strcat('AutoGen_', datestr(now));   
end

if ~exist('connectionMat','var') || ~exist('states','var'),
    print('Using Default Data');
    connectionMat = [1 1 0 0; 1 0 1 0; 0 1 0 1; 0 0 1 1];
    states = [bin2dec('00') bin2dec('01') bin2dec('10') bin2dec('11')];
end;

if ~exist('transitions','var')||isempty(transitions),
      transitions = randint(1,500,[0,1]);
end;

k = length(transitions);



stimname  = strcat(name, '_stimlen_' , num2str(k),  '.matstim.dat'  );
statename = strcat(name, '_stimlen_' , num2str(k),  '.matstates.dat');
transname = strcat(name, '_stimlen_' , num2str(k),  '.mattrans.dat' );
weightname = strcat(name, '_stimlen_' , num2str(k),  '.matweight.dat');
distname = strcat(name, '_stimlen_' , num2str(k),  '.matdist.dat');


StateEncCost = arrayfun(@(x)eff_ham(x), states);

%Compute the Connection Matrix Cost
connectCost = zeros(size(connectionMat));
for i = 1:size(connectionMat,1)
    for j = (i+1):size(connectionMat,2)
        connectCost(i,j) = eff_ham(bitxor(states(i), states(j)));
    end
end
connectCost = (connectCost + connectCost').*connectionMat;

%Perfom the Simulation

curr_state = 1;
cost_tran = zeros(1,k);
cost_state = cost_tran;

trans_list = cost_tran;
state = cost_tran;

for i = 1:k
    %inx= find(connectionMat(curr_state,:));
    %TODO: Computing the next state probability based on a weight factor
    %next_state = inx(randi(length(inx),1,1));
    %HACK JOB FOR SIMPLE MACHINES_AKA_COUNTERS
    
    if (transitions(i) == 1)
       next_state = (find(connectionMat(curr_state,:)>0,1,'last'));
    else
       next_state = (find(connectionMat(curr_state,:)>0,1));  
    end

    %FAIL! Only works if there are no cycles/null transitions between states e.g. a-b 
    if (next_state == curr_state)
       trans_list(i) = (curr_state > 1);       
    else
       trans_list(i) = (next_state > curr_state);    
    end

    cost_tran(i) = connectCost(curr_state, next_state);
    tran(i) = pow2(curr_state)+pow2(next_state);
    cost_state(i) = StateEncCost(next_state);
    curr_state = next_state;
    state(i) = curr_state;
end

dlmwrite(stimname, transitions) ;
dlmwrite(statename, state) ;
dlmwrite(transname, tran) ;
dlmwrite(weightname, cost_state) ;
dlmwrite(distname, cost_tran) ;

