#!/usr/bin/env python

import agate
import agateexcel
import dbf
import six

from csvkit.convert.fixed import fixed2csv
from csvkit.convert.geojs import geojson2csv

agateexcel.patch()

SUPPORTED_FORMATS = ['csv', 'dbf', 'geojson', 'json', 'ndjson', 'fixed', 'xls', 'xlsx']


def convert(f, format, schema=None, key=None, **kwargs):
    """
    Convert a file of a specified format to CSV.
    """
    if not f:
        raise ValueError('f must not be None')

    if not format:
        raise ValueError('format must not be None')

    if format == 'fixed':
        if not schema:
            raise ValueError('schema must not be null when format is "fixed"')

        return fixed2csv(f, schema, **kwargs)
    elif format == 'geojson':
        return geojson2csv(f, **kwargs)
    elif format in ('csv', 'dbf', 'json', 'ndjson', 'xls', 'xlsx'):
        if format == 'csv':
            table = agate.Table.from_csv(f, **kwargs)
        elif format == 'json':
            table = agate.Table.from_json(f, key=key, **kwargs)
        elif format == 'ndjson':
            table = agate.Table.from_json(f, key=key, newline=True, **kwargs)
        elif format == 'xls':
            table = agate.Table.from_xls(f, sheet=kwargs.get('sheet', None))
        elif format == 'xlsx':
            table = agate.Table.from_xlsx(f, sheet=kwargs.get('sheet', None))
        elif format == 'dbf':
            with dbf.Table(f.name) as db:
                column_names = db.field_names
                table = agate.Table(db, column_names)

        output = six.StringIO()
        table.to_csv(output)
        result = output.getvalue()
        output.close()

        return result
    else:
        raise ValueError('format "%s" is not supported' % format)


def guess_format(filename):
    """
    Try to guess a file's format based on its extension (or lack thereof).
    """
    last_period = filename.rfind('.')

    if last_period == -1:
        # No extension: assume fixed-width
        return 'fixed'

    extension = filename[last_period + 1:].lower()

    if extension == 'xls':
        return extension
    elif extension == 'xlsx':
        return extension
    elif extension in ['json', 'js']:
        return 'json'
    elif extension == 'csv':
        return extension
    elif extension == 'fixed':
        return extension
    elif extension == 'dbf':
        return extension

    return None

@@ -2059,71 +2059,49 @@
 ion 
-== 'xls':%0A        return extension%0A    elif extension ==
+in ('csv', 'dbf', 'fixed', 'xls',
  'xlsx'
+)
 :%0A  
@@ -2186,172 +2186,8 @@
 son'
-%0A    elif extension == 'csv':%0A        return extension%0A    elif extension == 'fixed':%0A        return extension%0A    elif extension == 'dbf':%0A        return extension
 %0A%0A  

Eliminate code duplication