
# Copyright 2019 Rich Altmaier  richalt2@yahoo.com
#
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
import sys
import png
import numpy

if len(sys.argv) != 2:
    print("require filename as argument")
    exit()

PNGFilename = sys.argv[1]

#r = png.Reader(filename='200x225-dad.png')
r = png.Reader(filename=PNGFilename)

r.validate_signature()

#x,y,pixels,info = r.asRGBA8()
x,y,pixels,info = r.asDirect()

print ( "//   x", x, "y", y, "pixels", pixels, "info", info)
if info['alpha'] == True:
    datums = 4
else:
    datums = 3

if info['greyscale'] == True:
    print("no decoding of true greyscale PNG format.  Exit.")
    exit()
if info['bitdepth'] != 8:
    print("only understand bitdepth of 8!  Exit.")
    exit()


print("//")
print(PNGFilename.replace(".", "").replace("-", "_"),  " = [")  
firstrow = True
for row in pixels:
    #print("//  row", row)

    # extract the datums from the iterator and stuff into an array.
    # the array allows the indexing needed to calculate!
    firstcol = True
    L = []
    for items in row:
        L = L + [items]

    # Now we have array L !

    #print("//  Llen", len(L), "alpha", info['alpha'], "datums", datums, "greyscale", info['greyscale'])

    if firstrow == True:
        firstrow = False
    else:
        print(",") 

    print(" [", end='')
    firstcol = True
    for pix in range(0, (datums*x)-1, datums):
        #iterate by pixel, which is a variable (datums) number of values.

        #converting RGB to grey, including Alpha if present
        #this is what Photoshop normally outputs for greyscale
        grey = (0.299 * L[pix])  + ( 0.587 * L[pix+1])  + ( 0.114 * L[pix+2]) 
        if info['alpha'] == True:
            greyA = grey * (L[pix+3] / 255.0)
        else:
            greyA = grey

        # print("r", L[pix], "g", L[pix+1], "b", L[pix+2], "grey", grey, "greyA", greyA, end=' ')
        if firstcol is False: 
            print(',', end='')
        else:
            firstcol = False

        print(greyA, end=' ')

    print(" ]", end='')

print("")
print("  ];")

