#!/usr/bin/env python

# TF - 11/10/01
# script to extract and convert CNS file to 
# something easily used for F2MTZ input
# (and it gets rid of exponential terms)

import sys, string

def isDigits(s):
	match=string.digits + '-'
	for letter in s:
		if letter not in match:
			return None
	return 1

def isNum(s):
	try: float(s)
	except ValueError:
		return None
	return 1

def isFile(f):
	try: open(f)
	except IOError:
		return None
	return 1

nargs = len(sys.argv)
if (nargs != 4):
	print """
	Usage: fixit.py [# lines to ignore] [# lines to concatenate] [filename]
	e.g. fixit.py 19 4 filename.cns
	will skip first 19 lines and merge 4 lines per reflection from filename.cns
	"""
	sys.exit()

strip = sys.argv[1]
tocat = sys.argv[2]
ifp = sys.argv[3]

# the regular checks
if not isNum(strip):
	print strip + ' is not an int - exiting'
	sys.exit()

if not isNum(tocat):
	print tocat + ' is not an int - exiting'
	sys.exit()

if not isFile(ifp):
	print ifp + ' is not a file - exiting'
	sys.exit()

f=open(ifp, 'r')

# skip the junk
for i in range(int(strip)):
	f.readline()

num=0
for curline in f.readlines():
	num=num+1
#	print curline
        # for all lines
	for i in string.split(curline):
		# if its a number
		if isNum(i):
			# check if its an integer or a float
			if isDigits(i):
				print '%10d' % int(i),
			else:
				print '%10.3f' % float(i),
	# done with the reflection? print newline if so
	if ((num % int(tocat)) == 0):
		print
		num=0

f.close()

