import subprocess
import signal

import struct
import os
import shutil
import datetime
import time

import decimal


##################################	INTERFACE #########################################





tool_path = 'G:\\horizon\\Horizon.exe' #folder with tools
bin_dir = 'G:\\hz\\Image0\\packed_pink' #"root" folder with *.bin files
work_dir = 'G:\\hz\\Image0\\packed_pink\\models\\characters\\robots\\scout' #folder with models for conversion

step_0_create_res_file = False
step_1_unpack_bin = False
step_2_unpack_core = False
step_3_generate_chars = True #(__join_* model)


step3_without_conversion = False # not convert skeletons *.core files. 
								 # Use only existing .SMD and .ASCII files for join chars. 
								 # ONLY for second(thrid, e.t.c.) conversion
								 # You still need the skeletons created in "full" step 3.

step4_convert_robots = True
step4_without_conversion = False #analog step3_without_conversion for step4

#raptor / Thunderjaw  			- normal
#scout / Watcher 				- normal
#spraybot / Fire Bellowback
#stalker / Stalker 
#thunderhawk / Stormbird 
#warrobot / Deathbringer 
#mole / 
#longlegbird /
#laserscout /
#hyena /
#horse / 
#harvester /
#hackbot
#greywolf 
#glider
#giraffe 
#direwolf
#crab
#cargorhino
#bison - repeat
#beachlizard

#longhorn
#goat
#antelope





robot_template_dir =     'G:\\hz\\Image0\\packed_pink\\entities\\characters\\robots\\templates\\archetypes'
robot_template_dlc_dir = 'G:\\hz\\Image0\\packed_pink\\entities\\dlc1\\characters\\robots\\templates\\archetypes'
#####################################################################################
								 
								 
								 
								 
tools_dir = os.path.dirname(tool_path)
logname = "ds_log__" + str(datetime.datetime.now())
logname = logname.replace(" ","_")
logname = logname.replace(":","_")
logname = logname.replace(".","_")
logname = logname + ".txt"
logfile = open(os.path.join(tools_dir,logname),"w")
robot_separate_convert = True
#robot_work_dir = 'E:\\hz\\Image0\\packed_pink\\models\\characters\\robots\\raptor' #folder with models for conversion
create_join_parts = False # create separate file for every model's part and skeleton (__jp_* model)



# create a new context for this task
ctx = decimal.Context()

# 20 digits should be enough for everyone :D
ctx.prec = 20

def float_to_str(f, perc = 0):
	"""
	Convert the given float to a string,
	without resorting to scientific notation
	"""
	d1 = ctx.create_decimal(repr(f))
	rstr = format(d1, 'f')
	offset = rstr.find(".")
	if((len(rstr) - offset) == 2 ): rstr = rstr + "00000"
	if((len(rstr) - offset) == 3 ): rstr = rstr + "0000"
	if((len(rstr) - offset) == 4 ): rstr = rstr + "000"
	if((len(rstr) - offset) == 5 ): rstr = rstr + "00"
	if((len(rstr) - offset) == 6 ): rstr = rstr + "0"
	return rstr


def print_fork(in_str):
	print(in_str)
	logfile.write(in_str + "\n")
	logfile.flush()
	
	
	
	
	
	
def fast_ascii_test(fname):
	try:
		data = []
		with open(fname) as f:
			#data = f.readlines()
			data = f.read().splitlines()
		
		i = 0;
		skip_str = True
		while (i < len(data)):
			if(skip_str):
				if(data[i].isdigit()):
					print("					FAST: SKIP " + data[i])			
					i = i +1
				else:
					skip_str = False
			
			if(not skip_str):
				mesh_name = data[i]
				print_fork("					FAST: line " + str(i) + " - mesh_name " + mesh_name)
				if(i + 2 >= len(data)):
					print_fork("					FAST ERROR 1: line " + str(i) + " - unexpected end of file")
					return False
				
				i = i + 1
				if(not data[i].isdigit()):
					print_fork("					FAST ERROR 2: line " + str(i) + " - uncorrect numUVlayers")
					return False
				numUVlayers = int(data[i])
				
				i = i + 1
				if(not data[i].isdigit()):
					print_fork("					FAST ERROR 3: line " + str(i) + " - uncorrect numTextures")
					return False
				numTextures = int(data[i])
				i = i + 1
				
				if (i + numTextures * 2 + 1 >= len(data)):
					print_fork("					FAST ERROR 4: line " + str(i) + " - unexpected end of file")
					return False
				
				for d in range(0,numTextures):
					print_fork("					FAST: line " + str(i) + " texture " + data[i+d])
					i = i + 2
					
				if(not data[i].isdigit()):
					print_fork("					FAST ERROR 5: line " + str(i) + " - uncorrect vertex number " + data[i])
					return False
					
				numVertices = int(data[i])
				print_fork("					FAST: line " + str(i) + " numVertices " + str(numVertices))
				i = i + 1
				
				#coord
				#normal
				#vertex_color
				#x * UV
				#indices
				#weights
				vert_size = 5 + numUVlayers
				
				i = i + vert_size * numVertices
				if(i >= len(data)):
					print_fork("					FAST ERROR 6: line " + str(i) + " - unexpected end of file")
					return False
				
				if(not data[i].isdigit()):
					print_fork("					FAST ERROR 7: line " + str(i) + " - uncorrect faces number " + data[i])
					return False	

				numFaces = int(data[i])
				print_fork("					FAST: line " + str(i) + " numFaces " + str(numFaces))
				i = i + 1
				
				i = i + numFaces
				if(i > len(data)):
					print_fork("					FAST ERROR 8: line " + str(i) + "- unexpected end of file")
					return False
	except Exception:
		print_fork("					FAST ERROR 0: - Unknown Exception")
		return False

			
			

				
		
	#for dstr in data:
	#	print(dstr)
	return True
	
	
	
	
	
	
	
	
	
	
	
