# addScaleBarToFolder.py
# ----------------------
#
# This script crawls through a folder (and subfolders), opens all TIF files, automatically fixes 
# brightness and contrast, adds a scale bar and resaves the images with an ending as configured
# by the user.
# 
#
# Author: Robert Haase, Scientific Computing Facility, MPI-CBG Dresden,
#         rhaase@mpi-cbg.de
# Date: June 2017
#
# Copyright 2017 Max Planck Institute of Molecular Cell Biology and Genetics,
# Dresden, Germany
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#   1. Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#   2. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#   3. Neither the name of the copyright holder nor the names of its
#      contributors may be used to endorse or promote products derived from
#      this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
#
# Configuration
#



## @File(label = "Input directory", style = "directory") srcFile
## @String(label = "Ouput file extension", value="scalebar.png", choices={"scalebar.tif", "scalebar.png", "scalebar.jpg"}) outputExt
## @String(label = "Color", value="white", choices={"black", "white"}) color

containString = ""
keepDirectories = True
outputExt = "scalebar.png"
inputExt = ".tif"
autoBrightnessContrast = True
do8Bit = True
color = "white"

        

# DO NOT CHANGE ANYTHING BELOW

import os
from ij import IJ, ImagePlus
from java.io import File
from fiji.util.gui import GenericDialogPlus;

extList = ["scalebar.tif", "scalebar.png", "scalebar.jpg"]
colorList = ["black", "white"]


gd = GenericDialogPlus("Add scale bar to all files in a folder");
gd.addDirectoryField("Folder", IJ.getDirectory("current"));
gd.addStringField("Input_file_extension", inputExt);
gd.addChoice("Output_file_extension", extList, outputExt);
gd.addChoice("Color", colorList, color);
gd.addCheckbox("Auto brightness and contrast", autoBrightnessContrast);
gd.addCheckbox("Convert to 8 bit", do8Bit);
gd.showDialog();

srcFile = File(gd.getNextString())
inputExt = gd.getNextString()
outputExt = gd.getNextChoice()
color = gd.getNextChoice()
autoBrightnessContrast = gd.getNextBoolean()
do8bit = gd.getNextBoolean()

dstFile = srcFile

def run():



  srcDir = srcFile.getAbsolutePath()
  dstDir = dstFile.getAbsolutePath()
  for root, directories, filenames in os.walk(srcDir):
    filenames.sort();
    for filename in filenames:
      # Check for file extension
      if not filename.endswith(inputExt):
        continue
      if filename.endswith(outputExt):
        continue
      # Check for file name pattern
      if containString not in filename:
        continue
      process(srcDir, dstDir, root, filename, keepDirectories)
 
def process(srcDir, dstDir, currentDir, fileName, keepDirectories):
  print "Processing:"
   
  # Opening the image
  print "Open image file", fileName
  imp = IJ.openImage(os.path.join(currentDir, fileName))
   
  if (autoBrightnessContrast):
      IJ.run(imp, "Enhance Contrast", "saturated=0.35");
  if (do8Bit):
      IJ.run(imp, "8-bit","")

  # the scale bar should have a length of approx a tenth of the image
  scaleBarLength = imp.getWidth() * imp.getCalibration().pixelWidth / 10;

  exponent = 0

  while(scaleBarLength > 1):
    exponent = exponent + 1
    scaleBarLength = scaleBarLength / 10

  while(scaleBarLength < 1):
    exponent = exponent - 1
    scaleBarLength = scaleBarLength * 10

  if (scaleBarLength >= 8):
    scaleBarLength = 10
	
  if (scaleBarLength > 3 and scaleBarLength < 8):
    scaleBarLength = 5
	
  if (scaleBarLength > 2 and scaleBarLength < 5):
    scaleBarLength = 2

  scaleBarLength = round(scaleBarLength) * pow(10, exponent)

  unit = imp.getCalibration().getUnit()

  if (scaleBarLength < 0 and unit == "µm"):
    scaleBarLength = scaleBarLength * 1000
    imp.getCalibration().setUnit("nm")
  
  if (scaleBarLength < 1 and ((ord(unit[0]) == 181 and ord(unit[1]) == 109) or unit == "microns" or unit == "um")):
    scaleBarLength = scaleBarLength * 1000
    imp.getCalibration().setUnit("nm")
    imp.getCalibration().pixelWidth = imp.getCalibration().pixelWidth * 1000
    imp.getCalibration().pixelHeight = imp.getCalibration().pixelHeight * 1000
    
  fontsize = imp.getHeight() / 50
  scaleBarWidth = imp.getHeight() / 170
  
  if (color == "black"):
    IJ.run(imp, "Scale Bar...", "width=" + str(scaleBarLength) + " height=" + str(scaleBarWidth+6) + " font=" + str(fontsize) + " color=White background=None location=[Lower Right] bold");
    IJ.run(imp, "Scale Bar...", "width=" + str(scaleBarLength) + " height=" + str(scaleBarWidth) + " font=" + str(fontsize) + " color=Black background=None location=[Lower Right] bold");
  else:
    IJ.run(imp, "Scale Bar...", "width=" + str(scaleBarLength) + " height=" + str(scaleBarWidth+6) + " font=" + str(fontsize) + " color=Black background=None location=[Lower Right] bold");
    IJ.run(imp, "Scale Bar...", "width=" + str(scaleBarLength) + " height=" + str(scaleBarWidth) + " font=" + str(fontsize) + " color=White background=None location=[Lower Right] bold");

  # Saving the image
  saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir
  if not os.path.exists(saveDir):
    os.makedirs(saveDir)

  delimiter = "."
  tempArray = fileName.split(delimiter)
  tempArray[len(tempArray) - 1] = ""
  
  newFileName = delimiter.join(tempArray)
  
  print "Saving to", saveDir, newFileName + outputExt
  
  IJ.saveAs(imp, outputExt.replace("scalebar", ""), os.path.join(saveDir, newFileName + outputExt));
  imp.close()

 
if (not gd.wasCanceled()):
	
	run()
print ("Bye.")