#!/usr/bin/env python3

from PIL import Image
from pprint import pprint

import argparse, sys, time, pickle

ON = 'X'
OFF = '.'
EMPTY = False
hexbug = True

# 128
INTENSITY = 64

parser = argparse.ArgumentParser( description='Display Graphical Image.')
parser.add_argument( 'FILENAME', help='Image file to process' )
parser.add_argument( '--hex', help='Display output in hexadecimal', action="store_true" )
parser.add_argument( '--all', help='Display all of the image.', action="store_true" )
parser.add_argument( '-d', help='Display image.', action="store_true" )
args = parser.parse_args()

filename = args.FILENAME

print("Loading", filename)

im = Image.open(filename)

# pix = im.convert('RGB')  # this is even worse.  No!
pix = im.load()

size = im.size
print("size:",size[0],"x",size[1])

# print im.format, im.size, im.mode, im.info

if im.mode == 'P':
    pal = im.getpalette()
    # print "Palette is:", pal

def img_point(x,y):
    global pix
    return pix[x,y]
    # return pix.getpixel((x,y))

def img_average(x,y):
    global im, pal

    rgb = img_point(x,y)
    # Image is in palette mode, convert from palette
    # index to RGB value.

    if im.mode == 'P':
        # print "rgb=",rgb
        rgb = pal[rgb*3:(rgb+1)*3]
        # print "rgb now:",rgb

    if im.mode == 'I':
        return rgb >> 8

    return int( ( rgb[0] + rgb[1] + rgb[2] ) / 3 )

def is_set(x,y):
    avg = img_average(x,y)
    return (avg < INTENSITY )

# This has start and end ranges to their max values.
sx = 0
ex = size[0]
sy = 0
ey = size[1]

total = 0

def scan_image():
    global sx, ex, sy, ey, total

    total = 0
    # Max out the start and end points.  We adjust 
    # as we find points within the image.

    sx = size[0]; ex = 0
    sy = size[1]; ey = 0

    for y in range( 0,size[1] ):
        for x in range( 0,size[0] ):
            # c = img_point(x,y)
            pnt_is = is_set(x,y)
            if (pnt_is):
                total += 1
                # print (x,y), (sx,ex,sy,ey)
                if x < sx:
                    sx = x
                if x > ex:
                    ex = x
                if y < sy:
                    sy = y
                if y > ey:
                    ey = y

    #print (sx,ex,sy,ey)
    # give us a little border to work with
    if sx > 0:
        sx -= 1
    if ex < size[0]:
        ex += 1

    if sy > 0:
        sy -= 1
    if ey < size[1]:
        ey += 1

    #print (sx,ex,sy,ey)
    return(sx,sy,ex,ey)

scan_image()

print("Character within ({0},{1}) - ({2},{3}) total {4} pixels...".format( sx, sy, ex, ey, total ))


def display_image():
    global args

    if args.all:
        for y in range(0,size[1]):
            s = ''
            for x in range(0,size[0]):
                if args.hex:
                    s += '{0:02X}'.format( img_average(x,y))
                else:
                    if is_set(x,y):
                        s += ON
                    else:
                        s += OFF
            print(s)
        
    else:
        for y in range(sy,ey):
            s = ''
            for x in range(sx,ex):
                if args.hex:
                    s += '{0:02X}'.format( img_average(x,y) )
                else:
                    if is_set(x,y):
                        s += ON
                    else:
                        s += OFF
            print(s)

    print(" --")

def save_image():
    global args
    result = []
    if args.all:
        for y in range(0,size[1]):
            s = ''
            for x in range(0,size[0]):
                if args.hex:
                    s += '{0:02X}'.format( img_average(x,y))
                else:
                    if is_set(x,y):
                        s += ON
                    else:
                        s += OFF
            result.append(s)
        
    else:
        for y in range(sy,ey):
            s = ''
            for x in range(sx,ex):
                if args.hex:
                    s += '{0:02X}'.format( img_average(x,y) )
                else:
                    if is_set(x,y):
                        s += ON
                    else:
                        s += OFF
            result.append(s)
    
    return result

display_image()
img_s = save_image()
img_s.append('net')
#img_s1 = filter_image(img_s)
# print "border:",border

with open('out.txt', 'w') as f:
    for e in img_s
        f.write(e)