##########
args <- commandArgs(T)
arg1 <- args[1]
arg2 <- args[2]
arg3 <- args[3]
#source("~/galaxy-dist/tools/mpdstoolsV2/tool3/Preold.R")
#pre(arg1,arg2,arg3)

pre <- function(args1,args2,args3){
#args <- commandArgs(TRUE)
nTrain <- read.csv(args1,row.names= 1, header = T) # example nTrain.csv file of unknown activity
#save(nTrain,file = "nTrain.RData")
#load("nTrain.RData")
load(args2) # model generated from  previous programn  
newdata <- nTrain
modelFit <- Fit
###########
# input csv file must contaion the exact same column as used in model building #
# Also do pre-proccessing by means of centering and scaling 
## problem in s4 object so first check that the given model has s4 object in
## >isS4(Fit$finalmodel) if it is s4 than add in with elseif loop 
## eg . isS4(plsFit$finalModel) == TRUE

library(caret)

#if(as.character(!isS4(Fit$finalModel == "TRUE")))
if(Fit$method != "svmRadial")
{
	reqcol <- Fit$finalModel$xNames
	newdata <- newdata[,reqcol]
	newdata1 <- preProcess(newdata, method = c("center", "scale"))
	newdata11 <- predict(newdata1,newdata)
###########
	library(stats)
	testpredict <- predict(modelFit,newdata11)
	Label <- levels(testpredict)
	a1 <- Label[1]
	a2 <- Label[2]
	probpredict <- predict(modelFit,newdata11,type="prob")
	names <- as.data.frame(rownames(nTrain))
	colnames(names) <- "COMPOUND"
	activity <- as.data.frame(testpredict)
	colnames(activity) <- "PREDICTED ACTIVITY"
        colnames(probpredict) <- c(eval(a1),eval(a2))
        Prob <- as.data.frame(probpredict)
	dw <- format(cbind(names,Prob,activity),justify="centre")
	write.table(dw,file=args3,row.names=FALSE,sep="\t")
}
else if(Fit$method == "svmRadial")
{        
        library(stats)
	newdata1 <- preProcess(newdata, method = c("center", "scale"))
	newdata11 <- predict(newdata1,newdata)
	#library(stats)
	#testpredict <- predict(modelFit,newdata11)
	#names <- as.data.frame(rownames(nTrain))
	#colnames(names) <- "COMPOUND"
	#activity <- as.data.frame(testpredict)
	#colnames(activity) <- "ACTIVITY"
	#dw <- cbind(names,activity)
	#write.csv(dw,file=args3,row.names=FALSE)
	library(stats)
	testpredict <- predict(modelFit,newdata11)
	Label <- levels(testpredict)
	a1 <- Label[1]
	a2 <- Label[2]
	probpredict <- predict(modelFit,newdata11,type="prob")
	names <- as.data.frame(rownames(nTrain))
	colnames(names) <- "COMPOUND"
	activity <- as.data.frame(testpredict)
	colnames(activity) <- "PREDICTED ACTIVITY"
        colnames(probpredict) <- c(eval(a1),eval(a2))
        Prob <- as.data.frame(probpredict)
        dw <- format(cbind(names,Prob,activity),justify="centre")
	write.table(dw,file=args3,row.names=FALSE,sep="\t")
}
else {
      dw <- "There is something wrong in data or model"
	 write.csv(dw,file=args3,row.names=FALSE)

 }

}
pre(arg1,arg2,arg3)
