#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

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

# function that takes names, filepaths and plot plot_id to produce histogram
def plot_names_and_filepaths(names, filepaths, plot_id):
    # save all data in a dict
    all_data = dict()

    # extract data from files
    for i, (name, filepath) in enumerate(zip(names, filepaths)):
        with open(filepath) as fp:
            data = [ line.strip().split(';') for line in fp ]

        # notify user of tallied data
        print(name)
        print(data)

        # process list into dict
        for group, count in data:
            if not group in all_data:
                all_data[group] = [int(count)]
            else:
                all_data[group].append(int(count))

    # flatten dict to format fitting for dataframe (list of lists)
    all_data_list = []
    for key in all_data.keys():
        all_data_list.append([key] + all_data[key])
    print(all_data_list)

    # create dataframe in form of [[group, count1, count2, ...], ...]
    df = pd.DataFrame(all_data_list, columns=["Instruction Groups"] + names)

    # create actual plot
    ax = df.plot( \
            x="Instruction Groups", \
            kind="bar", \
            title="\# Instructions per group across different OS configurations", \
            logy=True, \
            rot=0, \
            #colormap='tab10', \
            width=0.7, \
            figsize=(20, 16))

    # 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.{plot_id}.png')

    # increment plot id
    plot_id += 1

names = [ 'FreeRTOS', 'Zephyr RTOS', 'buildroot 2022.08 Linux 5.17 (glibc + busybox)', 'buildroot 2022.05 Linux 5.18 (uClibc + busybox)' ]
filepaths1 = [ 'count-rv32-freertos-base', 'count-rv32-zephyr-base', 'count-rv32-glibc-busybox-linux-base', 'count-rv32-uclibc-busybox-nommu-linux-base' ]
filepaths2 = [ 'count-rv32-freertos-ext', 'count-rv32-zephyr-ext', 'count-rv32-glibc-busybox-linux-ext', 'count-rv32-uclibc-busybox-nommu-linux-ext' ]

plot_names_and_filepaths(names, filepaths1, 0)
plot_names_and_filepaths(names, filepaths2, 1)
