#!/usr/bin/python
# Copyright (c) 2015, Michael LeBeane
# The University of Texas at Austin
# The Laboratory for Computer Architecture (LCA)
# All rights reserved.
#
# Redistribution of this source or derived binaries is not authorized without
# the express written consent of the original copyright holders.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Generates McPAT input files by populating a template
# @date: 11/21/2014

import csv
import os
import xml.etree.ElementTree as ET
import shutil
import sys
import collections
import argparse


def generate_mcpat(stats, output_dir, input_proc_model, l3_avail, bin_size, CORES, HW_THREADS, TSC_FREQUENCY):

	print "********** Generating McPAT input files **********"
	shutil.rmtree(output_dir,ignore_errors=True)
	os.makedirs(output_dir)

	# now, import the base McPat config file and augment the runtime statistics with our data
	tree = ET.parse(input_proc_model)
	root = tree.getroot()
	file_num = 0
	
	for time_stamp in stats.itervalues().next().keys():


		total_cycles = []
		idle_cycles = []
		busy_cycles = []

		for i in range(0,HW_THREADS):
			total_cycles.append(stats["CPU" + str(i)][time_stamp]["total_cycles"])
			idle_cycles.append(stats["CPU" + str(i)][time_stamp]["idle_cycles"])
			busy_cycles.append(stats["CPU" + str(i)][time_stamp]["busy_cycles"])
		total_cycles= max(total_cycles)
		idle_cycles = min(idle_cycles)
		busy_cycles = max(busy_cycles)
	
		# cycle information
		# These cycles define the simulation time only, so just express them as the TSC_Frequency into bin szie
		root.find(".//*[@id='system']/stat[@name='total_cycles']").set        ('value',str(bin_size * TSC_FREQUENCY))
		
		d = stats["TOTAL"][time_stamp]
		#l3 stats
		if l3_avail: