function [ scaledEeg ] = scaleeeg( inputEeg, channel, rec, maxEeg, reverse )
%scaleeeg Scales Muse EEG data for display in a PTB window
%   Version 2.0
%   inputEeg: channels by samples eeg data
%   channel: which channel to maxEeg (e.g. 1)
%   rec:    the dimensions of the PTB window (e.g. [0 0 800 400])
%   maxEeg:    max absolute EEG value
%   reverse: reverse direction of EEG (right to left instead)

% Time vector
nSamples = length(inputEeg);
times = (1:nSamples) ./ nSamples; % Scaled from 0 to 1

if reverse
    times = 1-times;
end

% EEG vector
inputEeg = inputEeg ./maxEeg; % Scale the rest of the EEG
inputEeg = inputEeg - nanmean(inputEeg) + 0.5; % Baseline correction so that waveforms are centered around 0.5
inputEeg(inputEeg > 1) = 1;
inputEeg(inputEeg < 0) = 0;

thesePoints = [times; inputEeg];

% Shift and scale the points for display
scaleFactor = repmat([rec(3)-rec(1); rec(4)/4],1,nSamples);
shiftFactor = repmat([rec(1); (channel - 1)*rec(4)/4],1,nSamples);
scaledEeg = thesePoints .* scaleFactor + shiftFactor;
end

