
setwd("")

#biphasic
comp <- read.table(".csv", header=T, sep=",")
plot(comp$S, comp$V)
#smooth data / save picture / write smoothed data to txt
sm1 <- smooth.spline(comp$S, comp$V)  #, spar = 0.5    
x1 <- sm1$x                           # save smoothed data
y1 <- sm1$y
file <- data.frame(S=x1, V=y1)
plot(file,pch=20)# thikness of signal

png('.png',width=680,height=384, bg=NA) # bg: background
plot(file, pch=20, col="black", frame.plot = FALSE, ylim = c(-,), xlim = c(-,), xlab = "", ylab="")#frame.plot= TRUE:keep frame
dev.off()

write.table(file, file="smooth_camp.txt", row.names=FALSE)
EOD <- read.table("smooth_camp.txt", header=T, sep=" ")

#find amplitude
colMax <- function(EOD) sapply(EOD, max, na.rm = TRUE)
colMin <- function(EOD) sapply(EOD, min, na.rm = TRUE)
colMax(EOD)[2]
colMin(EOD)[2]

EOD3 <-EOD[,]
colMin3 <- function(EOD3) sapply(EOD3, min, na.rm = TRUE)
colMax3 <- function(EOD3) sapply(EOD3, max, na.rm = TRUE)
colMax3(EOD3)[2]
colMin3(EOD3)[2]


#calculate % of amplitude
percentP1 <- ((2 * colMax(EOD)[2])/100)
percentP2 <- ((2 * colMin(EOD)[2])/100)

#create new y-axis basis
plot(EOD, pch=".")
abline(h=percentP1, col="red")
abline(h=percentP2, col="blue")

#find points of interesection
			# Points always intersect when above=TRUE, otherwise FALSE
V <- EOD$V
above<-V>percentP1     
intersect.points<-which(diff(above)!=0)
START <- EOD[intersect.points[1],] #red
ENDP1 <- EOD[intersect.points[2],] #green
ENDP3 <- EOD[intersect.points[4],] #blue

above<-V>percentP2     
intersect.points<-which(diff(above)!=0)
ENDP2 <- EOD[intersect.points[2],] #black


abline(v=START[1], col="red")  #start p1
abline(v=ENDP1[1], col="green")  #end p1 & start p2
abline(v=ENDP2[1], col="black") #end P2 & start p3
abline(v=ENDP3[1], col="blue") #end p3

duration <- abs(START[1]) + abs(ENDP3[1])
duration*1000 # = duration in ms total of EOD

durP1 <- (abs(START[1]) + abs(ENDP1[1]))
durP1*1000 # = duration in ms P1

durP2 <- (abs(ENDP2[1]) - abs(ENDP1[1]))
durP2*1000 # = duration in ms P2

durP3 <- (abs(ENDP3[1]) - abs(ENDP2[1]))
durP3*1000 # = duration in ms P3
          



