# -*- coding: utf-8 -*-

"""
This module contains auxiliary code which might be useful in interactive sessions
"""

import sympy as sp


def multi_str_replace(s, tup_list):
    """
    performs mutltiple consecutive replacements on one string

    tup_list: list of 2-tuples [(old1, new1), (old2, new2), ...]

    returns result string
    """
    for a, b in tup_list:
        s = s.replace(a, b)
    return s


def adapted_latex(obj, printit=True):
    """
    Performs some replacements to latex code (usually generated by sympy).
    Prints the result (by default).
    """

    if hasattr(obj, "to_latex"):
        ltx = obj.to_latex()
    else:
        ltx = sp.latex(obj)

    #print ltx.replace(r'{\left (', ' ').replace(r'\right )}', '').replace(r'\\', r'\\'+'\n')
    rplmts = [(r'{\left (', ' '), # for '\cos\left(' -> '\cos '
              (r'\right )}', ''),
              (r'\\', r'\\' + '\n'),
              (r'\left[', r'\left('),
              (r'\right]', r'\right)'),
              (r'\begin{matrix}', r'\begin{matrix}' + '\n'),
              (r'\end{matrix}', '\n' + r'\end{matrix}')
              ]
    res = multi_str_replace(ltx, rplmts)
    if printit:
        print(res)
        print("% -------------")
    else:
        return res
