# This file converts pixel based SWC into micron based SWC file. 
#
# python scaleSWC.py swcFilename xyDist zDist
# 
# Here xyDist is the pixel distance in micron in one plane, and zDist the distance between planes in micron. 
#

from numpy import *
import os, os.path, glob, re, fnmatch, sys

def scaleSWC(swcFilename, xyDist, zDist):
	print 'Scaling SWC points in ',swcFilename,' with xyDist=',xyDist, ' zDist=',zDist
	f = open(swcFilename)
	lines = f.readlines()
	f.close()
	Points = [];
	for line in lines:
		ll = line.split(' ')
		if ll[0] == '#':
			continue
		nn = int(float(ll[0]))	# label of the point
		tp = int(float(ll[1]))  # point type
		py = float(ll[2])	# note the inversion of x, y.
		px = float(ll[3])	
		z  = float(ll[4])	# z
		r = float(ll[5])	# radius of the sphere. 
		np = int(float(ll[6]))	# parent point id. 			
		# get the length in micron
		py *= xyDist; px *= xyDist; r = r*xyDist; z *= zDist
		Points.append([nn,tp,py,px,z,r,np])
	
	filenameOut = swcFilename[:-3]+'scaled.swc'	
	print 'Saving scaled SWC to file ',filenameOut
	
	f = open(filenameOut,'w')
	for [nn,tp,py,px,z,r,np] in Points:
		ll = str(int(nn))+' '+str(int(tp))+' '+str(py)+' '+str(px)+' '+str(z)+' '+str(r)+' '+str(int(np))+'\n'
		f.write(ll)
	f.close()

if len(sys.argv) > 3:
	swcFilename = sys.argv[1]
	xyDist = float(sys.argv[2])
	zDist = float(sys.argv[3])
else:
	print 'Error: please supply swcFilename.'
	exit()
scaleSWC(swcFilename, xyDist, zDist)
