#
#	File name: pluto_transformation.py
#
#	The pluto_transformation main functions in order to make all operations related with transforming source code or preparing transformation with pluto
#
#	Requires: pluto
#	
#	Verion: 1.0
#	Date created: 28/09/2018
#
#	Author: Charalampos Marantos
#

import sys
import os
import collections
import itertools

# The temp directory to save temporary files
temp_dir = './temp/'

#-----------------------------------------

# This function inserts pragmas for identification of the loops of interest that pluto will transform
def insert_time_pragmas(code, transformation_type, info):
	f1 = open(code.source_file,"r")
	new_file = temp_dir+'temp_source'
	f2 = open(new_file,"wb")
	for i, line in enumerate(f1):
		#if i == 0:
		#	line2 = "#include <time.h>\n"
		#	f2.write(line2)
		### insert pragma scop in the right place for identifying the loop of interest
		if i == int(code.line_start)-1:
			line2 = "struct timeval time0,time1;\n"
			f2.write(line2)
			line2 = "gettimeofday(&time0,NULL);\n"
			f2.write(line2)
		### if there is a pragma from previous transformation in another place remove it
		#elif "#pragma scop" in line:
		#	continue

		if i == int(code.line_end):
			line2 = "gettimeofday(&time1,NULL);\n"
			f2.write(line2)
			line2 = "double totaltime10 = (time1.tv_sec*1000000.0 + time1.tv_usec) - (time0.tv_sec*1000000.0 + time0.tv_usec);\n"
			f2.write(line2)
			line2 = "fprintf(stderr, \"CPU time: %lf msecs\\n\",  (totaltime10)/1000.0F);\n"
			f2.write(line2)

		### if there is a pragma from previous transformation in another place remove it
		#elif "#pragma endscop" in line:
		#	continue

		f2.write(line.replace("\r",""))

	f1.close()
	f2.close()
	os.system("mv "+new_file+" "+code.source_file)