<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def format(amount, currency=None):
 """ Formats a decimal or Money object into an unambiguous string representation for the purpose of invoices in English. :param amount: A Decimal or Money object :param currency: If the amount is a Decimal, the currency of the amount :return: A string representation of the amount in the currency """


    if currency is None and hasattr(amount, 'currency'):
        currency = amount.currency

    # Allow Money objects
    if not isinstance(amount, Decimal) and hasattr(amount, 'amount'):
        amount = amount.amount

    if not isinstance(currency, str_cls):
        raise ValueError('The currency specified is not a string')

    if currency not in FORMATTING_RULES:
        valid_currencies = sorted(FORMATTING_RULES.keys())
        formatted_currencies = ', '.join(valid_currencies)
        raise ValueError('The currency specified, "%s", is not a supported currency: %s' % (currency, formatted_currencies))

    if not isinstance(amount, Decimal):
        raise ValueError('The amount specified is not a Decimal')

    rules = FORMATTING_RULES[currency]

    format_string = ',.%sf' % rules['decimal_places']

    result = builtin_format(amount, format_string)

    result = result.replace(',', '_')
    result = result.replace('.', '|')

    result = result.replace('_', rules['thousands_separator'])
    result = result.replace('|', rules['decimal_mark'])

    if rules['symbol_first']:
        result = rules['symbol'] + result
    else:
        result = result + rules['symbol']

    return result