function design = caoMakeERms(waitUpFront,nStimTypes,ISIrange,nStim,fixedLength)
% Usage:  design = caoMakeERms(waitUpFront,nStimTypes,ISIrange,nStim,[fixedLength])
%  waitUpFront is the number of TRs before the first stim; nStimTypes is the
%  number of different stimulus types (will be presented equal # of times); 
%  ISIrange is the range of allowed ISI - actual ISIs will be uniformly 
%  distributed across this range; nStim is the number of times *each* stimulus
%  type is presented. If fixedLength (optional) is not provided, the code will 
%  generate a design that has variable length, but is approximately (waitUpFront 
%  + avgISI*nStim) TRs long.  If fixedLength is given, the code will either
%  return an error if fixedLength is less than the generated design vector, or 
%  add zeros at the end of the design matrix so the scan is fixedLength TRs
%  long.
%
%  Adapted from caoMakeER to use G. Buracas' m-sequence code.  His code
%  doesn't support 4 stim types, so a random permutation with exactly
%  nStimTypes*nStim total stim presentations is generated.  But if
%  nStimTypes = 2,3 or 5, then the m-sequence can only take on a few
%  different lengths, and the length closest to nStimTypes*nStim is used
%  ...

% First, generate an m-sequence with the stimuli
if nStimTypes == 4
    stimuli = repmat(1:nStimTypes,[nStim 1]);
else
    seqLength = nStimTypes*nStim;
    baseVal = nStimTypes;
    powerVal = round(log(seqLength-1));
    seq = gbMseq(baseVal,powerVal);
    stimuli = seq + 1 - min(seq);
end

% Then string it out and shuffle it randomly, so it's a list of the stimuli
% in the order they will be presented
stimuli = stimuli(randperm(prod(size(stimuli))));
design = zeros([1 waitUpFront]);
for n = 1:length(stimuli)
    % insert the appropriate stimulus type
    design = [design stimuli(n)];
    % randomly select an ISI from the range
    randomPick = randperm(length(ISIrange));
    ISI = ISIrange(randomPick(1));
    % add the appropriate number of zeros to the design matrix
    design = [design zeros([1 (ISI-1)])];
end

if nargin > 4
    if length(design) > fixedLength
        error('Required design length is greater than requested scan length.');
    else
        design = [design zeros([1 fixedLength - length(design)])];
    end
end