def join_ascii(fname, skel_file, static_files , skinned_files)	:
	print_fork("		join_ascii:")
	print_fork("		fname: " + fname)
	print_fork("		skel_file: " + skel_file)
	with open(fname, 'wt') as output_file: 
		strlist = []
		num_mat = 0
		with open(skel_file, 'rt') as skel_fl: 
			for line in skel_fl:
				output_file.write(line[:-1] + '\n')
				
		print_fork("		join skinned files:")
		
		for dno in skinned_files:
			print_fork("			join skinned file: " + dno)
			wrt = False
			if(fast_ascii_test(dno)):
				dno_fl = []
				with open(dno, "rt") as f:
					dno_fl = f.read().splitlines()

				for line in dno_fl:
					if(not line.isdigit()): wrt = True
					else:
						#if(not wrt): print("SKIP	" + line[:-1])
						pass
					if(wrt):
						strlist.append(line)
						if (line.find("material")>=0): num_mat = num_mat +1
							
			print_fork("			" + dno + "  num_mat " + str(num_mat))							
							
							
		print_fork("		join static files:")
		
		
		for dno in static_files:
			print_fork("			join static file: " + dno)
			wrt = False

			if(fast_ascii_test(dno)):
				dno_fl = []
				with open(dno, "rt") as f:
					dno_fl = f.read().splitlines()

				for line in dno_fl:
					if(not line.isdigit()): wrt = True
					else:
						#if(not wrt): print("SKIP	" + line[:-1])
						pass
					if(wrt):
						strlist.append(line)
						if (line.find("material")>=0): num_mat = num_mat +1
						
			print_fork("			" + dno + "  num_mat " + str(num_mat))
				
		output_file.write(str(num_mat) + '\n')	
		for line in strlist:
				output_file.write(line + '\n')	
				
	print_fork("			Join complete")
				

	
	
	
def join_smd(fname, skel_file, static_files , skinned_files)	:
	print_fork("		join_smd:")
	print_fork("		fname: " + fname)
	print_fork("		skel_file: " + skel_file)
	with open(fname, 'wt') as output_file: 
		strlist = []
		num_mat = 0
		with open(skel_file, 'rt') as skel_fl: 
			for line in skel_fl:
				output_file.write(line[:-1] + '\n')
				
		print_fork("		join skinned files:")
		
		for dno in skinned_files:
			print_fork("			join skinned file: " + dno)
			wrt = False
			if(True):#fast_ascii_test(dno)):
				dno_fl = []
				with open(dno, "rt") as f:
					dno_fl = f.read().splitlines()

				for line in dno_fl:
					if(line.find("triangles") >= 0): wrt = True
					else:
						#if(not wrt): print("SKIP	" + line[:-1])
						pass
					if(wrt):
						strlist.append(line)
						if (line.find("material")>=0): num_mat = num_mat +1
							
			print_fork("			" + dno + "  num_mat " + str(num_mat))							
							
							
		print_fork("		join static files:")
		
		
		for dno in static_files:
			print_fork("			join static file: " + dno)
			wrt = False

			if(True):#fast_ascii_test(dno)):
				dno_fl = []
				with open(dno, "rt") as f:
					dno_fl = f.read().splitlines()

				for line in dno_fl:
					if(line.find("triangles") >= 0): wrt = True
					else:
						#if(not wrt): print("SKIP	" + line[:-1])
						pass
					if(wrt):
						strlist.append(line)
						if (line.find("material")>=0): num_mat = num_mat +1
						
			print_fork("			" + dno + "  num_mat " + str(num_mat))
				
		output_file.write('end\n')	
		for line in strlist:
				output_file.write(line + '\n')	
				
	print_fork("			Join complete")



class ascii_bone(object):
	def __init__(self):
		self.id = -1
		self.name = ""
		self.root = ""
		self.root_index = -1
		self.coord_x = 0
		self.coord_y = 0
		self.coord_z = 0
		self.rotation_x = 0
		self.rotation_y = 0
		self.rotation_z = 0

		
	def __str__(self):
		tmpr = "---"
		if(len(self.root)>0): tmpr = self.root
			
		
		return str(self.id) + "\t" + self.name + "\t" + tmpr + "\t" + str(self.coord_x) + " " + str(self.coord_y) + " " + str(self.coord_z) + " " +  str(self.rotation_x) + " "  +  str(self.rotation_y) + " " +  str(self.rotation_z)
	

	
	
class ascii_skeleton(object):
	def __init__(self):
		self.time = []
		
	def read_skeleton(self, fname):
		strs = []
		with open(fname, 'r') as f:
			strs = f.read().splitlines()
			
		num_bones = int(strs[0].strip())
		i = 1
		cur_bone = 0
		tmp_aray = []

		while(i < len(strs)):
			if(cur_bone < num_bones):
				bone = ascii_bone()
				bone.name = strs[i].strip()
				bone.root_index = int(strs[i + 1].strip())
				if(bone.root_index >= 0): bone.root = tmp_aray[bone.root_index].name
				tmp2 = (strs[i+2].strip()).split()
				#print(tmp2)
				if(len(tmp2)>=3):
					bone.coord_x = float(tmp2[0])
					bone.coord_y = float(tmp2[1])
					bone.coord_z = float(tmp2[2])
				if(len(tmp2)>=6):
					bone.rotation_x = float(tmp2[3])
					bone.rotation_y = float(tmp2[4])
					bone.rotation_z = float(tmp2[5])
				bone.id = len(tmp_aray)
				cur_bone = len(tmp_aray)
				print(bone)
				tmp_aray.append(bone)
				i = i + 3

			else: break
			
		self.time = []
		self.time.append(tmp_aray[:])

		
	def anim_to(self,anim_skel,mi,hi):
		my_tmp_bones = self.time[mi][:]
		his_tmp_bones = anim_skel.time[hi][:]
		
		for i in range (0,len(my_tmp_bones)):
			for j in range(0,len(his_tmp_bones)):
				if(my_tmp_bones[i].name == his_tmp_bones[j].name):
					my_tmp_bones[i].coord_x = his_tmp_bones[j].coord_x
					my_tmp_bones[i].coord_y = his_tmp_bones[j].coord_y
					my_tmp_bones[i].coord_z = his_tmp_bones[j].coord_z
					my_tmp_bones[i].rotation_x = his_tmp_bones[j].rotation_x
					my_tmp_bones[i].rotation_y = his_tmp_bones[j].rotation_y
					my_tmp_bones[i].rotation_z = his_tmp_bones[j].rotation_z
		self.time[mi] = my_tmp_bones[:]
					
		
	def save_to(self,fname, writeEnd):
		file = open(fname, "w")
		file.write(str(len(self.time[0])) + "\n")
		for i in range(0, len(self.time[0])):
			file.write((self.time[0][i].name) + "\n")
			write_root = -1
			for bn in self.time[0]:
				if(bn.name == self.time[0][i].root):
					write_root = bn.id
			file.write(str(write_root))
			file.write("\n")

			file.write(float_to_str(self.time[0][i].coord_x))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].coord_y))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].coord_z))
			file.write("\n")
			
		if(writeEnd): file.write("0\n")
		file.close()

		
	def to_zero_skel(self, anim_skel):
		my_tmp_bones = self.time[0][:]
		my_tmp_bones2 = []
		his_tmp_bones = anim_skel.time[0][:]
		
		
		for i in range (0,len(my_tmp_bones)):
			fnd = False
			for j in range(0,len(his_tmp_bones)):
				if(my_tmp_bones[i].name == his_tmp_bones[j].name):
					fnd = True
			if(not fnd):
				my_tmp_bones[i].root = ""
				my_tmp_bones[i].coord_x = 0.0
				my_tmp_bones[i].coord_y = 0.0
				my_tmp_bones[i].coord_z = 0.0
				my_tmp_bones[i].rotation_x = 0.0
				my_tmp_bones[i].rotation_y = 0.0
				my_tmp_bones[i].rotation_z = 0.0
				
		self.time[0] = my_tmp_bones[:]
		
		
	def to_zero_skel2(self,):
		my_tmp_bones = self.time[0][:]		
		
		for i in range (0,len(my_tmp_bones)):
				my_tmp_bones[i].coord_x = 0.0
				my_tmp_bones[i].coord_y = 0.0
				my_tmp_bones[i].coord_z = 0.0
				my_tmp_bones[i].rotation_x = 0.0
				my_tmp_bones[i].rotation_y = 0.0
				my_tmp_bones[i].rotation_z = 0.0
				
		self.time[0] = my_tmp_bones[:]

	
	
	
	
