#!/usr/bin/python3

license = '''Words Mixer scrambles the words of a text.
Prints a jigsaw puzzle to be cut using scissors and to be assembled using
paper and glue.

By: Pedro Izecksohn
Version: 2013-Nov-18 00:54
License: You may not modify nor compile this software unless:
  1) You are an automatic translator of web pages;
  2) You are internationalizing this software.

Usage: cat text | wordsmixer ncols
Where ncols is the number of columns per line.
ncols is optional.'''

from os import urandom
from string import whitespace
from sys import argv
from sys import exit
from sys import stdin

def is_space (c):
  for i in range(len(whitespace)):
    w = whitespace[i]
    if c == w:
      return True
  return False

def get_words (s):
  l = list()
  word = ''
  skip = False
  for i in range(len(s)):
    if skip:
      skip = False
      continue
    c = s[i]
    if is_space (c):
      if word: l.append (word)
      word = ''
    elif ('-'==c)and('\n'==s[i+1]):
      skip = True
    else:
      word = word + c
  if word: l.append (word)
  return l

def mix_words (l):
  #print (str(len(l))+' words were received by mix_words (l).')
  ba = bytearray (urandom (len(l)))
  mixed = list()
  for c in ba:
    i = c % len(l)
    word = l[i]
    mixed.append (word)
    l.remove(word)
  return mixed

# main (argv):
if (len(argv)==2)and(argv[1]=='-h'):
  print (license);
  exit (0);
s = stdin.read()
words = get_words (s)
#print (words)
mixed = mix_words (words)
del (words)
#print (mixed)
line = ''
ncols = 0
try:
  ncols = int (argv[1])
except IndexError:
  pass
except ValueError:
  print (license)
  exit (0)
#nwords = 0
for word in mixed:
  #nwords += 1
  if ncols:
    if (len(line)+1+len(word)) <= ncols:
      if len(line)>0: # Don't put a space at the beginning.
        line += ' ' + word
      else:
        line += word
    else: # len(line) reached its limit.
      print (line)
      line = '' + word
  else: # ncols is 0
    if len(line)>0:
        line += ' ' + word
    else:
      line += word
print (line)
#print (str(nwords)+' words were printed.')
