package com.elphel.imagej.orthomosaic;

import java.awt.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.elphel.imagej.cameras.CLTParameters;
import com.elphel.imagej.common.ShowDoubleFloatArrays;
import com.elphel.imagej.gpu.GPUTileProcessor;
import com.elphel.imagej.gpu.TpTask;
import com.elphel.imagej.tileprocessor.ImageDtt;
import com.elphel.imagej.tileprocessor.TDCorrTile;

import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.PointRoi;


public class OrthoMapsCollection  implements Serializable{
	private static final long serialVersionUID = 1L;
	public static final String [] KEY_DIRS= {"rootDirectory", // from EyesisCorrectionParameters
			"sourceDirectory","linkedModels","videoDirectory","x3dDirectory","resultsDirectory"};
	OrthoMap []                       ortho_maps;
	transient HashMap<Double,Integer> map_index;
	transient HashMap<String,Integer> map_index_string;
	
	private void writeObject(ObjectOutputStream oos) throws IOException { // ?
		oos.defaultWriteObject();
//		oos.writeObject(path);
		// ortho_maps is not transient
	}
	private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
		ois.defaultReadObject();
		reindex(); // will recreate map_index, map_index_string
		// lla is not transient
	}
	
	public OrthoMapsCollection(
			String path) {
		if (path.endsWith(".list")) {
			String[] paths = getPathsFromSorceList(path);
			double [][] affine = {{1,0,0},{0,1,0}}; // maybe later calculate from mage_enuatr
			ortho_maps = new OrthoMap[paths.length];
			for (int n = 0; n < ortho_maps.length; n++) { 
				ortho_maps[n] = new OrthoMap(paths[n]);
				ortho_maps[n].setAffine(affine);
			}
		}
		Arrays.sort(ortho_maps);
		reindex();
	}
	
	
	public int reindex() {
		map_index = new HashMap<Double,Integer>();
		map_index_string = new HashMap<String,Integer>();
		for (int i = 0; i < ortho_maps.length; i++) {
			map_index.put(ortho_maps[i].ts, i);
			map_index_string.put(ortho_maps[i].name,i);
		}
		return ortho_maps.length;
	}
	
	OrthoMap [] getMaps() {
		return ortho_maps;
	}
	
	public String[] getNames() {
		String [] names = new String [ortho_maps.length];
		for (int n = 0; n < ortho_maps.length; n++) {
			names[n] = ortho_maps[n].getName();
		}
		return names;
	}
	
	public static String[] getPathsFromSorceList(
			String files_list) {
	      List<String> lines;
	        List<String> rel_files = new ArrayList<String>(); 
			Path seq_path = Paths.get(files_list);
			try {
				lines = Files.readAllLines(seq_path, StandardCharsets.UTF_8);
				//                lines.stream().forEach(System.out::println);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			Path base_path = seq_path.getParent();
			HashMap<String,String> dir_map = new HashMap<String,String>();
			for (String line:lines){
				if (line.split("#").length > 0) {
					String[] tokens = line.split("#")[0].trim().split("[\\s,;=]+");
					if ((tokens.length > 2) && (tokens[0].toUpperCase().equals("SET"))) {
						parse_set:
						{
							for (String dir_name:KEY_DIRS) if (dir_name.equals(tokens[1])) {
								dir_map.put(dir_name,tokens[2]);
								System.out.println("Parsed SET: "+tokens[1]+" in line: "+line);
								break parse_set;
							}
							System.out.println("*********** Unknown SET: "+tokens[1]+" in line: "+line);
						}
					} else if ((tokens.length == 1) && (tokens[0].length() > 0)) {
						rel_files.add(tokens[0]);
					}
				}
			}
	        if (dir_map.containsKey("rootDirectory")) {
	        	base_path=base_path.resolve(Paths.get(dir_map.get("rootDirectory")));
				File base_dir = new File(base_path.toString());
	        }
	        String sourceDirectory = base_path.toString();
	        // set sourceDirectory: 
	        if (dir_map.containsKey("sourceDirectory")) {
	        	sourceDirectory=(base_path.resolve(Paths.get(dir_map.get("sourceDirectory")))).toString();
	        }
			Path source_path = Paths.get(sourceDirectory);
//			File source_dir = new File(source_path.toString());
			String [] paths = new String[rel_files.size()];
			for (int i = 0; i < paths.length; i++) {
				paths[i] = (source_path.resolve(Paths.get(rel_files.get(i)))).toString();
			}
		return paths;
	}
	
	
	/**
	 * Get rectified bounds of all provided ortho images relative to the origin (vertical
	 * point) of the first one in pixels at the provided zoom level. Center of the first
	 * image correspond to the {0,0} point from which the bounds are counted
	 * @param zoom_level zoom level - 0 corresponds to 1pix=1cm scale, +1 - to 1pix = 0.5cm
	 * @return {{min_x,max_x},{min_y, max_y}} relative to the origin of the first image
	 */
	public int [][] getBoundsPixels(
			int zoom_level){ // maps[0] as a reference
		double [][] bounds_meters = getBoundsMeters();
		double pix_size = OrthoMap.getPixelSizeMeters (zoom_level);
		int [][] bounds_pix = new int[2][2];
		for (int n = 0; n < bounds_pix.length; n++) {
			bounds_pix[n][0] = (int) Math.floor(bounds_meters[n][0]/pix_size);
			bounds_pix[n][1] = (int) Math.ceil (bounds_meters[n][1]/pix_size);
		}
		return bounds_pix;
	}
	
	/**
	 * Get rectified bounds of all provided ortho images relative to the origin (vertical
	 * point) of the first one in meters
	 * @return {{min_x,max_x},{min_y,max_y}} bounds that include all provided maps
	 *         relative to the origin (vertical point) of the first image
	 */
	public double [][] getBoundsMeters(){ // maps[0] as a reference
		double [][] bounds = ortho_maps[0].getBoundsMeters(true);
		for (int nmap = 1; nmap < ortho_maps.length; nmap++) {
			double [][] bounds_other = ortho_maps[nmap].getBoundsMeters(true);
			double [] enuOffset = ortho_maps[0].enuOffsetTo(ortho_maps[nmap]);
			double [] rd = {enuOffset[0], -enuOffset[1]}; // {right,down} of the image 
			for (int n = 0; n < bounds.length; n++) {
				bounds[n][0] = Math.min(bounds[n][0],bounds_other[n][0]+ rd[n]);
				bounds[n][1] = Math.max(bounds[n][1],bounds_other[n][1]+ rd[n]);
			}
		}
		return bounds;
	}

	/**
	 * Get rectified overlap bounds of two provided ortho images relative to the origin (vertical
	 * point) of the first one in meters. Use specified affine transforms, not saved with the orto map
	 * @param ref_index - index of the first (reference) map
	 * @param other_index - index of the second (other) map
	 * @param ref_affine - specified affine transform of the reference image (referenced to its vertical_point)
	 * @param other_affine - specified affine transform of the other image (referenced to its vertical_point)
	 * @return {{min_x,max_x},{min_y,max_y}} bounds that include an overlap of the two provided maps
	 *         relative to the origin (vertical point) of the first image.
	 * Returns null if there is no overlap
	 */
	private double [][] getOverlapMeters(
			int ref_index,
			int other_index,
			double [][] ref_affine,
			double [][] other_affine){
		double [][] bounds = ortho_maps[ref_index].getBoundsMeters(true,ref_affine);
		double [][] bounds_other = ortho_maps[other_index].getBoundsMeters(true,other_affine);
		double [] enuOffset = ortho_maps[ref_index].enuOffsetTo(ortho_maps[other_index]);
		double [] rd = {enuOffset[0], -enuOffset[1]}; // {right,down} of the image 
		for (int n = 0; n < bounds.length; n++) {
			bounds[n][0] = Math.max(bounds[n][0],bounds_other[n][0]+ rd[n]);
			bounds[n][1] = Math.min(bounds[n][1],bounds_other[n][1]+ rd[n]);
			if (bounds[n][0] > bounds[n][1]) {
				return null;
			}
		}
		return bounds;
	}
	
	
	
	public ImagePlus renderMulti (
			String      title,
			boolean     use_alt,
			boolean     show_centers,
//			OrthoMap [] maps,
			int         zoom_level,
			int []      origin){
		int []     wh = new int[2];
		double [][] centers = new double [ortho_maps.length][];
		float [][] multi = renderMulti (
				use_alt,    // boolean     use_alt,
//				maps,       // OrthoMap [] maps,
				zoom_level, // int         zoom_level,
				wh,         // int []      wh,
				origin,    // int []      origin){ // maps[0] as a reference
				centers); // double [][] centers)
		String [] map_names = new String[ortho_maps.length];
		for (int n = 0; n < ortho_maps.length; n++) { 
			map_names[n] = ortho_maps[n].getName()+"_"+ortho_maps[n].getLocalDateTime().toString().replace("T","_")+"_UTC";
		}
		
        ImageStack stack = ShowDoubleFloatArrays.makeStack( 
        		multi,
        		wh[0],
        		wh[1],
        		map_names,
        		false);
        ImagePlus imp = new ImagePlus(title, stack);
        if (show_centers) {
        	PointRoi roi = new PointRoi();
        	for (int i = 0; i < centers.length; i++) {
        		roi.addPoint(centers[i][0],centers[i][1], i+1);
        	}
        	roi.setOptions("label");
        	imp.setRoi(roi);
        }
        
        return imp;
	}
	
	/**
	 * Rectify and render multiple images (as slices) matching vert_meters to
	 * their (vert_meters points) provided IMS coordinates
	 * @param show altitudes instead of thermal data 
	 * @param maps array of the ortho images 
	 * @param zoom_level zoom level (0 - 1pix=1cm, 1 - 1pix=0.5cm, -1 - 1pix=2cm
	 * @param wh null or int [2], will return {width, height}
	 * @param origin - null or double [2], will return {x0, y0} in pixels
	 * @param centers - null or double[maps.length][] - will return image centers coordinates
	 * @return
	 */
	public float [][] renderMulti (
			boolean     use_alt,
//			OrthoMap [] maps,
			int         zoom_level,
			int []      wh,
			int []      origin, // maps[0] as a reference
			double [][] centers){
		int [][] bounds = getBoundsPixels( // should be for rectified, {-bounds[0][0], -bounds[0][1]} - exact center
				zoom_level);
		int width =  bounds[0][1] - bounds[0][0]; // bounds[x][0] - negative 
		int height = bounds[1][1] - bounds[1][0];
		if (wh != null) {
			wh[0] = width;
			wh[1] = height;
		}
		if (origin != null) {
			origin[0] = -bounds[0][0];
			origin[1] = -bounds[1][0];
		}
		final float [][] fpixels = new float [ortho_maps.length][width * height];
		for (int nmap = 0; nmap< ortho_maps.length; nmap++) {
			final int fnmap = nmap;
			Arrays.fill(fpixels[nmap], Float.NaN);
			final double scale = 1.0/OrthoMap.getPixelSizeMeters(zoom_level);
			final double src_scale = 1.0/OrthoMap.getPixelSizeMeters(ortho_maps[nmap].orig_zoom_level); // pix per meter
		// metric bounds of the rectified image relative to its origin
			double [][] mbounds = ortho_maps[nmap].getBoundsMeters(true);
			double [] enu_offset = ortho_maps[0].enuOffsetTo(ortho_maps[nmap]);
			final double [] scaled_out_center = { // xy center to apply affine to
					-bounds[0][0] + scale * enu_offset[0],
					-bounds[1][0] - scale * enu_offset[1]};
			if (centers != null) {
				centers[nmap] = scaled_out_center;
			}
			final int [][] obounds = new int [2][2]; // output (rectified, combined) image bounds, relative to thje top-left
			for (int n = 0; n< 2; n++) {
				obounds[n][0] = (int) Math.floor(scaled_out_center[n] + scale*mbounds[n][0]);
				obounds[n][1] = (int) Math.ceil (scaled_out_center[n] + scale*mbounds[n][1]);
			}
			// Output window size
			final int ownd_width =  obounds[0][1] - obounds[0][0];
			final int ownd_height = obounds[1][1] - obounds[1][0];
			final int ownd_len = ownd_width * ownd_height;
			double [][] src_bounds=ortho_maps[nmap].getBoundsMeters (true);
			final double [] src_center = {-src_bounds[0][0],-src_bounds[1][0]}; // x,y center offset in the source image
			final double [][] affine = ortho_maps[nmap].affine;
			final int src_width = use_alt? ortho_maps[nmap].getAltData().width: ortho_maps[nmap].getImageData().width;
			final int src_height = use_alt? ortho_maps[nmap].getAltData().height : ortho_maps[nmap].getImageData().height;
			final float [] src_img = use_alt? ortho_maps[nmap].getAltData().data : ortho_maps[nmap].getImageData().data;
			final Thread[] threads = ImageDtt.newThreadArray();
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
					public void run() {
						for (int nPix = ai.getAndIncrement(); nPix < ownd_len; nPix = ai.getAndIncrement()) {
							int opX = nPix % ownd_width + obounds[0][0]; // absolute output pX, pY
							int opY = nPix / ownd_width + obounds[1][0];
							double dX = (opX - scaled_out_center[0]) /scale; // in original image scale 
							double dY = (opY - scaled_out_center[1]) /scale;
							double [] xy_src = { // pixels of the source image
									src_scale * (affine[0][0]*dX + affine[0][1]*dY + affine[0][2] + src_center[0]),
									src_scale * (affine[1][0]*dX + affine[1][1]*dY + affine[1][2] + src_center[1])};
							// limit to the source image
							if  ((xy_src[0] >= 0) && (xy_src[0] < (src_width-1)) &&
									(xy_src[1] >= 0) && (xy_src[1] < (src_height-1))) { 
								int [] ixy_src = {(int) Math.floor(xy_src[0]), (int)Math.floor(xy_src[1]) };
								double [] kxy = {xy_src[0]-ixy_src[0], xy_src[1]-ixy_src[1]}; 
								int indx00 = ixy_src[0] + ixy_src[1] * src_width; 
								double d00 = src_img[indx00];
								if (!Double.isNaN(d00)) {
									double d01 = src_img[indx00 + 1];
									double d10 = src_img[indx00 + src_width];
									double d11 = src_img[indx00 + src_width + 1];
									double d = d00*(1.0 - kxy[0])*(1.0 - kxy[1])+
											d01*       kxy[0] *(1.0 - kxy[1])+
											d10*(1.0 - kxy[0])*       kxy[1]+
											d11*       kxy[0] *       kxy[1];
									fpixels[fnmap][opX + opY*width] = (float) d;
								}
							}
						}
					}
				};
			}		      
			ImageDtt.startAndJoin(threads);
		}
		return fpixels;
	}
	
	public float [][] getPaddedPairGPU(
			String [] spair,
			int       zoom_lev){
		int [] pair = new int [spair.length];
		for (int i = 0; i < pair.length; i++) {
			pair[i] = map_index_string.get(spair[i]);
		}
		return getPaddedPairGPU(
				pair, // int [] pair,
				zoom_lev); // int    zoom_lev,
	}

	private float [][] getPaddedPairGPU(
			int [] pair,
			int    zoom_lev){
		float [][] gpu_pair_img = new  float [2][];
		for (int n = 0; n < pair.length; n++) {
			gpu_pair_img[n] = ortho_maps[pair[n]].getPaddedGPU (
							zoom_lev); // int zoom_level,
		}
		return gpu_pair_img;
	}
	
	/*
	public double [][] correlateOrthoPair(
			CLTParameters    clt_parameters,
			String           first_name,
			String           second_name,
			int              zoom_lev,
			double []        offset_xy_second, // on top of affine and GPS
			final int        debugLevel){
		int first_index = map_index_string.get(first_name);
		int second_index = map_index_string.get(second_name);
		return correlateOrthoPair(
				   clt_parameters,   // CLTParameters    clt_parameters,
				   first_index,      // int              first_index,
				   second_index,     // int              second_index,
				   zoom_lev,         // int              zoom_lev,
				   offset_xy_second, // double []        offset_xy_second, // on top of affine and GPS
				   debugLevel);      // final int        debugLevel)
	}
	
	private double [][] correlateOrthoPair(
			CLTParameters    clt_parameters,
			int              first_index,
			int              second_index,
			int              zoom_lev,
			double []        offset_xy_second, // on top of affine and GPS
			final int        debugLevel){
		int [] gpu_pair = {first_index,second_index};
		double [][][] bounds_out = new double [2][][];
		float [][] gpu_pair_img = new  float [2][];
		for (int n = 0; n < gpu_pair.length; n++) {
			gpu_pair_img[n] = ortho_maps[gpu_pair[n]].getPaddedGPU (
							zoom_lev); // int zoom_level,
		}
		if (debugLevel > 1) {
			String [] map_names = {ortho_maps[gpu_pair[0]].getName(),ortho_maps[gpu_pair[1]].getName()};
			ShowDoubleFloatArrays.showArrays( 
					gpu_pair_img,
					OrthoMap.gpu_width,
					OrthoMap.gpu_height,
					true,
					"gpu_pair-zoom"+zoom_lev+"-"+ortho_maps[gpu_pair[0]].getName()+"-"+ortho_maps[gpu_pair[1]].getName(),
					map_names);
		}
		return null;
	} */
    
	
	public double [][] correlateOrthoPair(
			CLTParameters    clt_parameters,
			String []        gpu_spair,
			double [][][]    affines, // here in meters, relative to vertical points
			int              zoom_lev,
			final int        debugLevel){
		int [] gpu_pair = new int[gpu_spair.length];
		for (int i = 0; i < gpu_pair.length; i++) {
			gpu_pair[i] = map_index_string.get(gpu_spair[i]);
		}
		return correlateOrthoPair(
				clt_parameters, // CLTParameters    clt_parameters,
				gpu_pair, // int []           gpu_pair,
				affines,  // double [][][]    affines, // here in meters, relative to vertical points
				zoom_lev, // int              zoom_lev,
				debugLevel); // final int        debugLevel)
	}
	
	private double [][] correlateOrthoPair(
			CLTParameters    clt_parameters,
			int []           gpu_pair,
			double [][][]    affines,  // here in meters, relative to vertical points
			int              zoom_lev,
			final int        debugLevel){
		boolean show_gpu_img = true; // (debugLevel > 1);
		boolean show_tile_centers = true; // (debugLevel > 1);
		double [][] bounds_overlap_meters = getOverlapMeters(
				gpu_pair[0],  // int ref_index,
				gpu_pair[1],  // int other_index)
				affines[0],   // double [][] ref_affine,
				affines[1]);  // double [][] other_affine
				
		if (bounds_overlap_meters == null) {
			if (debugLevel > -3) {
				System.out.println("correlateOrthoPair(): no overlap");
				return null;
			}
		}
		double pix_size = OrthoMap.getPixelSizeMeters (zoom_lev);
	    int [] overlap_wh_pixel = new int [2];
	    for (int i = 0; i < 2; i++) {
	    	overlap_wh_pixel[i] = ((int) Math.ceil(bounds_overlap_meters[i][1]/pix_size)) - ((int) Math.floor(bounds_overlap_meters[i][0]/pix_size));
	    }
//		double [][] bounds_overlap_pixels = new double[2][2];
		// convert to pixels,shift top-left to [0,0] (remember offsets, limit w,h,
		// change to pixels last, remember TL in meters?
		// keep center where it was
		// {bounds_overlap_meters[0][0],bounds_overlap_meters[1][0],
		double [] enuOffset = ortho_maps[gpu_pair[0]].enuOffsetTo(ortho_maps[gpu_pair[1]]);
		double [] rd = {enuOffset[0], -enuOffset[1]}; // {right,down} of the image 
		double [][] tlo_rect_metric = new double [2][2]; // top-left of overlap referenced to it's own vertical point (subtract!)
		tlo_rect_metric[0][0] = bounds_overlap_meters[0][0]; // relative to ref vert_meters
		tlo_rect_metric[0][1] = bounds_overlap_meters[1][0]; // vert_meters
		tlo_rect_metric[1][0] = bounds_overlap_meters[0][0]  // relative to other vert_meters
				- rd[0]; //  + ortho_maps[gpu_pair[1]].vert_meters[0]- ortho_maps[gpu_pair[0]].vert_meters[0];
		tlo_rect_metric[1][1] = bounds_overlap_meters[1][0]
				- rd[1]; //  + ortho_maps[gpu_pair[1]].vert_meters[1]- ortho_maps[gpu_pair[0]].vert_meters[1];

		double [][] tlo_src_metric = new double[tlo_rect_metric.length][2]; // relative to it's own vert_meters
		for (int n=0; n <tlo_src_metric.length; n++) {
			for (int i = 0; i < 2; i++) { // subtracting tl_rect_metric[n] (-1)
				tlo_src_metric[n][i] =
						tlo_rect_metric[n][0] * affines[n][i][0] +
						tlo_rect_metric[n][1] * affines[n][i][1] + affines[n][i][2]; //  -
//						tl_rect_metric[n][i];
			}
		}
		/// referenced to top-left pixel of the gpu image
		double [][] tlo_source_pixel = new double[tlo_src_metric.length][2];
		for (int n=0; n <tlo_source_pixel.length; n++) {
			for (int i = 0; i < 2; i++) {
				tlo_source_pixel[n][i] = (tlo_src_metric[n][i] + ortho_maps[gpu_pair[n]].vert_meters[i])/pix_size;
			}
		}
		
		double [][][] affines_gpu = new double [affines.length][2][3]; // relative to top left corners, in pixels
		float [][] gpu_pair_img = new  float [2][];
		for (int n = 0; n < gpu_pair.length; n++) {
			for (int i = 0; i < 2; i++) {
				for (int j = 0; j < 2; j++) {
					affines_gpu[n][i][j] = affines[n][i][j]; 
				}
				affines_gpu[n][i][2] = tlo_source_pixel[n][i];
			}
			gpu_pair_img[n] = ortho_maps[gpu_pair[n]].getPaddedGPU (zoom_lev); // int zoom_level,
		}
		if (show_gpu_img) {
			String [] dbg_titles = {ortho_maps[gpu_pair[0]].getName(),ortho_maps[gpu_pair[1]].getName()};
    		ShowDoubleFloatArrays.showArrays(
    				gpu_pair_img,
    				OrthoMap.gpu_width,
    				OrthoMap.gpu_height,
    				true,
    				"gpu_img",
    				dbg_titles);

		}
		Rectangle  woi = new Rectangle(0, 0, overlap_wh_pixel[0], overlap_wh_pixel[1]);
		if (woi.width > OrthoMap.gpu_width) {
			if (debugLevel > -3) {
				System.out.println("correlateOrthoPair() correlation woi.width="+woi.width+" > gpu_width="+OrthoMap.gpu_width+". Truncating.");
			}
			woi.width = OrthoMap.gpu_width;
		}
		if (woi.height > OrthoMap.gpu_height) {
			if (debugLevel > -3) {
				System.out.println("correlateOrthoPair() correlation woi.height="+woi.height+" > gpu_height="+OrthoMap.gpu_height+". Truncating.");
			}
			woi.height = OrthoMap.gpu_height;
		}
		final int  gpu_width = OrthoMap.gpu_width; // static
		// uses fixed_size gpu image size
//		TDCorrTile [] td_corr_tiles =
		TpTask [][] tp_tasks = new TpTask [2][];
		double [][][] vector_field = 
				ComboMatch.rectilinearVectorField(//rectilinearCorrelate_TD( // scene0/scene1
				clt_parameters, // final CLTParameters          clt_parameters,
				gpu_pair_img,        // final float  [][]            fpixels, // to check for empty
				gpu_width,      // final int                    img_width,
				woi, // Rectangle                    woi, // if null, use full GPU window
				affines_gpu,         // final double [][][]          affine,  // [2][2][3] affine coefficients to translate common to 2 images
				tp_tasks, // TpTask [][]                  tp_tasks_o,
				false,          // final boolean                batch_mode,
				debugLevel);    // final int                    debugLevel);
		// may use tl_rect_metric to remap to the original image
		double [][] tile_centers = new double [vector_field[0].length][];
		int tilesX = gpu_width/GPUTileProcessor.DTT_SIZE; 
		for (TpTask task: tp_tasks[1]) {
			int ti = task.getTileY() * tilesX + task.getTileX();
			tile_centers[ti] = task.getDoubleCenterXY();
		}
		if (show_tile_centers){
			double [][] dbg_img = new double [6][tile_centers.length];
			String [] dbg_titles = {"cX","cY","px0","py0", "px1","py1"};
			for (int i = 0; i< dbg_img.length;i++) Arrays.fill(dbg_img[i], Double.NaN);
			for (int t = 0; t < tp_tasks[0].length; t++) {
				TpTask task0 = tp_tasks[0][t];
				TpTask task1 = tp_tasks[1][t];
				int ti = task0.getTileY() * tilesX + task0.getTileX();
				dbg_img[0][ti] = task0.getDoubleCenterXY()[0]; // same for task0, task1 
				dbg_img[1][ti] = task1.getDoubleCenterXY()[1]; 
				dbg_img[2][ti] = task0.getXY()[0][0];
				dbg_img[3][ti] = task0.getXY()[0][1];
				dbg_img[4][ti] = task1.getXY()[0][0];
				dbg_img[5][ti] = task1.getXY()[0][1];
			} // getXY()
    		ShowDoubleFloatArrays.showArrays(
    				dbg_img,
    				tilesX,
    				tile_centers.length/tilesX,
    				true,
    				"tile_centers",
    				dbg_titles);
		}
		
		
		OrthoPairLMA orthoPairLMA = new OrthoPairLMA();
		// vector_field[1] - neighbors
		double lambda =            0.1;
		double lambda_scale_good = 0.5;
		double lambda_scale_bad =  8.0;
		double lambda_max =      100;
		double rms_diff =          0.001;
		int    num_iter =         20;
		boolean last_run =       false;
		orthoPairLMA.prepareLMA(
				// will always calculate relative affine, starting with unity
				tilesX, // int           width,
				vector_field[1], // double [][]   vector_XYS,    // optical flow X,Y, confidence obtained from the correlate2DIterate()
				tile_centers, // double [][]   centers,       // tile centers (in pixels)
				null, // double []     weights_extra, // optional, may be null 
				true, // boolean       first_run,
				debugLevel); // final int     debug_level)
		int lma_rslt = orthoPairLMA.runLma( // <0 - failed, >=0 iteration number (1 - immediately)
				lambda,             // double lambda,           // 0.1
				lambda_scale_good,  // double lambda_scale_good,// 0.5
				lambda_scale_bad,   // double lambda_scale_bad, // 8.0
				lambda_max,         // double lambda_max,       // 100
				rms_diff,           // double rms_diff,         // 0.001
				num_iter,           // int    num_iter,         // 20
				last_run,           // boolean last_run,
				debugLevel);       // int    debug_level)
		System.out.println("LMA result = "+lma_rslt);
// analyze result, re-run correlation
		
/*
		if (show_vector_field) {
			double [][] dbg_vf = new double [3 * vector_field.length][tilesX * tilesY];
			String [] dbg_titles = new String[dbg_vf.length];
			String [] prefix= {"single","neibs"};
			for (int n = 0; n < vector_field.length; n++) {
				dbg_titles [3*n+0] = prefix[n]+"-vx";	
				dbg_titles [3*n+1] = prefix[n]+"-vy";	
				dbg_titles [3*n+2] = prefix[n]+"-str";	
			}
			for (int i = 0; i < dbg_vf.length; i++) {
				Arrays.fill(dbg_vf[i], Double.NaN);
				
			}
			for (int t=0; t<dbg_vf[0].length; t++) {
				for (int n = 0; n < vector_field.length; n++) {
					if (vector_field[n][t] != null) {
						for (int k = 0; k < 3; k++) {
							dbg_vf[n*3 + k][t] = vector_field[n][t][k];
						}
					}
				}
			}
    		ShowDoubleFloatArrays.showArrays(
    				dbg_vf,
    				tilesX,
    				tilesY,
    				true,
    				"vector_field",
    				dbg_titles);
		}

 */
		if (debugLevel > 1) {
			String [] map_names = {ortho_maps[gpu_pair[0]].getName(),ortho_maps[gpu_pair[1]].getName()};
			ShowDoubleFloatArrays.showArrays( 
					gpu_pair_img,
					OrthoMap.gpu_width,
					OrthoMap.gpu_height,
					true,
					"gpu_pair-zoom"+zoom_lev+"-"+ortho_maps[gpu_pair[0]].getName()+"-"+ortho_maps[gpu_pair[1]].getName(),
					map_names);
		}
		return null;
	}


	
	
	
	
	
	
	public static OrthoMapsCollection readOrthoMapsCollection (
			String path) throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream  = new FileInputStream(path);
		ObjectInputStream objectInputStream  = new ObjectInputStream(fileInputStream);
		OrthoMapsCollection orthoMapsCollection = (OrthoMapsCollection) objectInputStream.readObject();
		objectInputStream.close();
		return orthoMapsCollection;
	}
	
	public void writeOrthoMapsCollection (String path) throws IOException {
		FileOutputStream fileOutputStream = new FileOutputStream(path);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
		objectOutputStream.writeObject(this);
	    objectOutputStream.flush();
	    objectOutputStream.close();
	}
	
	
	/*
		float [][] gpu_pair_img = new  float [2][];
		for (int n = 0; n < gpu_pair.length; n++) {
			gpu_pair_img[n] = ortho_maps[gpu_pair[n]].getPaddedGPU (
							zoom_lev, // int zoom_level,
							gpu_width, // int gpu_width,
							gpu_height); // int gpu_height)
		}
map_index_string
	 */
	
	
}
