'''
Created Dec, 2014

@author: henryre
'''

import argparse
from random import randrange
from os.path import join

def run(path, out, N, M):
    
    # Get input file
    with open(path, 'rb') as i:
        content = i.readlines()
    # Separate cascade file blocks
    hblock = ''
    block = 0
    for l in content:
        block += 1
        # Break if blocks separate
        if l in ['\n', '\r\n']:
            break
        # Add line to first block
        hblock += l
    
    # Get second block
    cascades = content[block:len(content)]
    
    # For every bootstrap
    for m in xrange(M):
        filename = 'netboot-' + str(m) + '.txt'
        opath = join(out, filename)
        with open(opath, 'w+') as o:
            # Write first block
            o.write(hblock)
            o.write('\n')
            # Sample lines (cascades) in second block and write them
            samp = [randrange(len(cascades)) for _ in xrange(N)]
            for j in samp:
                o.write(cascades[j])
        

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Bootstrap cascades for NETINF')
    parser.add_argument('input', type=str, help='Path to observed/resampled cascade data file.')
    parser.add_argument('output', type=str, help='Path to output directory.')
    parser.add_argument('n', type=int, help='Number of observations per bootstrap.')
    parser.add_argument('m', type=int, help='Number of bootstrap samples.')
    
    args = parser.parse_args()
    
    run(args.input, args.output, args.n, args.m)
