#!/usr/bin/env python

from math import ceil, floor

def pages(n_pages_for_display, n_pages, current_page):

    # Return early if no ellipsization is needed
    if n_pages_for_display > n_pages:
        return range(1, n_pages + 1)

    # Begin and end of range surrounding the current page
    n_surrounding = float(n_pages_for_display - 3) / 2
    begin = current_page - int(floor(n_surrounding))
    end = current_page + int(ceil(n_surrounding))

    # Shift right within bounds
    if begin <= 2:
        offset = 2 - begin
        begin += offset
        end += offset

    # Shift left within bounds
    elif end >= n_pages - 1:
        offset = n_pages - end - 1
        begin += offset
        end += offset

    # Number range augmented with first and last page
    pages = range(begin, end + 1)
    pages.insert(0, 1)
    pages.append(n_pages)
    assert len(pages) == n_pages_for_display

    # Left ellipsization if needed (with size of gap as negative number)
    if pages[1] != 2:
        pages[1] = 2 - pages[2]

    # Right ellipsization if needed
    if pages[-2] != n_pages - 1:
        pages[-2] = 1 + pages[-3] - n_pages

    return pages



# Test it
if __name__ == '__main__':
    n_pages_for_display = 9

    print 'display width: %d' % n_pages_for_display
    print

    for n_pages in xrange(n_pages_for_display - 1, n_pages_for_display + 10):
        print 'number of pages: %d' % n_pages
        for page in xrange(1, n_pages + 1):
            out = pages(n_pages_for_display, n_pages, page)
            print 'current page %-2d    %s' % (page, out)
        print

