#!/usr/bin/python

# Program to convert polar coordinates to rectangular coordinates
# made for Difmap model files.

import math, sys, string

if len(sys.argv)==1:
    print "\npolar2rect.py written by Enno Middelberg 2002"
    print "\nProgram to convert polar coordinates to rectangular coordinates"
    print "and to calculate T_b from Difmap model files."
    print "It prints out a table of distances among all model comps."
    print "\nCall the program with 'polar2rect.py filename.mod'\n"
    sys.exit()

y=open(sys.argv[1]).readlines()
xlist=[]
ylist=[]
i=0

for line in y:
    newline=string.replace(line, "v", " ")
    numbers=string.split(newline)
    try:
	# getting flx in Jy
	flx=string.atof(numbers[0])
	r=string.atof(numbers[1])
	# getting major and minor axes from modelfile, convert them to arcsec
	bmaj=0.001*string.atof(numbers[3])
	bmin=bmaj*string.atof(numbers[4])
	#calculating the frequency in cm
	l=100*2.99792458E8/string.atof(numbers[7])
	# calculating the brightness temperature
	# T_B = 1359.4*(lambda[cm])^2 * S[Jy] / (bmin[arcsec] * bmaj [arcsec])
	Tb=1359.4*(l**2)*flx/(bmin*bmaj)
	phi=math.pi*string.atof(numbers[2])/180
	x=r*math.cos(phi)
	y=r*math.sin(phi)
	print line,
	print "Nr. "+string.ljust(`i`,3)+": x=%5.2f mas, y=%5.2f mas, flux=%7.4f Jy, FWHM=%5.2f mas, T_b=%3.2e K\n" % (x,y,flx,(1000*0.5*(bmaj+bmin)),Tb)
	xlist.append(x)
	ylist.append(y)
	i=i+1
    except (ValueError, IndexError):
	print line,

print "\n\nDistances among all "+`i`+" model components:\n\n"

s=0
columns="        "
line="----"

while s<i:
    columns=columns+string.ljust(`s`,9)
    line=line+"---------"
    s=s+1

print columns
print line

s=0
t=0

while s<i:
    print string.ljust(`s`,3),
    while t<i:
        dist=math.sqrt((xlist[s]-xlist[t])**2+(ylist[s]-ylist[t])**2)
	print "%8.3f" % dist,
	t=t+1
    print
    t=0
    s=s+1

