train.data <- read.csv("../input/train/subj1_series1_data.csv", header=TRUE, stringsAsFactors = FALSE)
train.label <- read.csv("../input/train/subj1_series1_events.csv", header=TRUE, stringsAsFactors = FALSE)

train.label.n.frames <- dim(train.label)[1]

train.label$HandStart.up <- pmax(0,c(0,train.label$HandStart[-1] - train.label$HandStart[-train.label.n.frames]))
train.label$FirstDigitTouch.up <- pmax(0,c(0,train.label$FirstDigitTouch[-1] - train.label$FirstDigitTouch[-train.label.n.frames]))
train.label$BothStartLoadPhase.up <- pmax(0,c(0,train.label$BothStartLoadPhase[-1] - train.label$BothStartLoadPhase[-train.label.n.frames]))
train.label$LiftOff.up <- pmax(0,c(0,train.label$LiftOff[-1] - train.label$LiftOff[-train.label.n.frames]))
train.label$Replace.up <- pmax(0,c(0,train.label$Replace[-1] - train.label$Replace[-train.label.n.frames]))
train.label$BothRelease.up <- pmax(0,c(0,train.label$BothRelease[-1] - train.label$BothRelease[-train.label.n.frames]))

##This part is very time consuming, would be interested to have comments on this
train.label$State <- NULL
train.label$State[1] <- 0
for (i in 2:train.label.n.frames)
{
  train.label$State[i] <- (train.label$State[i-1] + sum(train.label[i,8:13])) %% 6
}



filter.smooth.width <- 200
filter.smooth <- rep(1/filter.smooth.width,filter.smooth.width)


window.start <- 60000
window.length <- 60000
window.vector <- window.start:(window.start+window.length)
graphics.off()
par(mfrow=c(4,1), mai=c(0,0,0,0), col="red")
plot(filter(as.matrix(train.data$Cz[window.vector]), filter.smooth, sides=2), type="l", main="Cz, FC5, FC6")
par(new=TRUE, col="green")
plot(filter(as.matrix(train.data$FC5[window.vector]), filter.smooth, sides=2), type="l")
par(new=TRUE, col="blue")
plot(filter(as.matrix(train.data$FC6[window.vector]), filter.smooth, sides=2), type="l")

par( col="red")
plot(filter(as.matrix(train.data$Fz[window.vector]), filter.smooth, sides=2), type="l", main="Fz, F7, F8")
par(new=TRUE, col="green")
plot(filter(as.matrix(train.data$F7[window.vector]), filter.smooth, sides=2), type="l")
par(new=TRUE, col="blue")
plot(filter(as.matrix(train.data$F8[window.vector]), filter.smooth, sides=2), type="l")


par( col="red")
plot(filter(as.matrix(train.data$Pz[window.vector]), filter.smooth, sides=2), type="l", , main="Pz, P7, P8")
par(new=TRUE, col="green")
plot(filter(as.matrix(train.data$P7[window.vector]), filter.smooth, sides=2), type="l")
par(new=TRUE, col="blue")
plot(filter(as.matrix(train.data$P8[window.vector]), filter.smooth, sides=2), type="l")

plot(train.label$State[window.vector], type="l", main="State of the trial, 0 to 5")
print((train.label ))