library(ggplot2)
require(reshape2)

crellin.data <- read.csv(commandArgs(T)[1], head=T)
pi.data <- read.delim(commandArgs(T)[2])
prefix <- commandArgs(T)[3]
colnames(pi.data) <- c("var", "value", "utime", "sensor")
#remove the ds1820 for now
pi.data <- pi.data[!(pi.data$var == "temperature" & pi.data$sensor == 1),]
#rename crellin vars
for(i in c(1:length(levels(crellin.data$var)))) {
  lab = levels(crellin.data$var)[i]
  lab = substr(lab,3,nchar(lab))
  if(lab == "Temperature")
    levels(crellin.data$var)[i] <- "temperature"
  else if(lab == "Light_level")
    levels(crellin.data$var)[i] <- "light"
  else if(lab == "Humidity")
    levels(crellin.data$var)[i] <- "humidity"
}
same <- c("temperature", "humidity")
merged <- rbind(cbind(crellin.data[is.element(crellin.data$var, same),c(1,3,4)], src="crellin"), 
                cbind(pi.data[is.element(pi.data$var, same),c(1:3)], src="pi"))
#refactor
merged$var <- factor(merged$var)

#plot
g <- ggplot(merged, aes(x=utime, y=value, colour=src))
cairo_pdf(paste("./plots/",prefix,"_time_series.pdf",sep=""), width = 12, height=6)
print(
g + geom_line() + facet_grid(var~., scales="free")
)
dev.off()


#analyse
m.cast <- dcast(merged, utime + var ~ src)
for (i in c(3:nrow(m.cast))) {
    if(is.na(m.cast$crellin[i]))
        m.cast$crellin[i] <- m.cast$crellin[i-2]
    if(is.na(m.cast$pi[i]))
        m.cast$pi[i] <- m.cast$pi[i-2]
}
filtered <- m.cast[!is.na(m.cast$crellin) & !is.na(m.cast$pi),]
m.cast <- data.frame(filtered,diff=filtered$crellin - filtered$pi)
p <- ggplot(m.cast, aes(x=diff))
cairo_pdf(paste("./plots/",prefix,"_histogram.pdf",sep=""), width = 12, height=6)
print(
p + geom_histogram() + facet_grid(var~., scales="free")
)
dev.off()

