



#
# Sort large text files in a minimum amount of memory
#
import argparse
import os





class    __lowerCAmelCase					:
				__lowerCamelCase					=							'''block_{0}.dat'''




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       filename
									_lowerCAmelCase         =       []




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.BLOCK_FILENAME_FORMAT.format(_snake_case						)
									with open(_snake_case		,							"""w"""						) as file:
														file.write(_snake_case						)
									self.block_filenames.append(_snake_case						)




				def 				snake_case  (				self						):



									"""simple docstring"""





									return self.block_filenames




				def 				snake_case  (				self		,							_snake_case		,							_snake_case=None						):



									"""simple docstring"""





									_lowerCAmelCase         =       0
									with open(self.filename						) as file:
														while True:
																			_lowerCAmelCase         =       file.readlines(_snake_case						)

																			if lines == []:
																								break

																			if sort_key is None:
																								lines.sort()
																			else:
																								lines.sort(key=_snake_case						)

																			self.write_block("""""".join(_snake_case						)		,							_snake_case						)
																			i += 1




				def 				snake_case  (				self						):



									"""simple docstring"""





									map(os.remove		,							self.block_filenames						)





class    __lowerCAmelCase					:




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       -1
									_lowerCAmelCase         =       None

									for i in range(len(_snake_case						)						):
														if min_str is None or choices[i] < min_str:
																			_lowerCAmelCase         =       i

									return min_index





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       files
									_lowerCAmelCase         =       set()
									_lowerCAmelCase         =       len(_snake_case						)
									_lowerCAmelCase         =       {i: None for i in range(self.num_buffers						)}




				def 				snake_case  (				self						):



									"""simple docstring"""





									return {
									    i: self.buffers[i] for i in range(self.num_buffers						) if i not in self.empty
									}




				def 				snake_case  (				self						):



									"""simple docstring"""





									for i in range(self.num_buffers						):
														if self.buffers[i] is None and i not in self.empty:
																			_lowerCAmelCase         =       self.files[i].readline()

																			if self.buffers[i] == "":
																								self.empty.add(_snake_case						)
																								self.files[i].close()

									if len(self.empty						) == self.num_buffers:
														return False

									return True




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.buffers[index]
									_lowerCAmelCase         =       None

									return value





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       merge_strategy




				def 				snake_case  (				self		,							_snake_case		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       FilesArray(self.get_file_handles(_snake_case		,							_snake_case						)						)
									with open(_snake_case		,							"""w"""		,							_snake_case						) as outfile:
														while buffers.refresh():
																			_lowerCAmelCase         =       self.merge_strategy.select(buffers.get_dict()						)
																			outfile.write(buffers.unshift(_snake_case						)						)




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       {}

									for i in range(len(_snake_case						)						):
														_lowerCAmelCase         =       open(filenames[i]		,							"""r"""		,							_snake_case						)  # noqa: UP015

									return files





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       block_size




				def 				snake_case  (				self		,							_snake_case		,							_snake_case=None						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.get_number_blocks(_snake_case		,							self.block_size						)
									_lowerCAmelCase         =       FileSplitter(_snake_case						)
									splitter.split(self.block_size		,							_snake_case						)

									_lowerCAmelCase         =       FileMerger(NWayMerge()						)
									_lowerCAmelCase         =       self.block_size / (num_blocks + 1)
									merger.merge(splitter.get_block_filenames()		,							filename + """.out"""		,							_snake_case						)

									splitter.cleanup()




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									return (os.stat(_snake_case						).st_size / block_size) + 1


def 						_UpperCAmelCase							( snake_case     ):





					"""simple docstring"""

					if string[-1].lower() == "k":
										return int(string[:-1]     ) * 10_24
					elif string[-1].lower() == "m":
										return int(string[:-1]     ) * 10_24 * 10_24
					elif string[-1].lower() == "g":
										return int(string[:-1]     ) * 10_24 * 10_24 * 10_24
					else:
										return int(snake_case     )


def 						_UpperCAmelCase							( ):





					"""simple docstring"""

					_lowerCAmelCase         =       argparse.ArgumentParser()
					parser.add_argument(
					    """-m"""      ,		"""--mem"""      ,		help="""amount of memory to use for sorting"""      ,		default="""100M"""     )
					parser.add_argument(
					    """filename"""      ,		metavar="""<filename>"""      ,		nargs=1      ,		help="""name of file to sort"""     )
					_lowerCAmelCase         =       parser.parse_args()

					_lowerCAmelCase         =       ExternalSort(parse_memory(args.mem     )     )
					sorter.sort(args.filename[0]     )


if __name__ == "__main__":
	main()






def   UpperCamelCase(   lowercase_				)      ->							str:





  '''simple docstring'''





  return "".join(chr(ord(lowercase_				) + 32				) if """A""" <= char <= """Z""" else char for char in word				)


if __name__ == "__main__":
    from doctest import testmod

    testmod()