# Published by "Sawdusty" on Thingiverse - 17 April 2013
# http://www.thingiverse.com/thing:75581
# Licensed under the Attribution - Creative Commons license.
#
# Mark Peeters changed this file to output "normed" 0-1 values - November 2013
# this file outputs grey scales (0-255) converted to (0.00-1.00) depthval = 0.003922
# The original output grey scales (0-255) converted to (0.00-7.65) depthval = 0.03

import re
import numpy
import sys

def read_pgm(filename, scaleval):
    #Read image data from an ASCII PGM file and return a numpy array.
    #PGM Format spec: http://netpbm.sourceforge.net/doc/pgm.html
    
    with open(filename, 'r') as f:
        buffer = f.read()
    try:
        header, width, height, maxval = re.search(
            b"(^P2\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
    except AttributeError:
        raise ValueError("Not a raw PGM file: '%s'" % filename)

    vals = buffer.replace(header,"")
    newvals = vals.split(" ")
    newvals.pop(-1)
    image2 = numpy.array([int(x) * scaleval for x in newvals])
    
    return numpy.reshape(image2, (int(height), int(width)))


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "pgm2surf requires two argument values: <input PGM file>, <output DAT file>"
        exit
    else:
        if len(sys.argv) == 4:
            depthval = float(sys.argv[3])
        else:
            depthval = 0.003922
        image = read_pgm(sys.argv[1], depthval)
        numpy.savetxt(sys.argv[2], image, fmt='%2.2f')

