---------------------------------------------------------------------
-- File    : batch_exporter.ms                                     --
-- Author  : Yannick Puech - puechyannick@yahoo.fr                 --
-- Website : http://ypuechweb.free.fr                              --
--                                                                 --
-- Developped for David Lanier 3D                                  --
-- (3D Tools Freelance Developer,                                  -- 
--  Please visit www.dl3d.com for more info)                       --
--                                                                 --                                                          
-- Made with Maxscript for 3D Studio Max                           --
-- This script is free and can be used / modified / distributed    --
-- freely but at your own risks                                    --
---------------------------------------------------------------------
-- This script export all .MAX files of a directory and its sub-   --
-- directories to a file format choosen by the user                --   
---------------------------------------------------------------------

global g_nf                  -- Rollout floater window
global g_lf                  -- Log file
global g_slf                 -- log file name

fn appendToLog string = (
-- Add string in the log filestream 
   format "%" string to:g_lf
)
 
fn createLogFile dir = (
-- Create a Log file in the directory dir
   
   -- Create log file name
   g_slf = dir + "\\export.txt"
   
   -- Create the log file
   g_lf = createFile g_slf
   
   -- Some informations are added to the log file
   appendToLog "#Log file generated by Batch Exporter\n"
   appendToLog "#For any bug please contact the author at puechyannick@yahoo.fr\n"
   
   -- Write date and hour to the log file
   appendToLog "\n*** Export process started at "
   appendToLog localTime 
   appendToLog " ***\n\n"
)

fn fileExport fToLoad fToExport destdir ext overw = (
-- Export all .MAX files of the directory dir to .ext files in the destdir directory
-- fToLoad, fToExport, destdir and ext : string
-- overw : boolean
   -- Load Max file in the viewports
   loadMaxFile fToLoad quiet:true
   
   -- Export only if file does not exist or if file exist and overwrite mode is set to true
   if ( not doesFileExist fToExport ) or ( doesFileExist fToExport and overw ) then exportFile(fToExport) #noPrompt  

   -- Cleanup file and viewports
   resetMaxFile #noPrompt
)

fn exportDir root dest ext overw = (
-- Export all files of the root directory and its sub-directories
-- root, dest and ext : string
-- overw : boolean 

   -- Create a log file in the input directory
   createLogFile root
   
   -- Get directories and files from the root directory
   dir_array = GetDirectories (root + "\*")
   file_array  = getFiles (root + "\*" + ".MAX")
   nb_files = 0   -- number of exported files
   
   -- Get all sub-directories from the root directory
   for d in dir_array do
       join dir_array (GetDirectories (d+"\*"))
   
   -- Create all new directories
   for d in dir_array do (
       -- Root directory length
       root_length = root.count+1
	   -- Relative path (to the root) length
	   path_rel_length = d.count-root.count
	   -- Creation of the new directory
       makeDir ( dest + substring d root_length path_rel_length )
   )
   
   -- Root directory added to the array of directories to export
   append dir_array root 
   
   -- Cleanup file and viewports
   resetMaxFile #noPrompt

   -- Get all files to export
   for file in dir_array do (
       files = getFiles (file + "\*.MAX")
   	   for f in files do ( 
	       -- Root directory length
           root_length = root.count+1
		   -- Get path of the filename
		   path = getFilenamePath f
		   -- Relative path (to the root) length
	       path_rel_length = path.count-root.count

           -- Making the destination dir and file
	       dir = dest + substring path root_length path_rel_length
		   fname = ( getFilenameFile f ) + "." + ext
		   expf = dir + fname
		   
		   -- export of the current file
	       fileExport f expf dir ext overw
		   sline1 = f + "\n"
		   sline2 = "exported to : " + expf + "\n\n" 
		   
		   appendToLog sline1
		   appendToLog sline2
		   flush g_lf
		   
           nb_files = nb_files + 1      	   
       ) 
    )
	-- Add end time of the export
	appendToLog "*** Export process finished at "
    appendToLog localTime 
    appendToLog " ***\n\n"
	
	-- Put the number of exported files
	appendToLog "Number of exported files : " 
	appendToLog nb_files
	appendToLog "\n"
	
	-- Close the log file
	close g_lf

	-- Execute the log file
    ShellLaunch g_slf ""
) 

