"""
================================================================================

    abc2esac - ABC to EsAC conversion
    Copyright (C) 2010, Marcus Weseloh

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

================================================================================
"""

import re

from abcesac.parser import ABCParser
from abcesac.music import Song
from abcesac.formatter import ESACFormatter
from abcesac.grouper import TemperleyGrouper

__version__ = '0.1'

def abc_to_esac(abc, collection=None, prefix='', group=False, meter_cmd=None,
                grouper_cmd=None, grouper_params=None):
    """Convert notes in ABC format to roughly equivalent ESAC"""
    blocks = []
    block = []
    for line in abc.splitlines():
        if line.startswith('X:'):
            if block:
                blocks.append('\n'.join(block))
                block = []
        block.append(line)
    if block:
        blocks.append('\n'.join(block))
    output = []
    for i, block in enumerate(blocks):
        if group:
            grouper = TemperleyGrouper(meter_cmd=meter_cmd,
                                       grouper_cmd=grouper_cmd,
                                       grouper_params=grouper_params)
        else:
            grouper = None
        song = Song()
        ABCParser(song).parse(block)
        song.resolve_repeats()
        output.append(ESACFormatter(collection=collection, prefix=prefix,
                                    index=i, grouper=grouper).to_string(song))
    return '\n\n'.join(output)
