#!/usr/bin/env python
import csv
import os
import subprocess
import sys
import urllib
import zipfile


def filter_into_city(filename):
    city = raw_input('\nEnter city [default=None]: ')
    print "Filtering data..."

    if city:
        city = city.upper()
        output_dir = os.path.dirname(os.path.realpath(filename))
        output_file_name = output_dir + '/' + city + '.csv'

        with open(output_file_name, 'w') as output_file:
            # Fill the header
            r_val = subprocess.call(
                ['head', '-n', '1', filename],
                stdout=output_file,
            )
            if r_val > 0:
                print 'There was an error reading the downloaded data.'
                sys.exit(1)

            # Filter in the data
            city_column = 13
            pattern = '^([^,]*,){' + str(city_column) + '}' + city + ','
            r_val = subprocess.call(
                ['grep', '-E', pattern, filename],
                stdout=output_file,
            )
            if r_val > 0:
                print city + ' was not found in the data set.'
                sys.exit(1)

        return output_file_name

    else:
        return filename


def download_data():
    counties = [
        'ADAMS',
        'ALLEN',
        'ASHLAND',
        'ASHTABULA',
        'ATHENS',
        'AUGLAIZE',
        'BELMONT',
        'BROWN',
        'BUTLER',
        'CARROLL',
        'CHAMPAIGN',
        'CLARK',
        'CLERMONT',
        'CLINTON',
        'COLUMBIANA',
        'COSHOCTON',
        'CRAWFORD',
        'CUYAHOGA',
        'DARKE',
        'DEFIANCE',
        'DELAWARE',
        'ERIE',
        'FAIRFIELD',
        'FAYETTE',
        'FRANKLIN',
        'FULTON',
        'GALLIA',
        'GEAUGA',
        'GREENE',
        'GUERNSEY',
        'HAMILTON',
        'HANCOCK',
        'HARDIN',
        'HARRISON',
        'HENRY',
        'HIGHLAND',
        'HOCKING',
        'HOLMES',
        'HURON',
        'JACKSON',
        'JEFFERSON',
        'KNOX',
        'LAKE',
        'LAWRENCE',
        'LICKING',
        'LOGAN',
        'LORAIN',
        'LUCAS',
        'MADISON',
        'MAHONING',
        'MARION',
        'MEDINA',
        'MEIGS',
        'MERCER',
        'MIAMI',
        'MONROE',
        'MONTGOMERY',
        'MORGAN',
        'MORROW',
        'MUSKINGUM',
        'NOBLE',
        'OTTAWA',
        'PAULDING',
        'PERRY',
        'PICKAWAY',
        'PIKE',
        'PORTAGE',
        'PREBLE',
        'PUTNAM',
        'RICHLAND',
        'ROSS',
        'SANDUSKY',
        'SCIOTO',
        'SENECA',
        'SHELBY',
        'STARK',
        'SUMMIT',
        'TRUMBULL',
        'TUSCARAWAS',