#!/usr/bin/env python
# v0.1 6 October, 2008
from random import *
import sys,re
usage= """
 usage example: splitfile.py data.dat 3 1 1
 That will make data.dat.1 with 3/5 of the data,
 data.dat.2 with 1/5 of the data, and data.dat.3 with 1/5.
 The first argument is the file to split, following is
 arbitrary amount of numbers, separated by spaces.
 The order of the data records is shuffled (randomized).
"""
try:
	infile=sys.argv[1]
	inf=open(infile,'r')
except:
	print "failed to open ",infile
	print usage
try:
	nfile=[ int(x) for x in sys.argv[2:]]
	print nfile
except:
	print usage

sum=sum(nfile)
head=[]
all=[]

while 1:
	aline=inf.readline().strip()
	if not aline: break
	if re.match('\#',aline):
		head.append(aline)
		continue
	all.append(aline)

shuffle(all)  #randomize the order of the data records

nrec=len(all);

ia=0
na=0
for i in range(len(nfile)):
	outfile=infile+'.'+str(i+1)
	print outfile
	ouf=open(outfile,'w')
	for line in head:
		print >>ouf,line
	na=na+nfile[i]
	ib=na*nrec/sum
	for line in all[ia:ib]:
		print >>ouf,line
	ia=ib
