#
#	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: Nvidia Tegra
#	
#	Verion: 1.0
#	Date created: 28/02/2019
#
#	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_energy_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):
		### insert pragma scop in the right place for identifying the loop of interest
		if i == int(code.line_start)-1:
			line2 = "FILE *fp_energy = fopen(\"./extract_features/module-power-input.txt\",\"a\");\n"
			f2.write(line2)
			line2 = "if(fp_energy) {\n"
			f2.write(line2)
			line2 = "char Buf[7] = \"Start\\n\";\n"
			f2.write(line2)
			line2 = "fwrite(Buf, 1, 6, fp_energy);\n"
			f2.write(line2)
			line2 = "fclose(fp_energy);}\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 = "fp_energy = fopen(\"./extract_features/module-power-input.txt\",\"a\");\n"
			f2.write(line2)
			line2 = "if(fp_energy) {\n"
			f2.write(line2)
			line2 = "char Buf[5] = \"End\\n\";\n"
			f2.write(line2)
			line2 = "fwrite(Buf, 1, 4, fp_energy);\n"
			f2.write(line2)
			line2 = "fclose(fp_energy);}\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)