# splits a file down into manageable chunks

DEFAULT_MAX_LINES = 100000

case ARGV.size
when 1
  in_file = ARGV[0]
  max_lines = DEFAULT_MAX_LINES
when 2
  in_file = ARGV[0]
  max_lines = ARGV[1].to_i
else
  puts "Usage: #{File.basename(__FILE__)} FILE [MAX_LINES]"
  exit
end

extension = File.extname(in_file)
base = in_file.sub(extension, '')

File.open(in_file, 'r') do |input|
  line_num = 0
  file_num = 1
  
  begin
    output = File.open("#{base}_#{sprintf('%03d', file_num)}#{extension}", 'w')

    while (line = input.gets)

      output.puts line

      line_num += 1
      if line_num == max_lines
        line_num = 0
        file_num += 1
        output.close
        output = File.open("#{base}_#{sprintf('%03d', file_num)}#{extension}", 'w')
      end
    end

  rescue Exception
    output.close
  end
end