rollout rTool "Batch Exporter" width:350 height:300
(
    -- Controls creation
	GroupBox grpDir "Directories" pos:[10,15] width:316 height:134
	label lblID "Input :" pos:[22,38] width:79 height:14 
	button btnBrowseID "Browse" pos:[25,58] width:70 height:20 toolTip:"Choose an input directory"
	edittext editInDir "" pos:[111,58] width:196 height:20
	label lblOD "Output :" pos:[22,93] width:56 height:16
	button btnBrowseOD "Browse" pos:[25,113] width:70 height:20 toolTip:"Choose an output directory"
	edittext editOutDir "" pos:[111,113] width:196 height:20
	GroupBox grpParam "Others Parameters" pos:[10,160] width:316 height:56
	label labelType "Export type :" pos:[32,184] width:59 height:13
	edittext editExt "" pos:[111,184] width:50 height:20
	checkbox chkOWfile "Overwrite existing files" pos:[185,186] width:125 height:15 checked:true
	button btnRun "Run" pos:[10,233] width:316 height:20 toolTip:"Run batch exporter process"
	button btnHelp "Help" pos:[11,268] width:90 height:20 toolTip:"Help on Batch Exporter"
	HyperLink lnk "Author Website" pos:[132,273] width:73 height:15 color:(color 0 0 255) hovercolor:(color 0 0 255) visitedcolor:(color 0 0 192) address:"http://www.freewebs.com/ypuech/"
	button btnAbout "About" pos:[237,269] width:90 height:20 toolTip:"About Batch Exporter"
	
	-- Events handling 
	on btnBrowseID pressed do
	(
	   dir = getSavePath caption:"Choose directory to export :"
	   if dir != undefined then editInDir.text = dir
	)
	on btnBrowseOD pressed do
	(
	   dir = getSavePath caption:"Choose the output directory :"
	   if dir != undefined then editOutDir.text = dir       
	)
	on btnRun pressed do
	(
	   try 
	   (
	      -- Check if the user has entered the directories and file extension
	      if editInDir.text == "" and editOutDir.text == "" and editExt.text == "" then
	          messagebox("Please choose a directory to export, an output directory and an export type (examples : 3ds, ase).")
	      else if  editInDir.text == "" and editOutDir.text == "" then
	          messagebox("Please choose a directory to export and an ouput directory.")
	      else if  editInDir.text == "" then
	          messagebox("Please choose a directory to export.")
	      else if  editOutDir.text == "" then
	          messagebox("Please choose an output directory.")	  
	      else if editExt.text == "" then
	          messagebox("Please enter an export type (examples : 3ds, ase).")
	      else
	          -- Check if the directories exist
		      if not doesFileExist editInDir.text and not doesFileExist editOutDir.text then
	              messagebox(editInDir.text + " and " + editOutDir.text + " directories doesn't exist.\n\nPlease enter other directories.") 	    
	          else if not doesFileExist editInDir.text then
	              messagebox(editInDir.text + " directory doesn't exist.\n\nPlease enter an other input directory.")
	          else if not doesFileExist editOutDir.text then
	              messagebox(editOutDir.text + " directory doesn't exist.\n\nPlease enter an other output directory.")   
		      else -- Export process can begin
	              exportDir editInDir.text editOutDir.text editExt.text chkOWfile.state
		)
		catch
		(
		     appendToLog "\nAn error has occured\n\n"
		)
  	)
	on btnHelp pressed do
	(
	   messagebox("Help :\n\nIn order to export all Max files of a directory and its sub-directories you must :\n\n- Choose valid input and output directories or enter its manually\n- Enter a valid file format extension\n- You can tick on the checkbox if you doesn't want to overwrite existing files\n\nAnd after, click on Run and batch export can begin.\n\nA log file is created in the input directory, it contains informations about the export process.\n\nI hope this help.\nYannick")
	)
	on btnAbout pressed do
	(
	   messagebox("Batch Exporter\n\nYannick Puech for David Lanier 3D (http://www.dl3d.com/)\n\nThis script is free and can be used / modified / distributed freely\nbut at your own risks.")
	)
)

-- To have only one rollout opened at the same time
if g_nf != undefined then closeRolloutFloater g_nf

-- Create the Rollout floater window 
g_nf = newRolloutFloater "Batch Exporter" 350 327
addRollout rTool g_nf 
