#!/usr/bin/env python

import os
import sys
# if you pip installed this is wrong but you have silent_tools installed anyways
silent_tools_dir = os.path.dirname(os.path.realpath(__file__))
if silent_tools_dir not in sys.path:
    sys.path.append(silent_tools_dir)

import silent_tools
from silent_tools import eprint
import math

# Don't throw an error when someone uses head
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL) 

if (len(sys.argv) != 3):
    eprint("")
    eprint("silentsplitdd by bcov - a tool to split a silentfile into equal size parts without copying")
    eprint("Usage:")
    eprint("        silentsplit myfile.silent TAGS_PER_SILENT_FILE > dd_files.list")
    eprint("")
    eprint("Each of the lines in the output may be regarded as a silent file.")
    sys.exit(1)

silent_file = sys.argv[1]

if ( not os.path.exists(silent_file) ):
    eprint("silentsplitshuf: File not found " + silent_file)
    assert(False)

tags_per = sys.argv[2]
try:
    tags_per = int(tags_per)
    assert(tags_per > 0)
except:
    eprint("silentsplitshuf: Second argument must be a number greater than 0")
    assert(False)


silent_index = silent_tools.get_silent_index( silent_file )
tags = silent_index['tags']

full_silent = os.path.abspath(silent_file)

total_structures = len(tags)
cur_i = 0
ifile = 0

while cur_i < total_structures:

    ub = min( total_structures, cur_i + tags_per )

    low_seek = silent_index['index'][tags[cur_i]]['seek']
    count = -1
    if ( ub < total_structures ):
        high_seek = silent_index['index'][tags[ub]]['seek']
        count = high_seek - low_seek

    print("<( silentdd %s %i %i )"%(full_silent, low_seek, count))

    ifile += 1
    cur_i += tags_per







