#!/usr/bin/python
# L-35 MCS 275 Fri 7 Apr 2017 : cookie_counter.py
"""
This scripts counts the number of visits of a web page.
"""
import os
from http.cookies import SimpleCookie

def increment():
    """
    Retrieves cookie, either initializes counter,
    or increments the counter by one.
    """
    if 'HTTP_COOKIE' in os.environ:
        cnt = SimpleCookie(os.environ['HTTP_COOKIE'])
    else:
        cnt = SimpleCookie()
    if 'visits' not in cnt:
        cnt['visits'] = 0
    else:
        cnt['visits'] = str(1 + int(cnt['visits'].value))
    return cnt

def main():
    """
    Retrieves a cookie and writes
    the value of counter to the page,
    after incrementing the counter.
    """
    counter = increment()
    print(counter)
    print("Content-Type: text/plain\n")
    print("counter: %s" % counter['visits'].value)

main()
