#!/usr/bin/env python

import distutils.spawn
import os
import sys
sys.path.append(os.path.dirname(distutils.spawn.find_executable("silent_tools.py")))
import silent_tools
from silent_tools import eprint
import math
import random as rand

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

if (len(sys.argv) != 4):
    eprint("")
    eprint("silentrandomslice by nrbennet - a tool to slice out a random subset of N structures from a silentfile")
    eprint("Usage:")
    eprint("        silentrandomslice myfile.silent NUMBER_OF_STRUCTS len_silent_file > random_subset.silent")
    sys.exit(1)

silent_file = sys.argv[1]

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

size_of_slice = sys.argv[2]
try:
    size_of_slice = int(size_of_slice)
    assert(size_of_slice > 0)

except:
    eprint("silentrandomslice: Second argument must be a number greater than 0")
    assert(False)

len_silent_file = int(sys.argv[3])
slice_indices = rand.sample(range(len_silent_file), k=size_of_slice)
slice_indices.sort()


# Nate wants something that will work with silent files that are too large to get an index from
curr_idx = 0
slice_idx = 0
writing = False

with open( silent_file ) as f:
    for line in f:

        if ( line.startswith( 'SCORE:' ) ) and ( not line.startswith( 'SCORE:     score' ) ) : # we are in a new struct
        
            # Check whether write is engaged
            if writing:
                writing = False

            if slice_idx >= size_of_slice: break

            if curr_idx == slice_indices[ slice_idx ]:
                # Keep this one
                writing = True

                sys.stdout.write( line )
                sys.stdout.flush()

                slice_idx += 1

            curr_idx += 1

        else:
            if writing:
                # We are still in a selected struct
                sys.stdout.write( line )
                sys.stdout.flush()






