# ServiceTimes-Histogram.R
#/----------------------------------------------------------------------------------------------\
#|	Summary:			With a .txt as input, convert line separated values to a histogram		
#|	Author: 			Ramón L De Jesús				
#|	Start date:			6/25/2013 8:49am						
#|	Last version:		.01								
#\ ---------------------------------------------------------------------------------------------/
#
# This script
# 	-	Creates a .csv file besides the original .txt
# 	-	Displays and saves a .png picture of the histogram plot using R
#
#=====================================================
# Note: R and its dependencies must be installed on the computer
# 			Script only works on linux machines
#			Tested on a VMWare running Ubuntu 12.04 LTS 64-bit
#	~~~~TO RUN:
#	By standalone;
#		Open a terminal and type:
#	$ Rscript ServiceTimes-Histogram.R [nameOfTrace] [folder path] [nameOfFile.csv]
#	WARNING: "/Desktop/TraceFiles/nameOfTrace-DATA/ServiceTimes.csv" MUST EXIST!!!
#=====================================================

#~ Pre-do, aquire Arguments!!!
Args <- commandArgs(TRUE);      # retrieve args

#~Assign #s strings and #i ints
traceName <- Args[1]	#s
newPath <- Args[2]	#s User Working Path
newName <- Args[3]	#s User File Name
title <- paste(traceName, "service times")	#s Title of plot
xTitle <- "Time in usec"	#s Title of x axis in plot
yTitle <- "Total Cycles in usec"	#s Title of y axis in plot
imageName <- paste(traceName, "-ServiceTimes-Histogram.png", sep="")	#s Name of image
workingPath <- sprintf("~/Desktop/TraceFiles/%s-DATA",traceName)	#s Path of the .csv
nameOfFile <- paste(traceName, "-ServiceTimes.csv", sep="")	#s name of the file to plot

#~
if(!is.na(newPath))
{
workingPath <- newPath	
}
if(!is.na(newName))
{
nameOfFile <- newName
}
setwd(workingPath)	# cd to .csv file
data<-read.csv(nameOfFile)	# read from .csv file
png(filename=imageName, width=800, height=800)  # Tell R it's going to output on an image file
# plot the graph and output it to imageName
h<-hist(data$ServiceTimes, col="darkgoldenrod3", labels=TRUE, xlab=xTitle, main=title) 
xfit<-seq(min(data$ServiceTimes),max(data$ServiceTimes)) 
yfit<-dnorm(xfit,mean=mean(data$ServiceTimes),sd=sd(data$ServiceTimes)) 
yfit <- yfit*diff(h$mids[1:2])*length(data$ServiceTimes) 
lines(xfit, yfit, col="blue", lwd=2)