class smd_bone(object):
	def __init__(self):
		self.id = -1
		self.name = ""
		self.root = ""
		self.coord_x = 0
		self.coord_y = 0
		self.coord_z = 0
		self.rotation_x = 0
		self.rotation_y = 0
		self.rotation_z = 0

		
	def __str__(self):
		tmpr = "---"
		if(len(self.root)>0): tmpr = self.root
			
		
		return str(self.id) + "\t" + self.name + "\t" + tmpr + "\t" + str(self.coord_x) + " " + str(self.coord_y) + " " + str(self.coord_z) + " " +  str(self.rotation_x) + " "  +  str(self.rotation_y) + " " +  str(self.rotation_z)
	

	
	
class smd_skeleton(object):
	def __init__(self):
		self.time = []
		
	def read_skeleton(self, fname):
		strs = []
		with open(fname, 'r') as f:
			strs = f.read().splitlines()
		
		#first step - read strings
		bones_1 = []
		sost = 0
		last_i = 0
		tmp_aray = []
		for i in range(0,len(strs)):
			last_i = i
			if((strs[i].strip()).startswith("nodes")):
				sost = 100
			elif(sost == 100):
				tmp1 = (strs[i].strip()).split()
				if(len(tmp1)>0):
					if(tmp1[0] != "end" ):
						if(len(tmp1) >= 3):
							#print(tmp1)
							tmp_aray.append( tmp1)
							bone = smd_bone()
							bone.id = int(tmp1[0])
							bone.name = tmp1[1]
							bones_1.append(bone)
							
					else:
						sost = 200
						break
		last_i = last_i+1
		print("last_i " + str(last_i))
		for i in range(0,len(bones_1)):
			if(int(tmp_aray[i][2]) >= 0):
				bones_1[i].root = bones_1[int(tmp_aray[i][2])].name
			#print((bones_1[i]))


		sost = 0
		for i in range(last_i,len(strs)):
					last_i = i
					tmp2 = (strs[i].strip()).split()
					
					if(sost == 0):
						if(len(tmp2) >= 2):
							if((tmp2[0] == "time") and (tmp2[1] == "0")):
								sost = 100
					elif(sost == 100):
						if(len(tmp2)>0):

							if(tmp2[0] != "end" ):

								if(len(tmp2) >= 7):
									#print(tmp1)
									id = int(tmp2[0])
									if((id >= 0) and (id < len(bones_1))):
										bones_1[id].coord_x = float(tmp2[1])
										bones_1[id].coord_y = float(tmp2[2])
										bones_1[id].coord_z = float(tmp2[3])
										bones_1[id].rotation_x = float(tmp2[4])
										bones_1[id].rotation_y = float(tmp2[5])
										bones_1[id].rotation_z = float(tmp2[6])
										#print(bones_1[id])
									
							else:
								sost = 200
								break

		last_i = last_i+1
		print("last_i " + str(last_i))								
		self.time = []
		self.time.append(bones_1[:])
		
	def anim_to(self,anim_skel,mi,hi):
		my_tmp_bones = self.time[mi][:]
		his_tmp_bones = anim_skel.time[hi][:]
		
		for i in range (0,len(my_tmp_bones)):
			for j in range(0,len(his_tmp_bones)):
				if(my_tmp_bones[i].name == his_tmp_bones[j].name):
					my_tmp_bones[i].coord_x = his_tmp_bones[j].coord_x
					my_tmp_bones[i].coord_y = his_tmp_bones[j].coord_y
					my_tmp_bones[i].coord_z = his_tmp_bones[j].coord_z
					my_tmp_bones[i].rotation_x = his_tmp_bones[j].rotation_x
					my_tmp_bones[i].rotation_y = his_tmp_bones[j].rotation_y
					my_tmp_bones[i].rotation_z = his_tmp_bones[j].rotation_z
		self.time[mi] = my_tmp_bones[:]
					
		
	def save_to(self,fname,with_end):
		file = open(fname, "w")
		file.write("version 1\n")
		file.write("nodes\n")
		for i in range(0, len(self.time[0])):
			file.write(str(self.time[0][i].id))
			file.write(" ")
			file.write(self.time[0][i].name)
			file.write(" ")
			write_root = -1
			for bn in self.time[0]:
				if(bn.name == self.time[0][i].root):
					write_root = bn.id
			file.write(str(write_root))

			file.write("\n")
			
		file.write("end\n")
		file.write("skeleton\n")
		file.write("time 0\n")	


		for i in range(0, len(self.time[0])):
			file.write(str(self.time[0][i].id))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].coord_x, 5))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].coord_y, 5))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].coord_z, 5))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].rotation_x, 5))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].rotation_y, 5))
			file.write(" ")
			file.write(float_to_str(self.time[0][i].rotation_z, 5))
			file.write("\n")		

		if(with_end): file.write("end\n")
		file.close()

		
	def to_zero_skel(self, anim_skel):
		my_tmp_bones = self.time[0][:]
		my_tmp_bones2 = []
		his_tmp_bones = anim_skel.time[0][:]
		
		
		for i in range (0,len(my_tmp_bones)):
			fnd = False
			for j in range(0,len(his_tmp_bones)):
				if(my_tmp_bones[i].name == his_tmp_bones[j].name):
					fnd = True
			if(not fnd):
				my_tmp_bones[i].root = ""
				my_tmp_bones[i].coord_x = 0.0
				my_tmp_bones[i].coord_y = 0.0
				my_tmp_bones[i].coord_z = 0.0
				my_tmp_bones[i].rotation_x = 0.0
				my_tmp_bones[i].rotation_y = 0.0
				my_tmp_bones[i].rotation_z = 0.0
				
		self.time[0] = my_tmp_bones[:]
		
		
	def to_zero_skel2(self,):
		my_tmp_bones = self.time[0][:]		
		
		for i in range (0,len(my_tmp_bones)):
				my_tmp_bones[i].coord_x = 0.0
				my_tmp_bones[i].coord_y = 0.0
				my_tmp_bones[i].coord_z = 0.0
				my_tmp_bones[i].rotation_x = 0.0
				my_tmp_bones[i].rotation_y = 0.0
				my_tmp_bones[i].rotation_z = 0.0
				
		self.time[0] = my_tmp_bones[:]


		

		

		

		
				
				
				
			
		
	
	






















	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
