import multiprocessing


def splitList(inputList, bins = None, preserveOrder = False):
   """Split a list into sublists and return the list of sublists.

   Args:
       inputList: The list to be split
       bins: The number of bins. Overrides cpu_count()
       preserveOrder: if true, append to each sublist in list order, otherwise round robin.

   Returns:
       List of sublists.
   """

   # Break the list of candidates up into the number of CPUs
   listLength = len(inputList)

   if bins: # and bins <= 256:
      nProcessors = bins
   else:
      nProcessors = multiprocessing.cpu_count()

   if listLength <= nProcessors:
      nProcessors = listLength


   # Create nProcessors x empty arrays
   listChunks = [ [] for i in range(nProcessors) ]

   i = 0

   if preserveOrder:
      # work out the remainder
      remainder = listLength % nProcessors
      chunkSize = listLength / nProcessors

      ch = 0
      for item in inputList:
         listChunks[i].append(item)
         ch += 1
         if remainder > 0:
             rem = 1
         else:
             rem = 0

         if ch >= chunkSize + rem:
            i += 1
            ch = 0

            if remainder > 0:
               remainder -= 1
   else:
      for item in inputList:
         listChunks[i].append(item)
         i += 1
         if i >= nProcessors:
            i = 0

   return nProcessors, listChunks