import os, sys
import matplotlib.pyplot as plt

# Append root dir of this project to include functionality
sys.path.append(os.path.dirname(os.getcwd()))
import binary_c

from utils.defaults import physics_defaults
from utils.functions import create_arg_string

def example_with_loading_default_args():
    """
    Example function loading the default physics args for a binary_c system. Got
    it from the binary_grid2 perl module

    This function works if binary_c is set to log something every timestep so that we can plot the evolution of a system
    """

    # Load args
    physics_args = physics_defaults.copy()

    # Manually set M_1, M_2, orbital_period and separation values:
    physics_args['M_1'] = 20
    physics_args['M_2'] = 15
    physics_args['separation'] = 0 # 0 = ignored, use period
    physics_args['orbital_period'] = 4530.0

    arg_string = create_arg_string(physics_args)
    arg_string = f'binary_c {arg_string}' 

    buffer = ""

    output = binary_c.run_binary(arg_string)

    # Make some 
    results = {}
    time_arr = []
    mass_arr = []
    mass_2_arr = []

    # split output on newlines
    for line in output.split('\n'):
        # Skip any blank lines
        if not line=='':
            split_line = line.split()
            header = split_line[0]
            value_array = split_line[1:]

            # Use parse data here:
            if header=='TESTLOG':
                # Add values to lists
                time_arr.append(float(value_array[0]))
                mass_arr.append(float(value_array[1]))
                mass_2_arr.append(float(value_array[4]))

    # Save in results dir
    results['time'] = time_arr
    results['mass'] = mass_arr
    results['mass2'] = mass_2_arr

    return results

results = example_with_loading_default_args()

# Plot some stuff
plt.plot(results['time'], results['mass'])
plt.plot(results['time'], results['mass2'])
plt.xscale('log')
plt.show()