def calcpurchases(numtries,numpurchases):
   buychoices = {}

   # print ".. trying options for ",numpurchases," number of purchases...tries",numtries
   # now running multiprocessor, only put out a status bar for the first job.
   for i in xrange(numtries):
      buyamounts = rebalance.constrained_sum_sample_pos(numpurchases,int(addedcash - (fee * numpurchases)))
      buycode = []
      intermedport = []
      buypattern = []
      asxcodestobuy = copy.copy(asxcodestochoosesorted)
      # we have the sorted list of ASX codes, so randomly remove some from the list until we
      # only have numpurchases left
      while len(asxcodestobuy) > numpurchases:
          asxcodestobuy.remove(random.choice(asxcodestobuy))

      # print "for numpurchases",numpurchases,"have  asxcodestobuy", asxcodestobuy
          
      codestobuy = asxcodestochoosesorted
      for purchase in xrange(numpurchases):
         # since the intervals chosen are random anyway, we dont need to randomly choose an ASX code?
         # so we can do it in order of largest to smallest shareprice
	 buycode.append(asxcodestobuy[purchase][1])
         # lets grab the asx code in order of lowest to highest share price, deleting 
         # lets round the amount down to a multiple of share price, and add the remainder to the next purchase..
         # proivided we got a share price (which we may have not if it is not a share already in the portfolio)
         if starterport[buycode[purchase]][3] > 0.0:
            remainder = buyamounts[purchase] % starterport[buycode[purchase]][3]
            # print remainder,purchase,numpurchases,buyamounts
            if purchase < numpurchases -1:
               buyamounts[purchase] = buyamounts[purchase] - remainder
               buyamounts[purchase + 1] = buyamounts[purchase + 1] + remainder
         
	 if purchase == 0:
	    intermedport.append(rebalance.rebalance(buyamounts[purchase],starterport,buycode[purchase]))
	 else:
	    intermedport.append(rebalance.rebalance(buyamounts[purchase],intermedport[purchase - 1],buycode[purchase]))
	 buypattern.append(buyamounts[purchase])
	 buypattern.append(buycode[purchase])
      newport = intermedport[-1]
      newrating = rebalance.isrebalancegood(newport)
      buychoices[newrating] = buypattern

   # just grab the top rated one, we dont have to pass the whole lot back
   # this step a holdover from when the non-parallel code putting it all in one global dict.
   sortratings = buychoices.keys()
   sortratings.sort()
   # print "ending worker with numtries",numtries,"numpurchases",numpurchases

   return({ sortratings[0] : buychoices[sortratings[0]] })
starterports = []
firstcsv = True
for csvfile in inputcsvfiles:
   starterports.append(rebalance.read_cmc_pnl_to_portfdict(csvfile,desiredport))
   if not firstcsv:
      starterports.append(rebalance.add_portfdict(starterports[-2],starterports[-1]))
   else:
      firstcsv = False

portfolios = [starterports[-1]]
starterport = starterports[-1]

print "starter portfolio"
rebalance.printport(starterport)
starterrating = rebalance.isrebalancegood(starterport)
print "starter rating", starterrating

totalspend = 0
fees = 0
for buycode,buyamount in buysequence:
   print  "buy ",buyamount," of ",buycode
   portfolios.append(rebalance.rebalance(float(buyamount),portfolios[-1],buycode))
   totalspend = totalspend + float(buyamount)
   fees = fees + fee
   rebalance.printport(portfolios[-1])
   print "rating of ",rebalance.isrebalancegood(portfolios[-1])

print "totalspend is: ",totalspend," (inc fees is: ",totalspend + fees," )"
print "fees are: ",fees," which is ",fees/(totalspend + fees) * 100," per cent"
if __name__ == '__main__':
   try:
      fee, desiredport, singleproc = rebalance.readconfig(sys.argv[1])
      cmcpnlcsvfilename = sys.argv[2]
      addedcash = float(sys.argv[3])
      numtries = int(sys.argv[4])
   except:
      usage()

   starterport = rebalance.read_cmc_pnl_to_portfdict(cmcpnlcsvfilename,desiredport)

   buychoices = {}

   print "starter portfolio, loaded from the file ",cmcpnlcsvfilename
   rebalance.printport(starterport)
   starterrating = rebalance.isrebalancegood(starterport)
   print "starter balance rating (i.e. how close to the desired balance):", starterrating
   print

   # first gather all the single buy choices.
   for asxcode in starterport.keys():
      newport = rebalance.rebalance(addedcash - fee,starterport,asxcode)
      newrating = rebalance.isrebalancegood(newport)
      # print asxcode,newrating
      # if newrating > starterrating or asxcode == 'TOTALS:':
      if asxcode == rebalance.TOTALS:
	 # print "dont bother with", asxcode
	 pass
      else:
	 buychoices[newrating] = [addedcash,asxcode]