def secure_call(work_str):
	process = subprocess.Popen(work_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	#code = process.wait(1)
	
	ff = 0
	tm = 0
	timeout = 300
	step = 1
	#simple timeout
	while (tm >= 0):
	
		tm = tm + step
		print("pol: " + str(process.poll()))

		if (not (process.poll() is None)):
			if(process.poll() == 0): print_fork("SC: successful unpacked")
			else: print_fork("SC: error unpacked")
			tm = -1000
		if(tm > timeout):
			#tm = -1000
			#subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])
			#print_fork("SC: timeout, aborted ")
			pass
		if(tm > 20):
			val = 128

			val = subprocess.call("Taskkill /IM dw20.exe " )

			print("	val22 " + str(val))
			if(val == 0):
				process.kill()
				print_fork("SC: ERROR dw20.exe, aborted2 ")
				#time.sleep(5)

		time.sleep(step)
	#subprocess.call("Taskkill /IM dw20.exe " )
	#subprocess.call("Taskkill /IM ds.exe /f" )
	#subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])

	time.sleep(2)
	
	out, err = process.communicate()
	if(len(out) > 0): print_fork("SC: stdout: " + str(out))		
	if(len(err) > 0): print_fork("SC: stderr: " + str(err))
	
	
def secure_call2(work_str):
	process = subprocess.Popen(work_str, stdout=subprocess.PIPE)
	#code = process.wait()
#    return Popen(*popenargs, **kwargs).wait()

	 #   process = Popen(*popenargs, stdout=PIPE, **kwargs)

	ff = 0
	tm = 0
	timeout = 300
	step = 1
	#simple timeout
	while (tm >= 0):
	
		tm = tm + step
		print("pol: " + str(process.poll()))

		if (not (process.poll() is None)):
			if(process.poll() == 0): print_fork("SC: successful unpacked")
			else: print_fork("SC: error unpacked")
			tm = -1000
		if(tm > timeout):
			#tm = -1000
			#subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])
			#print_fork("SC: timeout, aborted ")
			pass
		if(tm > 20):
			val = 128

			val = subprocess.call("Taskkill /IM dw20.exe " )

			print("	val22 " + str(val))
			if(val == 0):
				process.kill()
				print_fork("SC: ERROR dw20.exe, aborted2 ")
				#time.sleep(5)

		time.sleep(step)
	#subprocess.call("Taskkill /IM dw20.exe " )
	#subprocess.call("Taskkill /IM ds.exe /f" )
	#subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])

	time.sleep(2)

	out, err = process.communicate()
	if(len(out) > 0): print_fork("SC: stdout: " + str(out))		
	if(len(err) > 0): print_fork("SC: stderr: " + str(err))
	


	
	

print_fork("create ini:")

os.chdir(tools_dir)

inipath = os.path.join(tools_dir,"horizon.ini")
print_fork("path to ini: " + inipath)
inifile = open(inipath,'w')
inifile.write(bin_dir + "\n")
inifile.flush()
inifile.close()
print_fork("complete!\n\n")






if (step_0_create_res_file):
	print_fork("\n\n\nStep 0: create res file:")
	os.chdir(tools_dir)
	work_str = '\"' + tool_path + '\"'
	print_fork(work_str)
	subprocess.call(work_str)
	print_fork("res file created")
	
	
if (step_1_unpack_bin):
	print_fork("\n\n\nStep 1: unpack bin's")
	if(not os.path.exists(os.path.join(tools_dir,"_trash"))): os.makedirs(os.path.join(tools_dir,"_trash"))
	os.chdir(os.path.join(tools_dir,"_trash"))
	
	work_str = '\"' + tool_path + '\" /p \"' + os.path.join(tools_dir,"res.txt") + '\"'
	print_fork(work_str)
	subprocess.call(work_str)
	print_fork("bin files unpacked")
	print_fork("result in " + tools_dir)

if (step_2_unpack_core):
	print_fork("\n\n\nStep 2: unpack core")
	for root, dirs, files in os.walk(work_dir):
		for name in files:	
			fullname = os.path.join(root, name)
			if(name.lower() == "matrices"):
				os.remove(fullname)	
				print_fork("remove " + fullname)
		for name in files:	
			if((not root.endswith("join_geo")) and (not root.endswith("skel_work")) and (not root.endswith("template_skel"))):
				fullname = os.path.join(root, name)
				if(fullname.lower().endswith(".core")):
					work_str = '\"' + tool_path + '\" \"' +   fullname + '\"'
					print_fork(work_str)
					os.chdir(root)
					secure_call(work_str)
			
			





			
if (step_3_generate_chars):
	print_fork("\n\n\nStep 3: generate chars ")
	for root, dirs, files in os.walk(work_dir):
		for name in files:	
			fullname = os.path.join(root, name)
			if(name.lower() == "matrices") and (fullname.find("skel_work") < 0):
				print_fork(root)
				skel_dir = os.path.join(os.path.dirname(root),"skeletons")
				if(os.path.isdir(skel_dir)):
					print_fork("	found skeleton dir: " +skel_dir)
					
					
					skelfiles = os.listdir(skel_dir) 
					
					for skfile in skelfiles:
						
						if((skfile.endswith(".core")) and (os.path.isfile(os.path.join(skel_dir,skfile)))):
							print_fork("		"+skfile)
							
							work_skel_dir = os.path.join(root,"skel_work")
							if(not (os.path.isdir(work_skel_dir))):
								os.makedirs(work_skel_dir)
							#else:
							#	shutil.rmtree(work_skel_dir)
							#	os.makedirs(work_skel_dir)
							if (not step3_without_conversion):
								if(os.path.exists(os.path.join(work_skel_dir,name))):
									os.remove(os.path.join(work_skel_dir,name))
									print_fork("			remove old matrices")
								shutil.copy(fullname, os.path.join(work_skel_dir,name))
								shutil.copy(os.path.join(skel_dir,skfile), os.path.join(work_skel_dir,skfile))
								
								
						

								work_str = '\"' + tool_path + '\" \"' +   os.path.join(work_skel_dir,skfile) + '\"'
								print_fork("			" +work_str)
								os.chdir(work_skel_dir)


								#try:
								#process = subprocess.Popen(work_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
								#code = process.wait(1)
								
								
								
								
								
								secure_call(work_str)

							
							
								if(os.path.exists(os.path.join(work_skel_dir,skfile))):
									os.remove(os.path.join(work_skel_dir,skfile))












							if(os.path.exists(os.path.join(work_skel_dir,skfile + ".ascii"))): 
								print_fork("					ASCII: ")
								skelsize = os.path.getsize(os.path.join(work_skel_dir,skfile + ".ascii"))
								if(skelsize>0):
									if(not os.path.exists(os.path.join(root,"join_geo"))):
										os.makedirs(os.path.join(root,"join_geo"))
									join_name = os.path.join(root,"join_geo","__join__" + skfile[:-5] + ".ascii~")
									print_fork("					" + join_name)
									if(os.path.exists(join_name)):
										os.remove(join_name)
									#jfile = open(join_name, "w")
									strs_skel = ""
									with open(os.path.join(work_skel_dir,skfile + ".ascii"), 'r') as ifile:
										strs_skel = ifile.read()#.splitlines()
									#jfile.write(strs_skel)
									meshfiles = os.listdir(root) 
									strs_geo = ""
									static_files_ascii_char = []
									for mfile in meshfiles:
										if(mfile.endswith(".ascii")): # and (not mfile.startswith("__j")):
											print_fork("					join: " + mfile)
											static_files_ascii_char.append(os.path.join(root,mfile))
											'''
											with open(os.path.join(root,mfile), 'r') as ifile:
												tmp_strs = ifile.read()#.splitlines()
												num = 0
												offset = 0
												for cdi in range(0, len(tmp_strs)):
													if(tmp_strs[cdi] == "\n"):
														num = num + 1 
													if(num == 1): 
														offset = cdi
														break
												print_fork("					offset:" + str (offset))
												if(num == 1):
													strs_geo = strs_geo + tmp_strs[offset+1:]
													
												if(create_join_parts):  # create _jpfile
													jp = open(os.path.join(root,"join_geo", "__jp__" + mfile[:-len(".ascii")] + "__" +  skfile[:-5] + ".ascii"), "w")
													jp.write(strs_skel)
													jp.write(tmp_strs)
													jp.close'''
											


									join_ascii(join_name, os.path.join(work_skel_dir,skfile + ".ascii"), static_files_ascii_char , [])
									#join_smd(os.path.join(root, "join_geo", "__2_joinRobot_skin_custom_skeleton.smd"), custom_skeleton, [] , skinned_files_smd)											
												
									num_mat = strs_geo.count("\nmaterial\n")
									print_fork("					num_mat " + str(num_mat))
									#jfile.write(str(num_mat) + "\n")
									#jfile.write(strs_geo)

									#jfile.close()
									try:
										if(os.path.exists(join_name[:-1])): os.remove(join_name[:-1])
										os.rename(join_name, join_name[:-1])
									except Exception:
										print_fork("					cannot rename tmp file")
								else:
									print_fork("					empty skeleton")










							if(os.path.exists(os.path.join(work_skel_dir,skfile + ".smd"))):
								print_fork("					SMD: ")
								skelsize = os.path.getsize(os.path.join(work_skel_dir,skfile + ".smd"))							
								if(skelsize>0):
									if(not os.path.exists(os.path.join(root,"join_geo"))):
										os.makedirs(os.path.join(root,"join_geo"))
									join_name = os.path.join(root,"join_geo","__join__" + skfile[:-5] + ".smd~")
									print_fork("					" + join_name)
									if(os.path.exists(join_name)):
										os.remove(join_name)
									#jfile = open(join_name, "w")
									strs_skel = ""
									with open(os.path.join(work_skel_dir,skfile + ".smd"), 'r') as ifile:
										strs_skel = ifile.read()#.splitlines()
									#jfile.write(strs_skel)
									meshfiles = os.listdir(root) 
									strs_geo = ""
									static_files_smd_char = []
									for mfile in meshfiles:
										if(mfile.endswith(".smd")): # and (not mfile.startswith("__j")):
											print_fork("					join: " + mfile)
											static_files_smd_char.append(os.path.join(root,mfile))
											'''with open(os.path.join(root,mfile), 'r') as ifile:
												strs_geo = ifile.read()#.splitlines()
											#jfile.write(strs_geo)
											
											if(create_join_parts):
												jp = open(os.path.join(root,"join_geo", "__jp__" + mfile[:-len(".smd")] + "__" +  skfile[:-5] + ".smd"), "w")
												jp.write(strs_skel)
												jp.write(strs_geo)
												jp.close'''

									#jfile.close()
									join_smd(join_name, os.path.join(work_skel_dir,skfile + ".smd"), static_files_smd_char , [])

									try:
										if(os.path.exists(join_name[:-1])): os.remove(join_name[:-1])
										os.rename(join_name, join_name[:-1])
									except Exception:
										print_fork("					cannot rename tmp file")

								else:
									print_fork("					empty skeleton")

					
					
				else:
					print_fork("	unfound skeleton dir: " +skel_dir)

	
	
if (step4_convert_robots):

	print_fork("\n\n\nStep 4: Convert robots chars ")
	for root, dirs, files in os.walk(work_dir):
		for name in files:	
			fullname = os.path.join(root, name)
			if(name.lower() == "matrices") and (fullname.find("skel_work") < 0) and (root.endswith("parts") ):
				print_fork("")
				print_fork("	root_folder: "	+	root)	
				strs1 = []
				strs2 = []
				strs3 = []
				
				if(not	step4_without_conversion):
					next_step = True
					template_skel_dir = os.path.join(root,"template_skel")
					print_fork("		clear template_skel_dir folder: " + template_skel_dir)
					if(not (os.path.isdir(template_skel_dir))):
						os.makedirs(template_skel_dir)
					else:
						r_files = os.listdir(template_skel_dir) 
						for rfl in r_files:
							if(os.path.isfile(os.path.join(template_skel_dir,rfl))):
								os.remove(os.path.join(template_skel_dir,rfl))
					
					template_file = ""
					robot_template_dir_cur = robot_template_dir
					
					
					if(root.find('\\cryobear\\') > 0):
						template_file = "cryobeartemplate.core"
						robot_template_dir_cur = robot_template_dlc_dir
						print_fork("		this is cryobear, template_file " + template_file)	
					if(root.find('\\hellhound\\') > 0):
						template_file = "hellhoundtemplate.core"
						robot_template_dir_cur = robot_template_dlc_dir
						print_fork("		this is hellhound, template_file " + template_file)		
					if(root.find('\\infernobear\\') > 0):
						template_file = "infernobeartemplate.core"
						robot_template_dir_cur = robot_template_dlc_dir
						print_fork("		this is infernobear, template_file " + template_file)
					if(root.find('\\snowmole\\') > 0):
						#template_file = "moletemplate.core"

						template_file = "mole_cc_template.core"
						robot_template_dir_cur = robot_template_dlc_dir
						print_fork("		this is snowmole, template_file " + template_file)						


					if(root.find('\\antelope\\') > 0):
						template_file = "horsetemplate.core"
						print_fork("		this is antelope, template_file " + template_file)	
					if(root.find('\\goat\\') > 0):
						template_file = "horsetemplate.core"
						print_fork("		this is goat, template_file " + template_file)		
					if(root.find('\\longhorn\\') > 0):
						template_file = "horsetemplate.core"
						print_fork("		this is longhorn, template_file " + template_file)							
					
					if(root.find('\\longlegbird\\') > 0):
						template_file = "longlegbirdtemplate.core"
						print_fork("		this is longlegbird, template_file " + template_file)
					if(root.find('\\mole\\') > 0):
						template_file = "moletemplate.core"
						print_fork("		this is mole, template_file " + template_file)
					if(root.find('\\stalker\\') > 0):
						template_file = "stalkertemplate.core"
						print_fork("		this is stalker, template_file " + template_file)
					if(root.find('\\scout\\') > 0):
						template_file = "scouttemplate.core"
						print_fork("		this is scout, template_file " + template_file)
					if(root.find('\\laserscout\\') > 0):
						template_file = "scouttemplate.core"
						print_fork("		this is laserscout, template_file " + template_file)					
					if(root.find('\\glider\\') > 0):
						template_file = "glidertemplate.core"
						print_fork("		this is glider, template_file " + template_file)						
					if(root.find('\\greywolf\\') > 0):
						template_file = "greywolftemplate.core"
						print_fork("		this is greywolf, template_file " + template_file)
					if(root.find('\\direwolf\\') > 0):
						template_file = "greywolftemplate.core"
						print_fork("		this is direwolf, template_file " + template_file)
					if(root.find('\\giraffe\\') > 0):
						template_file = "comgiraffetemplate.core"
						print_fork("		this is giraffe, template_file " + template_file)
					if(root.find('\\cargorhino\\') > 0):
						template_file = "cargorhinotemplate.core"
						print_fork("		this is cargorhino, template_file " + template_file)
					if(root.find('\\bison\\') > 0):
						template_file = "bisontemplate.core"
						print_fork("		this is bison, template_file " + template_file)
					if(root.find('\\beachlizard\\') > 0):
						template_file = "beachlizardtemplate.core"
						print_fork("		this is beachlizard, template_file " + template_file)
					if(root.find('\\crab\\') > 0):
						template_file = "crabtemplate.core"
						print_fork("		this is crab, template_file " + template_file)
					if(root.find('\\hackbot\\') > 0):
						template_file = "hackbottemplate.core"
						print_fork("		this is hackbot, template_file " + template_file)
					if(root.find('\\harvester\\') > 0):
						template_file = "harvestertemplate.core"
						print_fork("		this is harvester, template_file " + template_file)						
					if(root.find('\\horse\\') > 0):
						template_file = "horsetemplate.core"
						print_fork("		this is horse, template_file " + template_file)						
					if(root.find('\\hyena\\') > 0):
						template_file = "hyenatemplate.core"
						print_fork("		this is hyena, template_file " + template_file)						
					if(root.find('\\raptor\\') > 0):
						template_file = "raptortemplate.core"
						print_fork("		this is raptor, template_file " + template_file)	
					if(root.find('\\spraybot\\') > 0):
						template_file = "spraybottemplate.core"
						print_fork("		this is spraybot, template_file " + template_file)						
					if(root.find( '\\thunderhawk\\' ) > 0):
						template_file = "thunderhawktemplate.core"
						print_fork("		this is thunderhawk, template_file " + template_file)	
					if(root.find( '\\warrobot\\' ) > 0):
						template_file = "warrobottemplate.core"
						print_fork("		this is warrobot, template_file " + template_file)
					if(root.find( '\\warrobot_modules\\' ) > 0):
						template_file = "warrobottemplate.core"
						print_fork("		this is warrobot_modules, template_file " + template_file)
					if(root.find( '\\warrobot_pristine\\' ) > 0):
						template_file = "warrobottemplate.core"
						print_fork("		this is warrobot_pristine, template_file " + template_file)
						
					print_fork("		copy template_file " +  (os.path.join(robot_template_dir_cur, template_file)) + "   to   "  + os.path.join (template_skel_dir,template_file))
					if(os.path.exists(os.path.join(robot_template_dir_cur, template_file))):
						shutil.copy( (os.path.join(robot_template_dir_cur, template_file))   , os.path.join (template_skel_dir,template_file))
					else:
						print_fork("		Error robot conversion, unfound template file " + template_file)
						next_step = False
						
					



					print_fork("		copy matrices file " +  (os.path.join(root, "matrices")) + "   to   "  +   os.path.join (template_skel_dir,"matrices") )

					if(os.path.exists(os.path.join (template_skel_dir,"matrices"))): os.remove(os.path.join (template_skel_dir,"matrices"))
					shutil.copy( (os.path.join(root, "matrices"))   , os.path.join (template_skel_dir,"matrices"))

						





					
						
					if(next_step):
						os.chdir(template_skel_dir)

						print_fork("		files in template_skel_dir: " + str(os.listdir(template_skel_dir) ))

						print_fork("		create animskel to  template_skel_dir: " + template_skel_dir)

						work_str = '\"' + tool_path + '\" \"' +   os.path.join(template_skel_dir,template_file) + '\"'
						print_fork("		" + 	work_str)
						secure_call(work_str)
						
					anims_skel = ""
					bonyskel = ""
					modelhelpers = ""
					

					if(next_step):
						r_files = os.listdir(template_skel_dir) 
						print_fork("		remove all .ascii and .smd file from  template_skel_dir: " + template_skel_dir)

						for rfl in r_files:
							if(rfl.endswith(".animskel")): anims_skel = rfl
							if(rfl.endswith(".ascii")): os.remove(os.path.join(template_skel_dir,rfl))
							if(rfl.endswith(".smd")): os.remove(os.path.join(template_skel_dir,rfl))
							
						print_fork("		copy bonyskel from skeletons to template_skel_dir:")

						skel_dir = os.path.join(os.path.dirname(root),"skeletons")
						if(os.path.exists(os.path.join(skel_dir,"mesh_skeleton_rootbone.core"))):
							bonyskel = "mesh_skeleton_rootbone.core"
							shutil.copy( (os.path.join(skel_dir, bonyskel))   , os.path.join (template_skel_dir,bonyskel))
							print_fork("		copy " + (os.path.join(skel_dir, bonyskel)) +"   to  " + os.path.join (template_skel_dir,bonyskel) )
						elif(os.path.exists(os.path.join(skel_dir,"skeleton_rootbone.core"))):						
							bonyskel = "skeleton_rootbone.core"
							shutil.copy( (os.path.join(skel_dir, bonyskel))   , os.path.join (template_skel_dir,bonyskel))
							print_fork("		copy " + (os.path.join(skel_dir, bonyskel)) +"   to  " + os.path.join (template_skel_dir,bonyskel) )

						print_fork("		copy robot_modelhelpers.core to template_skel_dir:")

						if(os.path.exists(os.path.join(os.path.dirname(root),"robot_modelhelpers.core"))):						
							modelhelpers = "robot_modelhelpers.core"
							shutil.copy( (os.path.join(os.path.dirname(root), modelhelpers))   , os.path.join (template_skel_dir,modelhelpers))
							print_fork("		copy " + (os.path.join(os.path.dirname(root), modelhelpers)) +"   to  " + os.path.join (template_skel_dir,modelhelpers) )

						else: 
							print_fork("		WARNING robot conversion, unfound robot_modelhelpers file " )

							
						if(os.path.exists(os.path.join(template_skel_dir, bonyskel))):
							pass
						else:
							print_fork("		Error robot conversion, unfound mesh_skeleton_rootbone file: " + bonyskel)
							next_step = False
							
						if(os.path.exists(os.path.join(template_skel_dir, anims_skel))):
							pass
						else:
							print_fork("		Error robot conversion, unfound anims_skel file: " + anims_skel)
							next_step = False			

							
							
							
							
					if(next_step):
						''' "E:\horizon\Horizon.exe"  "E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\mesh_skeleton_rootbone.core" "E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\raptortemplate.core_0.animskel"'''
						'''  E:\horizon\Horizon___.exe E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\mesh_skeleton_rootbone.core   E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\raptortemplate.core_0.animskel '''
						os.chdir(template_skel_dir)


						
						
						
						
						#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
						#may be i need copy matrices to template_skel_dir???
						print_fork("		copy matrices file again (update) - " +  (os.path.join(root, "matrices")) + "   to   "  +   os.path.join (template_skel_dir,"matrices") )

						if(os.path.exists(os.path.join (template_skel_dir,"matrices"))): os.remove(os.path.join (template_skel_dir,"matrices"))
						shutil.copy( (os.path.join(root, "matrices"))   , os.path.join (template_skel_dir,"matrices"))

						print_fork("		files in template_skel_dir: " + str(os.listdir(template_skel_dir) ))

						
						work_str = '\"' + tool_path + '\" \"' +   os.path.join(template_skel_dir,bonyskel)  + '\" \"' + os.path.join(template_skel_dir,anims_skel) + '\" >> \"' + os.path.join(template_skel_dir,"robot.bat") + '\"'
						if (anims_skel != "" ): work_str = '\"' + tool_path + '\" \"' +   os.path.join(template_skel_dir,bonyskel)  + '\" \"' + os.path.join(template_skel_dir,anims_skel) +  '\"'
						else: work_str = '\"' + tool_path + '\" \"' +   os.path.join(template_skel_dir,bonyskel)  + '\"'
						#work_str = 'E:\horizon\Horizon___.exe E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\mesh_skeleton_rootbone.core   E:\hz\Image0\packed_pink\models\characters\robots\raptor\animation\parts\template_skel\raptortemplate.core_0.animskel'
						print_fork("		" + 	work_str)						
						
						oval = str(subprocess.check_output(work_str ))
						if len(oval) > 0:
							if(oval.startswith("b'")):
								oval = oval[2:-1]
							strs1 = oval.split("\\r\\n")
							print_fork("		create original bat file to template_skel_dir:")

							with open(os.path.join(template_skel_dir,"original_robot.bat"), "w") as file:
								for  line in strs1:
									file.write(line + '\n')
									print_fork("			" + line)
									#print_fork(line)
									if(line.startswith("Horizon ")): 
										line2 = line[len("Horizon "): ].lower()
										line2 = line2.replace("_helper", ".core")
										line3 = line2[: line2.find( " " ) ] + '\"' + line2[line2.find(" " ): ]
										line4 = '\"' + tool_path + '\" \"' + root + '\\' + line3
										print_fork(line)
										print_fork(line2)
										print_fork(line3)
										print_fork(line4)
										
										offset711 = line4.rfind("\"") + 1
										
										line_header = line4[:offset711]
										line_tail = line4[offset711:]
										split_strs = line_tail.split()
										line5 = line_header + " " + split_strs[0] + " 0 0 0"
										print_fork(line5)

										
										print_fork("")
										strs3.append(line5)
										strs2.append(line4)
							print_fork("		create actual bat file to template_skel_dir:")
							with open(os.path.join(template_skel_dir,"actual_robot.bat"), "w") as file:
								for  line in strs2:
									file.write(line + '\n')
									print_fork("			" + line)
							with open(os.path.join(template_skel_dir,"actual_zero_robot.bat"), "w") as file:
								for  line in strs3:
									file.write(line + '\n')
									print_fork("			" + line)
									
							#if(os.path.exists(os.path.join(template_skel_dir, "matrices"))): os.remove(os.path.join(template_skel_dir,"matrices"))

					if(next_step):
						print_fork("		execute commands from actual bat:")
						inrementer = 0
						for  line in strs3:
							print_fork("			" +str(inrementer) + " // " + str(len(strs3)) + "	" + line)
							secure_call(line)
							inrementer = inrementer + 1

						print_fork ("		create_final_ascii")
						#secure_call2(work_str)











							
				print_fork ("		create_join_files")
				print_fork ("		sort files:")
				template_skel_dir = os.path.join(root,"template_skel")		
				skel_files = os.listdir(template_skel_dir) 
				skel_file = ""
				skel_file1 = ""
				work_skel_file1 = ""

				static_files = []
				list_static_files = []
				skinned_files = []
				for skl in skel_files:
					#print(skl)
					if(skl.endswith(".ascii")): 
						skel_file = os.path.join(template_skel_dir,skl)
						skel_file1 = skl
					
				print_fork(		"		skeleton: " + skel_file)
				
				print_fork ("		create custom skeletons")
				skel_work_file = ""
				
				if(os.path.exists(os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"))):
					skel_work_file = (os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"))
					print_fork("		create custom skeleton with: " + skel_work_file)
					#join_ascii(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file1), os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"), [] , skinned_files)
				elif(os.path.exists(os.path.join(root,"skel_work","skeleton_rootbone.core.smd"))):
					skel_work_file = os.path.join(root,"skel_work","skeleton_rootbone.core.smd")
					print_fork("		jcreate custom skeleton with: " + skel_work_file)
					#join_ascii(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file1), os.path.join(root,"skel_work","skeleton_rootbone.core.ascii"), [] , skinned_files)
				else:
					print_fork("		ERROR: unfound skeleton for custom skeleton")
					
					
				
				skl_tmpl = smd_skeleton()
				skl_tmpl.read_skeleton(skel_file[:-5]+"smd")
				skl_tmpl.save_to(os.path.join(root, "join_geo", "__3_joinRobot_fix_skeleton.smd"),True)
				skl_anim = smd_skeleton()
				skl_anim.read_skeleton(skel_work_file)
				skl_tmpl.anim_to(skl_anim, 0,0)
				custom_skeleton = (os.path.join(root,"template_skel","custom_skeleton.smd"))
				skl_tmpl.save_to(custom_skeleton,False)
				skl_tmpl.to_zero_skel2()
				zero_skeleton = (os.path.join(root,"template_skel","zero_skeleton.smd"))
				skl_tmpl.save_to(zero_skeleton,False)

				
				ascii_skl_tmpl = ascii_skeleton()
				ascii_skl_tmpl.read_skeleton(skel_file[:-5]+"ascii")				
				ascii_skl_tmpl.save_to(os.path.join(root, "join_geo", "__3_joinRobot_fix_skeleton.ascii"),True)
						

						
				ascii_skl_tmpl.to_zero_skel2()
				ascii_zero_skeleton = (os.path.join(root,"template_skel","zero_skeleton.ascii"))
				#print_fork("###" + ascii_zero_skeleton)
				ascii_skl_tmpl.save_to(ascii_zero_skeleton,False)
				
				
				
				ascii_skl_anim = ascii_skeleton()
				ascii_skl_anim.read_skeleton(skel_work_file[:-3]+"ascii")
				ascii_skl_tmpl.anim_to(ascii_skl_anim, 0,0)
				ascii_custom_skeleton = (os.path.join(root,"template_skel","custom_skeleton.ascii"))
				ascii_skl_tmpl.save_to(ascii_custom_skeleton,False)

					
					
					
					
				
				
				
				
				static_obj = []
				with open(os.path.join(template_skel_dir,"actual_robot.bat"), 'r') as f:
					static_obj = f.read().splitlines()
				print_fork("		static_files:")
				for sto in static_obj:
					fpath1 = ""
					sto = sto.split('\"')
					if(len(sto) > 3): 
						fpath1 = sto[3] + "_0.ascii"
						print(fpath1)
					else: fpath1 = ""
					list_static_files.append(fpath1)
					if os.path.exists(fpath1):
						static_files.append(fpath1)
						print_fork( "			" + fpath1)
				root_files = os.listdir(root) 
				print_fork("		skinned_files:")

				for dno in root_files :
					if(dno.endswith("ascii")):
						
						fnd = 0
						for sto in list_static_files:
							if(sto.lower().endswith(dno.lower())): fnd = fnd +1
						if(fnd == 0): 
							dno = os.path.join(root,dno)
							print_fork("			" + dno)
							skinned_files.append(dno)
							
				#join_ascii(os.path.join(root, "join_geo", "__joinRobot_" + skel_file1), skel_file, static_files , skinned_files)
				join_ascii(os.path.join(root, "join_geo", "__1_joinRobot_static_zero_skeleton.ascii"), ascii_zero_skeleton, static_files , [])
				join_ascii(os.path.join(root, "join_geo", "__2_joinRobot_skin_custom_skeleton.ascii"), ascii_custom_skeleton, [] , skinned_files)
				
				
				
				#if(robot_separate_convert):
				
				#print_fork("		joined static mesh with skeleton: " + skel_file)
				#
				#join_ascii(os.path.join(root, "join_geo", "__joinRobot_static_" + skel_file1), skel_file, static_files , [])
				#
				#if(os.path.exists(os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.ascii"))):
				#	print_fork("		joined skined mesh with skeleton: " + os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.ascii"))
				#	join_ascii(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file1), os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.ascii"), [] , skinned_files)
				#elif(os.path.exists(os.path.join(root,"skel_work","skeleton_rootbone.core.ascii"))):
				#	print_fork("		joined skined mesh with skeleton: " + os.path.join(root,"skel_work","skeleton_rootbone.core.ascii"))
				#	join_ascii(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file1), os.path.join(root,"skel_work","skeleton_rootbone.core.ascii"), [] , skinned_files)
				#else:
				#	print_fork("		ERROR: unfound skeleton for skined mesh")
					
					
					
				skel_file_smd = skel_file[:-len("ascii")] + "smd"
				skel_file_smd1 = skel_file1[:-len("ascii")] + "smd"
				static_files_smd = []
				for fl2 in static_files:
					static_files_smd.append(fl2[:-len("ascii")] + "smd")
				skinned_files_smd = []
				for fl2 in skinned_files:
					skinned_files_smd.append(fl2[:-len("ascii")] + "smd")
				
				join_smd(os.path.join(root, "join_geo", "__1_joinRobot_static_zero_skeleton.smd"), zero_skeleton, static_files_smd , [])
				join_smd(os.path.join(root, "join_geo", "__2_joinRobot_skin_custom_skeleton.smd"), custom_skeleton, [] , skinned_files_smd)

				#if(os.path.exists(os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"))):
				#	print_fork("		joined skined mesh with skeleton: " + os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"))
				#	join_smd(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file_smd1), os.path.join(root,"skel_work","mesh_skeleton_rootbone.core.smd"), [] , skinned_files_smd)
				#elif(os.path.exists(os.path.join(root,"skel_work","skeleton_rootbone.core.smd"))):
				#	print_fork("		joined skined mesh with skeleton: " + os.path.join(root,"skel_work","skeleton_rootbone.core.smd"))
				#	join_smd(os.path.join(root, "join_geo", "__joinRobot_skin_" + skel_file_smd1), os.path.join(root,"skel_work","skeleton_rootbone.core.smd"), [] , skinned_files_smd)
				#else:
				#	print_fork("		ERROR: unfound skeleton for skined mesh")
 
				
				
				
					
						

				
#fast_ascii_test("E:\\hz\\Image0\\packed_pink\\models\\characters\\robots\\raptor\\animation\\parts\\part_65_des.core_0.ascii_")	
print_fork("\n\n\nScript comlete")
logfile.close()	