#@ File inputfile

from ij import IJ
from inra.ijpb.label import LabelImages
from ij.measure import ResultsTable
import os.path

path, ext = os.path.splitext(str(inputfile))
parent_dir, filename = os.path.split(path)

label_imp = IJ.openImage(str(inputfile))
IJ.log("remapping labels...")
original_labels = LabelImages.findAllLabels(label_imp)
LabelImages.remapLabels(label_imp)
remapped_labels = LabelImages.findAllLabels(label_imp)
atlas_map = ResultsTable()

for index, value in enumerate(sorted(original_labels)):
    atlas_map.setValue("original labels", index, value)

for index, value in enumerate(sorted(remapped_labels)):
    atlas_map.setValue("remapped labels", index, value)

IJ.log("saving results...")
IJ.run("Input/Output...", "file=.csv save_column save_row")
atlas_map.save(parent_dir + "/" + filename + "_labelmap.csv")
IJ.saveAs(label_imp, "Tiff", parent_dir + "/" + filename + "_remapped.tif")
label_imp.close()
IJ.log("done")