#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# Copyright (C) 2017 Correlated Solutions, Inc.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# 
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#-----------------------------------------------------------------------------
# This program reads gray values from the deformed TIFF and maps them
# into the data file as a new variable.
#-----------------------------------------------------------------------------

from VicPy import *
from PIL import Image
import sys
import glob
from os import _exit as exit

data = VicDataSet()

if len(sys.argv) != 2:
    print("Usage: %s prefix\n" % sys.argv[0])
    exit(-1)

input_files = glob.glob(sys.argv[1] + "*_0.out")

for filename in input_files:
    if (data.load(filename) == False):
        print("Could not load data set\n\n")
        exit(-1)

    g_var = data.addVariable("G", "Gray Level")

    var_names = ["sigma", "x", "y", "u", "v"]
    aoi = 0
    try:
        im = Image.open(data.deformedImage())
    except IOError:
        print("Error loading image " + data.deformedImage())
        continue

    if (im.mode != "L"):
        im = im.convert("L")

    for aoi in range(data.numData()):
        d = data.data(aoi)
        var_ids = []
        g_idx = d.varIndex(g_var);
        if g_idx < 0:
            print("Could not find variable index for gray value.")
            exit(-1)
        for var in var_names:
            idx = d.varIndex(var)
            if (idx < 0):
                print("Could not find variable %s" % var)
                exit(-1)
            var_ids.append(idx)
            
        for i in range(d.matrixSize()):
            values = d.values(i, var_ids)
            r = 0.0
            if values[0] >= 0:
                x = values[1]
                y = values[2]
                u = values[3]
                v = values[4]
                xprime = x + u
                yprime = y + v
                g = im.getpixel((xprime,yprime))
                d.setValue(i, g_idx, g)

    if data.save(filename) == False:
        print("Could not save the dataset\n\n")
        exit(-1)
