#!/usr/bin/env python3

import matplotlib.pyplot as plt
import pandas as pd

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "sans-serif",
})

files = [
    ['rv32-freertos/dump/main.csr'],
    ['rv32-zephyr/dump/zephyr.csr'],
    ['rv32-glibc-busybox-linux/dump/vmlinux.csr', 'rv32-glibc-busybox-linux/dump/busybox.csr'],
    ['rv32-uclibc-busybox-nommu-linux/dump/vmlinux.csr', 'rv32-uclibc-busybox-nommu-linux/dump/busybox.csr'],
]

names = [
    'FreeRTOS',
    'Zephyr RTOS',
    'Linux (glibc + busybox)',
    'Linux (uClibc + busybox) nommu',
]

short_names = [
    'FreeRTOS',
    'Zephyr RTOS',
    'Linux (glibc)',
    'Linux (uClibc)',
]

data = { 'System': [], 'CSR': [], 'Count': [] }

for name, filelist in zip(names, files):
    for fp in filelist:
        with open(fp) as lines:
            for line in lines:
                count, csr = line.strip().split(' ')
                data['System'].append(name)
                data['CSR'].append(csr)
                data['Count'].append(int(count))

df = pd.DataFrame(data)
#print(df)

# latex table output
print(df.pivot_table(index='CSR', columns='System', values='Count', fill_value='').to_latex(index_names=True, label='table:os-csr-counts', caption='\# CSR occurences compared across systems', header=short_names))

#df2 = df.groupby(['CSR', 'System']).sum()
#print(df2)

#ax = df[df['count'] > 1].groupby(['CSR', 'System']).sum().unstack().plot( \
        #x="Control Status Registers", \
        #kind="bar", \
        #stacked=True, \
        #title="CSRs across different systems", \
        #logy=True, \
        #rot=0, \
        #colormap='tab10_r', \
        #width=0.7, \
        #figsize=(11, 8))

#plt.legend([names[0], names[2], names[3], names[1]], title='Systems')

# modify plot to have grid in the background
#ax.grid(which='major', linestyle='-', linewidth='0.5') #, color='red')
#ax.grid(which='minor', linestyle='--', linewidth='0.4') #, color='red')
#ax.set_axisbelow(True)

# extract figure and save to file
#fig = ax.get_figure()
#fig.savefig(f'histogram.{3}.png')
