import VS
import Director
import fg_util
import vsrandom
import faction_ships
import universe
import dynamic_universe
import dynamic_news
import debug
import generate_dyn_universe
import PickleTools
import dynamic_battle


global dnewsman_
dnewsman_ = dynamic_news.NewsManager()
baseship=None
plr=0
basefac='neutral'

mission_script_template = '''
import mission_lib
import %(module)s
temp=%(module)s.%(constructor)s%(args)r
mission_lib.AddMissionHooks(temp)
temp=0
'''

# PODXX per-system counters to track each generated mission type
perSystemMissions = {}

def resetPerSystemMissionsCounters():
  global perSystemMissions
  perSystemMissions = {}

def increaseMissionsCounter(missionKey):
  global perSystemMissions
  try:
    cnt = perSystemMissions[missionKey]
    perSystemMissions[missionKey] = cnt+1
  except:
    perSystemMissions[missionKey] = 1

def getMissionsCounter(missionKey):
  global perSystemMissions
  try:
    return perSystemMissions[missionKey]
  except:
    return 0

def isExcessiveMission(missionKey, cap):
    mcnt = getMissionsCounter( missionKey )
    if mcnt >= cap:
#      print "PODXXX excessive mission[" + missionKey + "] count[" + str(mcnt) + "]"
      return True
    else:
      return False

# load the company names & briefing text from files only once
company_names = []
cargo_briefs  = []
attack_briefs = []
attackpod_briefs = []
patrol_briefs = []
defend_briefs = []
escort_briefs = []
escortpod_briefs = []
rescue_briefs = []
bounty_briefs = []
scout_briefs  = []

def formatShip(ship):
    where=ship.find(".blank")
    if (where!=-1):
        ship=ship[0:where]
    return ship.capitalize()

def formatCargoCategory(ship):
    where=ship.rfind("/")
    if (where!=-1):
        ship=ship[where+1:]
    return ship.capitalize()

#Credit to Peter Trethewey, master of python and all things nefarious
def getSystemsKAwayNoFaction( start, k ):
    set = [start]#set of systems that have been visited
    pathset = [[start]]#parallel data structure to set, but with paths
    pathtor = [[start]]#parallel data structure to raw return systems with path
    r = [start] #raw data structure containing systems n away where n<=k
    for n in range(0,k):
        set.extend(r)
        pathset.extend(pathtor)
        r=[]
        pathtor=[]
        for iind in range(len(set)):
            i = set[iind]
            l = universe.getAdjacentSystemList(i)
            for jind in range(len(l)):
                j=l[jind]
                if not (j in set or j in r):
                    r.append(j)
                    pathtor.append(pathset[iind]+[j])
    return pathtor

def getSystemsNAway (start,k,preferredfaction):
    l = getSystemsKAwayNoFaction(start,k)
    if (preferredfaction==None):
        return l
    lbak=l
    if (preferredfaction==''):
        preferredfaction=VS.GetGalaxyFaction(start)
    i=0
    while i <len(l):
        if (VS.GetRelation(preferredfaction,VS.GetGalaxyFaction(l[i][-1]))<0):
            del l[i]
            i-=1
        i+=1
    if (len(l)):
        return l
    return lbak


def LoadList(filename):
	bnl = []
	print 'Importing list from: ' + filename
	try:
		f = open (filename,'r')
		bnl = f.readlines()
		f.close()
	except:
		return []
	# strip newlines
	for i in range(len(bnl)):
		bnl[i]=bnl[i].rstrip()
	return bnl

def GetRandomFromList(list):
	import vsrandom
	idx = vsrandom.randint(0,len(list)-1)
	return list[idx]

def GetRandomCompanyName():
	#print 'reading company names '
	global company_names
	if (len(company_names) == 0):
		filename = 'universe/companies.txt'
		company_names = LoadList(filename)
	return GetRandomFromList(company_names)

def GetRandomCargoBrief():
	#print 'generating cargo briefing'
	global cargo_briefs
	if (len(cargo_briefs) == 0):
		filename = 'universe/cargo_brief.txt'
		cargo_briefs = LoadList(filename)
	return GetRandomFromList(cargo_briefs)

def GetRandomAttackBrief():
	#print 'generating attack briefing'
	global attack_briefs
	if (len(attack_briefs) == 0):
		filename = 'universe/attack_brief.txt'
		attack_briefs = LoadList(filename)
	return GetRandomFromList(attack_briefs)

def GetRandomAttackPodBrief():
	#print 'generating attack-pod briefing'
	global attackpod_briefs
	if len( attackpod_briefs) == 0:
		filename = 'universe/attackpod_brief.txt'
		attackpod_briefs = LoadList( filename)
	return GetRandomFromList(attackpod_briefs)

def numPatrolPoints(sysname,cleansweep=0):
    npp = 0;
    try:
        import faction_ships
        mmax=faction_ships.numPatrolPoints[sysname]
        if mmax == 1:
          return 1
        
        if cleansweep:
          if mmax > 3:
            mmax = 3
          npp = vsrandom.randrange(1,mmax+1)
        
        else:
          if mmax <= 4:
            npp = mmax
          else:
            if mmax > 6:
              mmax = 6
            npp = vsrandom.randrange(4,mmax+1)
    except:
        npp = 1
    #print "PODXXX numPatrolPoints for system [" + sysname + "] is [" + str(npp) + "]"
    return npp

def GetRandomPatrolBrief():
	#print 'generating patrol briefing'
	global patrol_briefs
	if (len(patrol_briefs) == 0):
		filename = 'universe/patrol_brief.txt'
		patrol_briefs = LoadList(filename)
	return GetRandomFromList(patrol_briefs)

def GetRandomScoutBrief():
	#print 'generating scout briefing'
	global scout_briefs
	if (len(scout_briefs) == 0):
		filename = 'universe/scout_brief.txt'
		scout_briefs = LoadList(filename)
	return GetRandomFromList(scout_briefs)

def GetRandomDefendBrief():
	#print 'generating defend briefing'
	global defend_briefs
	if (len(defend_briefs) == 0):
		filename = 'universe/defend_brief.txt'
		defend_briefs = LoadList(filename)
	return GetRandomFromList(defend_briefs)

def GetRandomEscortBrief():
	#print 'generating escort briefing'
	global escort_briefs
	if (len(escort_briefs) == 0):
		filename = 'universe/escort_brief.txt'
		escort_briefs = LoadList(filename)
	return GetRandomFromList(escort_briefs)

def GetRandomEscortPodBrief():
	#print 'generating escort-pod briefing'
	global escortpod_briefs
	if (len(escortpod_briefs) == 0):
		filename = 'universe/escortpod_brief.txt'
		escortpod_briefs = LoadList(filename)
	return GetRandomFromList(escortpod_briefs)

def GetRandomRescueBrief():
	#print 'generating rescue briefing'
	global rescue_briefs
	if (len(rescue_briefs) == 0):
		filename = 'universe/rescue_brief.txt'
		rescue_briefs = LoadList(filename)
	return GetRandomFromList(rescue_briefs)

def GetRandomBountyBrief():
	#print 'generating bounty briefing'
	global bounty_briefs
	if (len(bounty_briefs) == 0):
		filename = 'universe/bounty_brief.txt'
		bounty_briefs = LoadList(filename)
	return GetRandomFromList(bounty_briefs)

def getCargoName(category):
    l=category.split('/')
    if len(l)>1:
        cargo = l[len(l)-1]+' '+l[0]
    else:
        cargo = category
    cargo = cargo.replace('_',' ')
    return cargo

def getMissionDifficulty ():
    import difficulty
    tmp=difficulty.getPlayerUnboundDifficulty(VS.getCurrentPlayer())
    if (tmp>1.5):
        tmp=1.5
    return tmp

def getPriceModifier(isUncapped):
    return 1.0    #PODXX
#    return 1.15
    import difficulty
    if (not difficulty.usingDifficulty()):
        return 1.0
    if (isUncapped):
        return getMissionDifficulty()/.5+.9
    return VS.GetDifficulty()/.5+.9

def getSystemDifficulty( system):
    shortname = system[7:]
    if shortname in ["Perry","New_Constantinople","New_Detroit"]:
      return .25
    if shortname in ["Troy","Manchester","ND-57","Raxis","Varnus","Newcastle"]:
      return .5
    if shortname in ["Junction","XXN-1927","Oxford","Shangri_La","Metsor","Saxtogue","44-p-im","Padre","119ce"]:
      return 1.0
    if shortname in ["Auriga","Midgard","Castor","Aldebran","Hinds_Variable_N","Pentonville"]:
      return 1.5
    if shortname in ["Penders_Star","Pyrenees"]:
      return 2.0
    if shortname in ["Nexus","Freyja","Regallis","DN-N1912","CM-N1054","Rikel"]:
      return 2.5
    if shortname in ["J900","Crab-12","Sherwood","New_Caledonia","Prasepe","Pollux","Tingerhoff","Palan"]:
      return 3.0
    if shortname in ["Rygannon","Xytani","Ragnarok","Nitir","Surtur","CMF-A"]:
      return 3.5
    if shortname in ["Capella","KM-252","Telar","17-ar","Death","Pestilence","War","Famine","Valhalla","Eden"]:
      return 4.0
    if shortname in ["Blockade_Point_Alpha","Blockade_Point_Charlie","Hyades","Blockade_Point_Tango","Lisacc","41-gs"]:
      return 5.0
    if shortname in ["Sumn_Kpta","Mah_Rahn","Tr_Pakh"]:
      return 8.0
      
    return 0.1   # just in case

def calcPathDifficulty(path,includeDest=1):
    diff = 0
    for p in path:
      if p == path[-1] and not includeDest:
        break
      diff += getSystemDifficulty(p)
    return diff

def calcPathLengthBonus(path):
    pl = len(path)
    if pl <= 3:
      return 0
    return (pl-3)*vsrandom.randrange(1000,1500)


def isDeadEndSystem( systemName):
    sysShortName = systemName[7:]
    return sysShortName in [ "Rygannon", "Shangri_La", "Padre", "Auriga", "Prasepe","Pollux","DN-N1912", "Hyades", "CM-N1054", "Lisacc", "41-gs", "Valhalla", "Mah_Rahn"]
    

def calcDeadEndBonus( curSystem, destSystem, onlyTrueDeadEnds = False):
    if curSystem != destSystem:
        if isDeadEndSystem( destSystem):
            return vsrandom.randrange(750,1000)
        if onlyTrueDeadEnds:
            return 0
        if (destSystem[7:] == "Xytani" and curSystem <> "Gemini/Rygannon") or (destSystem[7:] == "Hinds_Variable_N" and curSystem <> "Gemini/DN-N1912"):
            return vsrandom.randrange(550,800)
    return 0

    
def processSystem(sys):
    k= sys.split('/')
    if (len(k)>1):
        k=k[1]
    else:
        k=k[0]
    return k

    
def isFixerString(s):
    k=str(s)
    if (len(k)<2):
        return 0
    if (k[1]=='F'):
        return 1
    if (k[1]=='G'):
        return 2
    return 0
    
    
def writemissionname(name,path,isfixer):
    if (isfixer==0):
        if path[-1]==VS.getSystemFile():
            name="In_System_"+name
    Director.pushSaveString(plr, "mission_names", name)

    
def writedescription(name):
    Director.pushSaveString(plr, "mission_descriptions", name.replace("_"," "))
def writemissionsavegame (name):
    Director.pushSaveString(plr, "mission_scripts", name)
def writemissionvars (vars):
    Director.pushSaveString(plr, "mission_vars", PickleTools.encodeMap(vars))
def eraseExtras():
	Director.clearSaveString(plr, "mission_scripts")
	Director.clearSaveString(plr, "mission_names")
	Director.clearSaveString(plr, "mission_descriptions")
	Director.clearSaveString(plr, "mission_vars")


use_missioncomputer=1
fixer_has_rescue=0
fixer_has_wingman=0

fixerpct=0.0
guildpct=0.4

def randomCredModifier():
    return vsrandom.randrange(0,700) - 200
    
def getEnemyShipValue(enemy):
    if enemy == "retro":
      return 600
    elif enemy == "pirates":
      return 700
    elif enemy == "kilrathi":
      return 2000
    return 1500;

    
def generateAttackMission( path, enemyFac):
    missionKey = "attack " + str( path[-1])
    if isExcessiveMission( missionKey, 1):
      return
    increaseMissionsCounter( missionKey)

    try:
        sysNavpoints = systemsNPDict[ path[-1] ]
        npName = sysNavpoints[ vsrandom.randrange( 0, len( sysNavpoints)) ]
    except:
        print "PODXXatk could not find dest NP for system: " + path[-1]
        return
    
    avgShipValue = max( 800, getEnemyShipValue( enemyFac))
    
    # choose numShips, depends on a sysdiff and faction
    sysDiff = getSystemDifficulty( path[-1])
    if   sysDiff <= .5:
        numShips = vsrandom.randrange( 3, 5)
    elif sysDiff <= 1.5:
        numShips = vsrandom.randrange( 4, 7)
    elif sysDiff <= 2.0:
        numShips = vsrandom.randrange( 5, 8)
    elif sysDiff <= 2.5:
        numShips = vsrandom.randrange( 5, 9)
    elif sysDiff <= 3.5:
        numShips = vsrandom.randrange( 6, 11)
    else:
        numShips = vsrandom.randrange( 7, 13)
    
    if enemyFac == "kilrathi":    
        if   sysDiff <= 3.0:
            numShips = vsrandom.randrange( 3, 5)
        elif sysDiff <= 3.5:
            numShips = vsrandom.randrange( 5, 7)
        else:
            numShips = vsrandom.randrange( 6, 9)

    creds = int( randomCredModifier() + avgShipValue*numShips*vsrandom.randrange( 85, 115)*.01 + vsrandom.randrange( 400, 600)*calcPathDifficulty( path) + calcDeadEndBonus( path[0], path[-1]) )

    bcreds = creds
    addstr = ""
    if vsrandom.random() < min( .9, creds/9000.0):
        if creds*1.3 <= 8000:
          creds *= 1.3
        elif creds*1.2 <= 11000:
          creds *= 1.2
        elif creds*1.1 <= 15000:
          creds *= 1.1
        addstr += "#G#Attack#\n"
    elif use_missioncomputer:
        addstr += "#C#Attack#\n"

    creds *= getPriceModifier( False)
        
    print "PODXXX " + addstr + " enemy [" + str( enemyFac) + "] numShips [" + str( numShips) + "] creds [" + str( bcreds) + "/" + str( creds) + "] path " + str( path) + ", npName: " + npName

    composedBrief = GetRandomAttackPodBrief().replace( '$CL', GetRandomCompanyName())
    composedBrief = composedBrief.replace( '$MT', enemyFac.capitalize())
    composedBrief = composedBrief.replace( '$NP', npName)
    composedBrief = composedBrief.replace( '$DS', processSystem( path[-1]))
    composedBrief = composedBrief.replace( '$PY', str( int( creds)))
    
    if len( path) == 1:
        mistype = 'IN-SYSTEM ATTACK'
    else:
        mistype = 'ATTACK'
        
    writedescription( "\n" + composedBrief)
    writemissionsavegame( addstr + mission_script_template % dict(
        module = "attack_pod",
        constructor = "attack_pod",
        args = ( creds, path, npName, numShips, enemyFac) ))

    writemissionname( "Attack/Attack %s ships at %s in %s system. Autopayment %i credits."%( enemyFac.capitalize(), npName, processSystem( path[-1]), creds), path, isFixerString( addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )

    
def generatePatrolMission (path,numplanets,enemy):
    if len(path) > 3:
      return
    missionKey = "patrol " + str(path[-1])
    if isExcessiveMission(missionKey, 1):
      return
    increaseMissionsCounter(missionKey)

    scanDist=400

    creds = int( randomCredModifier() + vsrandom.randrange( 400, 600)*calcPathDifficulty( path) + numplanets*vsrandom.randrange(400,500) + calcDeadEndBonus( path[0], path[-1]) ) #+ calcPathLengthBonus(path) )   + 1000*getSystemDifficulty( path[-1])

    bcreds = creds
    addstr=""
    guildRewardMod = 1.0
    if vsrandom.random() < min( .9, creds/7000.0):
        creds *= 1.2
        guildRewardMod = 1.2          # will be used only for extra payment
        addstr+="#G#Patrol#\n"
    elif use_missioncomputer:
        addstr+="#C#Patrol#\n"

    creds*=getPriceModifier(False)
    additional=()
    additionalinstructions=""

    print "PODXXX " + addstr + " [" + str(numplanets) + "] creds [" + str(bcreds) + "/" + str(creds) + "] path " + str(path)

    randCompany = GetRandomCompanyName()
    patrolb = GetRandomPatrolBrief()
    composedBrief = patrolb.replace('$CL',randCompany)
    composedBrief = composedBrief.replace('$NP',str(int(numplanets)))
    composedBrief = composedBrief.replace('$DS',processSystem(path[-1]))
    composedBrief = composedBrief.replace('$PY',str(int(creds)))
    composedBrief = composedBrief.replace('$EN',(str(enemy)).capitalize())
    ispoint = "s"
    if numplanets == 1:
        ispoint = ""
    if len( path) == 1:
        mistype = 'IN-SYSTEM PATROL'
    else:
        mistype = 'PATROL'
    writedescription( "\n" + composedBrief)
    writemissionsavegame ( addstr + mission_script_template % dict(
        module='patrol_pod',
        constructor='patrol_pod',
        args = ( 0, numplanets, scanDist, creds, path, guildRewardMod) ))

    writemissionname("Patrol/Patrol %d navpoint%s in %s for hostile presence. Autopayment %i credits and an extra payment per every outlaw ship."%(numplanets,ispoint, processSystem(path[-1]),creds),path,isFixerString(addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )
 
    
def generateScoutLocalMission(path,enemy):
    if len(path) > 1:
      return
      
    sysName = processSystem(path[0])
    navpoints = universe.getNonBaseSignificants()
    scoutSigName = (navpoints[ vsrandom.randrange(0,len(navpoints)) ]).getName()
    
    missionKey = "scout " + scoutSigName + str(path[0])
    if isExcessiveMission(missionKey, 1):
      return
    increaseMissionsCounter(missionKey)

    shipvalue = 1000   #getEnemyShipValue(enemy)
    forceattack = vsrandom.randrange(33,66) * 0.01

    fighterprob=vsrandom.randrange(40,70)*0.01;
    
    sysdiff = getSystemDifficulty(path[-1])
    
    if enemy in ["retro","pirates"]:
      minships=vsrandom.randrange(2,4)
      maxships=vsrandom.randrange(minships,4)
      q = 2
      if sysdiff < 1:
        q = 1.5
        minships -= 1
        maxships -= 1
    else:
      minships = maxships = 1
      q = 1.5
      if sysdiff >= 2:
        q = 2.5
        maxships = 2

    creds = int( randomCredModifier() + shipvalue * q + vsrandom.randrange(400,500)*sysdiff )

    bcreds = creds
    addstr=""
    if vsrandom.random() < min( .9, creds/6000.0):
        if (creds*1.2) <= 3500:
          creds*=1.2
        else:
          creds*=1.1
        addstr+="#G#Scout#\n"
    elif use_missioncomputer:
        addstr+="#C#Scout#\n"

    creds*=getPriceModifier(False)

    print "PODXXX " + addstr + " scoutSigName[" + scoutSigName + "] enemy [" + str(enemy) + "] minmaxships [" + str(minships) + "-" + str(maxships) + "] creds [" + str(bcreds) + "/" + str(creds) + "] prob [" + str(fighterprob) + "] fa[" + str(forceattack) + "] path " + str(path)

    dist=1500
    missiontype="scout"

    composedBrief = GetRandomScoutBrief().replace('$CL',GetRandomCompanyName())
    composedBrief = composedBrief.replace('$NP',scoutSigName)
    composedBrief = composedBrief.replace('$DS',sysName)
    composedBrief = composedBrief.replace('$PY',str(int(creds)))
    
    path=[path[0]]
    mistype = 'IN-SYSTEM SCOUT'
        
    writedescription("\n" + composedBrief)
    writemissionsavegame (addstr+mission_script_template % dict(
        module='patrol_enemies',
        constructor='patrol_enemies',
        args=(0,1,dist,creds,path,'',minships,maxships,fighterprob,0,enemy,forceattack,[],"randomize",[scoutSigName]) ))
    writemissionname("Scout/Scout %s in %s system for enemy presence. Autopayment %i credits."%(scoutSigName,sysName,creds),path,isFixerString(addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )

    
def isNotWorthy(fac):
    return VS.GetRelation(fac,VS.getPlayer().getFactionName()) <= -0.06
    
    
def changecat(category):
    l=category.split('/')
    if len(l)>1:
        return l[-1]+'_'+l[0]
    else:
        return category

        
HabitablePlanetTypes = ['i', 'a', 'am', 'u', 'com', 'bd', 's', 'o', 'at', 'bs', 'bdm', 'bsm', 'f', 'fm', 't']

def isHabitable( system):
    planetlist = VS.GetGalaxyProperty( system, "planets")
    if len( planetlist) == 0:
        return False
    planets = planetlist.split(' ')
    for planet in planets:
        if planet in HabitablePlanetTypes:
            return True
    #debug.debug(str(planets)+ " Not in Habitable List")
    return False
    

def getMilitiaRisk4System( system):
    shortname = system[7:]
    if shortname in ["Perry","New_Constantinople","New_Detroit","Tingerhoff","Junction","XXN-1927"]:
      return 0.9
    if shortname in ["Troy","Manchester","ND-57","Raxis","Newcastle","Varnus","New_Caledonia","Hinds_Variable_N"]:
      return 0.65
    if shortname in ["Metsor","Oxford","Penders_Star","Saxtogue","44-p-im","119ce"]:
      return .3
    if shortname in ["Sherwood","Nexus","Rikel","Pyrenees","Regallis","Padre","Auriga","Midgard","Shangri_La","Castor","Palan","Aldebran"]:
      return .5
    if shortname in ["Rygannon","Xytani","Ragnarok","Nitir","Surtur","CMF-A"]:
      return .5
    if shortname in ["Freyja","J900","Crab-12","Prasepe","Pollux","DN-N1912"]:
      return .3
    if shortname in ["Blockade_Point_Alpha","Blockade_Point_Charlie","Hyades","Blockade_Point_Tango","Lisacc"]:
      return .65
    if shortname in ["Capella","KM-252","Telar","17-ar","Death","Pestilence","War","Famine","Valhalla","Eden"]:
      return 0.1
    if shortname in ["Sumn_Kpta","Mah_Rahn","Tr_Pakh"]:
      return 0.1
      
    return 0.1   # ,"41-gs","CM-N1054","Pentonville"

    
def calcMilitiaRisk( path):
    risk = 0
    for p in path:
      risk += getMilitiaRisk4System( p)
    return risk
    
    
systemsBaseDict = {
      'Gemini/Oxford':['Oxford'],
      'Gemini/XXN-1927':['Jolson','Joplin'],
      'Gemini/Saxtogue':['Olympus'],
      'Gemini/New_Detroit':['New_Detroit'],
      'Gemini/New_Constantinople':['New_Constantinople','Edom'],
      'Gemini/Aldebran':['Matahari'],
      'Gemini/Auriga':['Beaconsfield','Elysia'],
      'Gemini/Castor':['Romulus'],
      'Gemini/Hyades':['Charon'],
      'Gemini/Junction':['Victoria','Speke','Burton'],
      'Gemini/DN-N1912':['N1912-1'],
      'Gemini/Lisacc':['Lisacc'],
      'Gemini/Manchester':['Wickerton','Thisbury'],
      'Gemini/Midgard':['Heimdal'],
      'Gemini/ND-57':['New_Reno'],
      'Gemini/New_Caledonia':['Edinburgh','Glasgow'],
      'Gemini/Newcastle':['Liverpool'],
      'Gemini/Nexus':['Macabee'],
      'Gemini/Nitir':['Nitir'],
      'Gemini/Padre':['Magdaline'],
      'Gemini/Prasepe':['Saratov'],
      'Gemini/Pyrenees':['New_Iberia','Basque'],
      'Gemini/Palan':['Palan','Basra'],
      'Gemini/Perry':['Anapolis','Perry_Naval_Base'],
      'Gemini/Pollux':['Remus'],
      'Gemini/Regallis':['Kronecker'],
      'Gemini/Rikel':['Siva','Vishnu'],
      'Gemini/Ragnarok':['Mjolnir'],
      'Gemini/Raxis':['Gracchus','Trinsic'],
      'Gemini/Tingerhoff':['Bodensee','Munchen'],
      'Gemini/Rygannon':['Rygannon'],
      'Gemini/Surtur':['Surtur'],
      'Gemini/Troy':['Achilles','Helen','Hector'],
      'Gemini/Varnus':['Rilke','Rodin'],
      'Gemini/Valhalla':['Valkyrie'],
      'Gemini/Shangri_La':['Erewhon'],
      'Gemini/Hinds_Variable_N':['Meadow','Oresville']
    }
    
systemsNPDict = {
      'Gemini/Oxford':['Jump_To_Saxtogue', 'Jump_To_Shangri_La', 'Jump_To_XXN-1927'],
      'Gemini/XXN-1927':['Jump_To_Oxford', 'Jump_To_New_Detroit', 'Jump_To_New_Constantinople', 'Jump_To_Metsor', 'Jump_To_119CE'],
      'Gemini/Saxtogue':['Jump_To_New_Detroit', 'Jump_To_Oxford'],
      'Gemini/New_Detroit':['Jump_To_Saxtogue', 'Jump_To_XXN-1927', 'Jump_To_Rikel', 'Jump_To_Raxis', 'Jump_To_Manchester', 'Jump_To_New_Constantinople', 'Jump_To_Perry', 'Jump_To_ND-57'],
      'Gemini/New_Constantinople':['Jump_To_New_Detroit', 'Jump_To_XXN-1927', 'Jump_To_Newcastle', 'Jump_To_Junction', 'Jump_To_Varnus', 'Jump_To_Junction', 'Jump_To_44-P-IM'],
      'Gemini/Aldebran':['Jump_To_New_Constantinople', "Jump_To_Hind's_Variable_N"],
      'Gemini/Auriga':['Jump_To_Newcastle','Nav_3'],
      'Gemini/Castor':['Jump_To_Junction'],
      'Gemini/Hyades':['Jump_To_Blockade_Point_Charlie', "Jump_To_Sumn-Kp'ta", 'Nav_3'],
      'Gemini/Junction':['Jump_To_J900', 'Jump_To_Nexus', 'Jump_To_Castor', 'Jump_To_New_Constantinople', 'Jump_To_119CE', "Jump_To_Pender's_Star"],
      'Gemini/DN-N1912':["Jump_To_Hind's_Variable_N"],
      'Gemini/Lisacc':['Jump_To_Blockade_Point_Tango'],
      'Gemini/Manchester':['Jump_To_New_Detroit'],
      'Gemini/Midgard':['Jump_To_Perry', 'Jump_To_Rikel', 'Nav_2'],
      'Gemini/ND-57':['Jump_To_New_Detroit', 'Nav_2'],
      'Gemini/New_Caledonia':['Jump_To_Prasepe', 'Jump_To_17-AR', 'Jump_To_Crab-12', 'Jump_To_Sherwood'],
      'Gemini/Newcastle':['Jump_To_Metsor', 'Jump_To_Auriga', 'Jump_To_New_Constantinople', 'Jump_To_Perry'],
      'Gemini/Nexus':['Jump_To_Junction', 'Jump_To_Tingerhoff', 'Jump_To_Capella', 'Jump_To_KM-252'],
      'Gemini/KM-252':['Jump_To_Nexus'],
      'Gemini/Nitir':['Jump_To_Perry', 'Jump_To_Blockade_Point_Tango', 'Jump_To_CMF-A', 'Nav_3'],
      'Gemini/Padre':['Jump_To_119CE'],
      'Gemini/Prasepe':['Jump_To_New_Caledonia', 'Nav_2'],
      'Gemini/Pyrenees':['Jump_To_Freyja', 'Jump_To_Troy', 'Jump_To_CM-N1054', 'Nav_5'],
      'Gemini/Palan':['Jump_To_Tingerhoff', 'Jump_To_Xytani', 'Nav_2'],
      'Gemini/Perry':['Jump_To_New_Detroit', 'Jump_To_Newcastle', 'Jump_To_Tingerhoff', 'Jump_To_Midgard', 'Jump_To_Nitir', 'Jump_To_Surtur', 'Jump_To_Ragnarok' ],
      'Gemini/Pollux':['Jump_To_Sherwood', 'Nav_2'],
      'Gemini/Regallis':['Jump_To_Freyja', 'Nav_2', 'Jump_To_Troy', 'Jump_To_Sherwood'],
      'Gemini/Rikel':['Jump_To_New_Detroit', 'Jump_To_Midgard', 'Jump_To_44-P-IM'],
      'Gemini/Ragnarok':['Jump_To_Blockade_Point_Alpha', 'Jump_To_Perry'],
      'Gemini/Raxis':['Jump_To_New_Detroit'],
      'Gemini/Tingerhoff':['Jump_To_CMF-A', 'Jump_To_Palan', 'Jump_To_Perry', 'Jump_To_Nexus'],
      'Gemini/Rygannon':['Jump_To_Xytani'],
      'Gemini/Surtur':['Jump_To_Blockade_Point_Charlie', 'Jump_To_Perry', 'Jump_To_41-GS'],
      'Gemini/Troy':['Jump_To_Pyrenees', "Jump_To_Pender's_Star", 'Jump_To_Regallis', 'Jump_To_War', 'Nav_8'],
      'Gemini/Varnus':['Jump_To_New_Constantinople'],
      'Gemini/Valhalla':['Jump_To_Telar', 'Nav_2'],
      'Gemini/Telar':['Jump_To_Valhalla', 'Jump_To_J900', 'Jump_To_17-AR'],
      'Gemini/Shangri_La':['Jump_To_Oxford'],
      'Gemini/17-ar':['Jump_To_New_Caledonia', 'Jump_To_Telar', 'Nav_2'],
      'Gemini/44-p-im':['Jump_To_Rikel', 'Jump_To_New_Constantinople', 'Nav_2'],
      'Gemini/119ce':['Jump_To_Junction', 'Jump_To_Padre', 'Jump_To_XXN-1927'],
      'Gemini/Capella':['Jump_To_Crab-12', 'Jump_To_Sherwood', 'Jump_To_Famine', 'Jump_To_Nexus'],
      'Gemini/CMF-A':['Jump_To_Tingerhoff', 'Jump_To_Nitir', 'Nav_2'],
      'Gemini/Crab-12':['Jump_To_New_Caledonia', 'Jump_To_Capella', 'Nav_2'],
      'Gemini/Death':['Jump_To_Pestilence', 'Jump_To_Famine', 'Nav_2'],
      'Gemini/Famine':['Jump_To_Death', 'Jump_To_Sherwood', 'Jump_To_Capella', 'Nav_4'],
      'Gemini/Freyja':['Jump_To_Regallis', 'Jump_To_Pyrenees'],
      'Gemini/J900':['Jump_To_Junction', 'Jump_To_Telar', 'Nav_2'],
      'Gemini/Metsor':['Jump_To_Newcastle', 'Jump_To_XXN-1927'],
      'Gemini/Penders_Star':['Jump_To_Junction', 'Jump_To_Troy', 'Nav_2'],
      'Gemini/Pestilence':['Jump_To_Death', 'Jump_To_War', 'Nav_2'],
      'Gemini/Sherwood':['Jump_To_New_Caledonia', 'Jump_To_Regallis', 'Jump_To_Pollux', 'Jump_To_Famine', 'Jump_To_Capella', 'Nav_4', 'Nav_5'],
      'Gemini/Xytani':['Jump_To_Rygannon', 'Jump_To_Palan', 'Nav_2'],
      'Gemini/War':['Jump_To_Pestilence', 'Jump_To_Troy', 'Nav_2'],
      'Gemini/Hinds_Variable_N':['Jump_To_DN-N1912', 'Jump_To_Aldebran', 'Nav_3'],
      'Gemini/41-gs':['Jump_To_Surtur'],
      'Gemini/CM-N1054':['Jump_To_Pyrenees']
    }
  
  
def getRandomBaseName(sysName):
    try:
      sysBases = systemsBaseDict[sysName]
      return sysBases[ vsrandom.randrange(0,len(sysBases)) ]
    except:
      return ''

      
refineryBases = ['Beaconsfield','Joplin','Meadow','Rilke','Munchen','Gracchus','Remus','Anapolis','Basra','Liverpool','Edinburgh','Glasgow','Wickerton','Thisbury',]
agriculturalPlanets = ['Burton','Edom','Elysia','Victoria','Oresville','Erewhon','Rodin','Helen','Surtur','Bodensee','Trinsic','Mjolnir','Siva','Palan','New_Iberia','Nitir','Heimdal',]
pleasurePlanets = ['Magdaline','New_Reno','N1912-1','Speke','Matahari','Olympus','Jolson']
miningBases = ['Valkyrie','Achilles','Hector','Rygannon','Vishnu','Kronecker','Basque','Saratov','Macabee','Lisacc','Charon','Romulus',]


def getBaseType(baseName):
    if baseName in refineryBases:
      return " (refinery)"
    if baseName in agriculturalPlanets:
      return " (agricultural)"
    if baseName in pleasurePlanets:
      return " (pleasure)"
    if baseName in miningBases:
      return " (mining)"
    return ""

    
CARGOS = ['Exotic_Foods','Natural_Furs','Premium_Liquor','Pets',
          'Gems','Plutonium','Uranium','Artwork','Construction',
          'Advanced_Fuels','Communications','Computers','Factory_Equipment',
          'Holographics','Home_Appliances','Medical_Equipment','Spaceship_Parts',
          'Pre_Fabs','Plastics','Robot_Servants','Robot_Workers','Textiles',
          'Passengers','Antique_Books','Mining_Equipment','Food_Dispensers',
          'Home_Entertainment','Tungsten','Iron','Isometal','Wood']

          
def chooseRandomCargo():
    return CARGOS[ vsrandom.randrange(0, len(CARGOS)) ]


def generateCargoMission( path):
    launchcap = 0
    if len( path) <= 1 or not isHabitable( path[-1]):
        return False
        
    missionKey = "cargo " + str(path[-1])
    if isExcessiveMission(missionKey, 2):
      return False
    increaseMissionsCounter(missionKey)

    category = chooseRandomCargo()
    if vsrandom.random() < .15:
        category = 'Contraband'
        numcargos = vsrandom.randrange(10,50)
    else:
        r = vsrandom.random()
        if r > .9:
            numcargos = vsrandom.randrange(125,135)
        elif r > .75:
            numcargos = vsrandom.randrange(90,125)
        elif r < .1:
            numcargos = vsrandom.randrange(15,25)
        elif r < .3:
            numcargos = vsrandom.randrange(25,50)
        else:
            numcargos = vsrandom.randrange(50,90)
            
    cargoVolumeBonus = 0  #vsrandom.randrange(30,50)*numcargos
    
#    nc = numcargos
#    credsMult = 20
#    while nc > 0:
#        nc = nc - 25
#        if nc >= 0:
#            cargoVolumeBonus += 25 * credsMult
#        else:
#            cargoVolumeBonus += (nc + 25) * credsMult
#        credsMult += 5
        
    if numcargos <= 25:
        cargoVolumeBonus = 500
    elif numcargos <= 50:
        cargoVolumeBonus = 750
    elif numcargos <= 75:
        cargoVolumeBonus = 1500
    elif numcargos <= 100:
        cargoVolumeBonus = 2250
    elif numcargos <= 125:
        cargoVolumeBonus = 3250
    else:
        cargoVolumeBonus = 4500

#25: 25  625  625  -     500
#30: 50  1375 1250 -     750
#35: 75  2250 2250 1850  1500
#40: 100 3250 3000       2250
#45: 125 4375 5625 3720  3250
#50: 135 5125 6075       4500
        
    
    destBaseName = getRandomBaseName(path[-1])
    baseType = getBaseType(destBaseName)
    
    isExpress = (category != 'Contraband') and (len(path) > 3) and (vsrandom.random() < .66)
    
    ambushChance = 0
    if vsrandom.random() > .9:
        ambushChance = vsrandom.randrange( 60, 80) * .01
    
    pathDiff = calcPathDifficulty(path)
    creds = int( randomCredModifier() + cargoVolumeBonus + ambushChance*3000 + pathDiff*vsrandom.randrange(300,400) + (category == "Contraband")*2000*calcMilitiaRisk(path) + calcDeadEndBonus(path[0],path[-1]) + calcPathLengthBonus(path))
    if isExpress:
        creds *= 1.15

    bcreds = creds
    addstr=""
    if category != 'Contraband' and ( vsrandom.random() < min( .9, creds/9000.0) ):
        if creds*1.2 < 5000:
            creds*=1.2
        elif creds*1.15 < 7500:
            creds*=1.15
        elif creds*1.1 < 15000:
            creds*=1.1
        addstr+="#G#Cargo#\n"
    elif use_missioncomputer:
        addstr+="#C#Cargo#\n"

    creds*=getPriceModifier(False)

    departBaseName = universe.getDockedBaseNameVerified()
    print "PODXXX " + addstr + " [" + category + "-" + str(numcargos) + "] pathDiff [" + str(pathDiff) + "] ambush[" + str(ambushChance) + "] creds [" + str(bcreds) + "/" + str(creds) + "] isExpress[" + str(isExpress) + "] path " + str(path) + " " + destBaseName + ", departBaseName: " + departBaseName

    cargoName = category
    willClearRecordNote = ''
    if category == 'Contraband':
        contrabands = ['Brilliance','Tobacco','Ultimate']   # no 'Slaves' - glitchy on the VDU for unknown reason
        cargoName = contrabands[vsrandom.randrange(0, len(contrabands))]
        willClearRecordNote = " Your record will be partially cleared upon completion if a patrol chases you."

    customerFactionsList = [ "merchant", "merchant", "merchant", "militia", "confed"]
    customerFaction = customerFactionsList[ vsrandom.randrange( 0, len( customerFactionsList))]
    writemissionsavegame (addstr+mission_script_template % dict(
        module='cargo_mission',
        constructor='cargo_mission',
        args=(customerFaction,0,numcargos,ambushChance,creds,launchcap,0,cargoName,path,'',destBaseName,isExpress, departBaseName)))
        
    randCompany = GetRandomCompanyName()
    if (randCompany==''):
        strStart = "We need to deliver some "
    else:
        strStart = randCompany+" seeks delivery of "
    if len(path)==1:
        mistype = 'IN-SYSTEM CARGO'
    else:
        mistype = 'CARGO'
    brief = GetRandomCargoBrief()
    
    if isExpress:
        brief = "EXPRESS delivery! " + brief + " Payment will be HALVED for landings enroute."
    
    ambushText = ''
    if ambushChance > 0:
        ambushText = " Scouts report an AMBUSH is likely along the route."

    composedBrief = brief.replace('$CL',randCompany)
    composedBrief = composedBrief.replace('$CG',str(numcargos) + " " + formatCargoCategory(category))   #PODXX now quantity will appear in a brief!
    composedBrief = composedBrief.replace('$DB',destBaseName + baseType)
    composedBrief = composedBrief.replace('$DS',processSystem(path[-1]))
    composedBrief = composedBrief.replace('$PY',str(int(creds)))
    composedBrief = composedBrief.replace('$AM', ambushText)
    composedBrief += willClearRecordNote
    writedescription( "\n" + composedBrief)

    briefDest = processSystem(path[-1])
    if len(destBaseName):
        briefDest = destBaseName + baseType + " in " + briefDest

    if ambushChance > 0:
        ambushText = " Ambush is likely."

    expressText = ""
    if isExpress:
        expressText = " Express delivery."
       
    writemissionname("Cargo/Deliver %i %s to %s system.%s Autopayment %i credits.%s"%(numcargos,changecat(category),briefDest,ambushText,creds,expressText),path,isFixerString(addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype, 'NUMCARGOS' : numcargos } )   #PODXX added variable cargo quantity support
    return True


def generateEscortPodMission( path):
    if not isHabitable( path[-1]):
        return False
        
    if len( path) > 1:
        destBaseName = getRandomBaseName( path[-1])
    else:
        try:
            currentBase = universe.getDockedBase()
            destBases = []
            for nb in systemsBaseDict[path[0]]:
                if (currentBase.getName().lower() <> nb.lower()) and (currentBase.getFullname().lower() <> nb.lower()):
                    destBases.append( nb)
            destBaseName = destBases[ vsrandom.randrange(0, len( destBases)) ]
        except:
            return

    destBaseType = getBaseType( destBaseName)
    
    missionKey = "escort " + path[-1]
    if isExcessiveMission(missionKey, 1):
        return
    increaseMissionsCounter(missionKey)
    
    pathDiff = calcPathDifficulty(path)

    shipTypes = ( "tarsus", "tarsus", "galaxy", "orion")
    if pathDiff > 3:
        shipTypes = ( "galaxy", "orion")
    escorteeShipType = shipTypes[ vsrandom.randrange( 0, len( shipTypes)) ]
    
    enemyLockOnEscorteeChance = .9
    if escorteeShipType == "tarsus":
        enemyLockOnEscorteeChance = .5
    elif escorteeShipType == "galaxy":
        enemyLockOnEscorteeChance = .7

    creds = int( randomCredModifier() + ( len( path) + pathDiff)*vsrandom.randrange(400,600) + calcDeadEndBonus(path[0],path[-1]))

    guildRewardMod=1.0
    bcreds = creds
    addstr = ""
    if vsrandom.random() < min( .9, creds/9000.0):
        if creds*1.2 < 10000:
            creds*=1.2
        elif creds*1.1 < 15000:
            creds*=1.1
        addstr += "#G#Escort#\n"
        #guildRewardMod = 1.2
    elif use_missioncomputer:
        addstr += "#C#Escort#\n"

    creds*=getPriceModifier(False)

    if len(path)==1:
        mistype = 'IN-SYSTEM ESCORT'
    else:
        mistype = 'ESCORT'

    print "PODXXX " + addstr + mistype + " creds [" + str(bcreds) + "/" + str( creds) + "] ship [" + escorteeShipType + "] pathDiff [" + str( pathDiff) + "] path " + str( path) + " " + destBaseName

    randCompany = GetRandomCompanyName()
    escortb = GetRandomEscortPodBrief()
    composedBrief = escortb.replace('$CL', randCompany)
    composedBrief = composedBrief.replace('$DB', destBaseName + destBaseType)
    composedBrief = composedBrief.replace('$DS', processSystem( path[-1]))
    composedBrief = composedBrief.replace('$PY', str( int( creds)))
    composedBrief = composedBrief.replace('$ET', escorteeShipType.capitalize())
    
    writedescription( "\n" + composedBrief )
    writemissionsavegame( addstr + mission_script_template % dict(
        module = 'escort_pod',
        constructor = 'escort_pod',
        args = ( creds, path, destBaseName, escorteeShipType, enemyLockOnEscorteeChance, guildRewardMod)))

    briefDest = destBaseName + destBaseType + " in " + processSystem( path[-1])

    writemissionname("Escort/Escort Merchant %s to %s. Autopayment %i credits. Extra payment per every outlaw ship destroyed enroute." % ( escorteeShipType.capitalize(), briefDest, creds), [path[-1]], isFixerString( addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )

    
systemsWithoutBases = { 
        'Gemini/Metsor':  [ ('Gemini/Metsor', 'Gemini/Newcastle'), ('Gemini/Metsor', 'Gemini/XXN-1927')],
        'Gemini/17-ar':   [ ('Gemini/17-ar', 'Gemini/New_Caledonia')],
        'Gemini/44-p-im': [ ('Gemini/44-p-im', 'Gemini/New_Constantinople')],
        'Gemini/119ce':   [ ('Gemini/119ce', 'Gemini/Junction'), ('Gemini/119ce', 'Gemini/XXN-1927')],
        'Gemini/CMF-A':   [ ('Gemini/CMF-A', 'Gemini/Tingerhoff'), ('Gemini/CMF-A', 'Gemini/Nitir')],
        'Gemini/Crab-12': [ ('Gemini/Crab-12', 'Gemini/New_Caledonia')],
        'Gemini/Famine':  [ ('Gemini/Famine', 'Gemini/Capella', 'Gemini/Nexus')],
        'Gemini/Freyja':  [ ('Gemini/Freyja', 'Gemini/Regallis'), ('Gemini/Freyja', 'Gemini/Pyrenees')],
        'Gemini/J900':    [ ('Gemini/J900', 'Gemini/Junction')],
        'Gemini/Xytani':  [ ('Gemini/Xytani','Gemini/Rygannon'), ('Gemini/Xytani', 'Gemini/Palan')],
        'Gemini/War':     [ ('Gemini/War', 'Gemini/Troy')],
        'Gemini/41-gs':   [ ('Gemini/41-gs', 'Gemini/Surtur')],
        'Gemini/CM-N1054':[ ('Gemini/CM-N1054', 'Gemini/Pyrenees')],
        'Gemini/Death':   [ ('Gemini/Death', 'Gemini/Famine', 'Gemini/Capella', 'Gemini/Nexus' )],
        'Gemini/Telar':   [ ('Gemini/Telar', 'Gemini/Valhalla' )],
        'Gemini/Capella': [ ('Gemini/Capella', 'Gemini/Nexus' )],
        'Gemini/Sherwood':[ ('Gemini/Sherwood', 'Gemini/Regallis'), ('Gemini/Sherwood', 'Gemini/New_Caledonia' )],
        'Gemini/Pestilence': [ ('Gemini/Pestilence', 'Gemini/War', 'Gemini/Troy' )],
        'Gemini/Penders_Star': [ ('Gemini/Penders_Star', 'Gemini/Junction'), ('Gemini/Penders_Star', 'Gemini/Troy')],
        'Gemini/Blockade_Point_Alpha': [ ('Gemini/Blockade_Point_Alpha', 'Gemini/Ragnarok')],
        'Gemini/Blockade_Point_Charlie': [ ('Gemini/Blockade_Point_Charlie', 'Gemini/Surtur')],
        'Gemini/Blockade_Point_Tango': [ ('Gemini/Blockade_Point_Tango', 'Gemini/Nitir')]}
        
# longer distances between NPs so search the ejected pilot only around NPs
looseSystemsList = [ "J900", "Blockade_Point_Tango", "Blockade_Point_Charlie", "Troy", "Penders_Star", "Rikel", "Junction", "Tingerhoff",
                     "XXN-1927", "New_Constantinople", "New_Detroit", "Capella", "War", "Xytani", "Perry", "Valhalla", "Telar", "Ragnarok",
                     "Hinds_Variable_N", "Pollux", "Sherwood", "New_Caledonia", "Crab-12", "Regallis", "Pyrenees", "Hyades", "44-p-im" ]

tightSystemsList = ["119ce", "Oxford", "Saxtogue", "ND-57", "Manchester", "Raxis", "Nitir", "Auriga", "Newcastle", "Metsor", "Surtur", "CMF-A", "Rygannon",
                    "Shangri-La", "Padre", "Castor", "Nexus", "Aldebran", "DN-N1912", "Freyja", "17-ar", "Prasepe" ]
     
     
def generateRescueMission( path, rescueFac, enemyFac):
    #rescueFac = rescuelist[0]
    #enemyFac = rescuelist[2]

    if (isNotWorthy(rescueFac)):
        return
        
    missionKey = "rescue " + str(path[-1])
    if isExcessiveMission(missionKey, 1):
      return
    increaseMissionsCounter(missionKey)

    numships = vsrandom.randrange(2,4)
    attackStrength = 1000
    if enemyFac == "kilrathi":
        numships = vsrandom.randrange(1,3)
        attackStrength = 2000
    
    sysNavpoints = []
    try:
        sysNavpoints = list( systemsNPDict[path[-1]])
        sysNavpoints += systemsBaseDict[path[-1]]
    except:
        pass
        
    if not len( sysNavpoints):
        return
    vsrandom.shuffle( sysNavpoints)
    if len( sysNavpoints) >= 2 and (str(path[-1])[7:] in tightSystemsList) and vsrandom.random() > .66:
        betweenNavpoints = sysNavpoints[0:2]
        searchOption = "somewhere BETWEEN " + betweenNavpoints[0] + " and " + betweenNavpoints[1]
    else:
        betweenNavpoints = sysNavpoints[0:1]
        searchOption = "somewhere AROUND " + betweenNavpoints[0] + ", beacon guidance available"

    try:
        dsl = systemsWithoutBases[ path[-1]]
        pilotDeliveryPath = dsl[ vsrandom.randrange( 0, len( dsl)) ]
    except:
        pilotDeliveryPath = []
    
    creds = int( randomCredModifier() + vsrandom.randrange(1000,1500)*len( pilotDeliveryPath) + attackStrength*2 + 1000 + vsrandom.randrange(700,900)*getSystemDifficulty(path[-1]) + vsrandom.randrange(400,600)*calcPathDifficulty(path) + calcDeadEndBonus(path[0],path[-1]) )
    
    bcreds = creds
    addstr = ""
    if ( rescueFac == "merchant" and vsrandom.random() < min( .9, creds/10000.0) ):
        if creds*1.2 < 7500:
            creds *= 1.2
        elif creds*1.1 < 15000:
            creds *= 1.1
        addstr+="#G#Rescue#\n"
    elif use_missioncomputer:
        addstr+="#C#Rescue#\n"
        
    creds*=getPriceModifier(False)

    if len(path)==1:
        mistype = 'IN-SYSTEM RESCUE'
    else:
        mistype = 'RESCUE'
    
    print "PODXXX " + addstr + " [" + rescueFac + "] from [" + enemyFac + "] numships [" + str(numships) + "] creds [" + str(bcreds) + "/" + str(creds) + "] path " + str(path) + ", NP: " + str( betweenNavpoints) + ", pilotDeliveryPath: " + str( pilotDeliveryPath)

    randCompany = GetRandomCompanyName()
    rescueb = GetRandomRescueBrief()
    composedBrief = rescueb.replace('$CL',randCompany)
    composedBrief = composedBrief.replace('$MT',rescueFac.capitalize())
    composedBrief = composedBrief.replace('$AT',str(int(numships)))
    composedBrief = composedBrief.replace('$AN',enemyFac.capitalize())
    composedBrief = composedBrief.replace('$DS',processSystem(path[-1]))
    composedBrief = composedBrief.replace('$PY',str(int(creds)))
    composedBrief = composedBrief.replace('$DI', searchOption)
    
    writedescription( "\n" + composedBrief)
    writemissionsavegame (addstr+mission_script_template % dict(
        module='rescue',
        constructor='rescue',
        args=( creds, 0, rescueFac, numships, enemyFac, '', path, '', betweenNavpoints, pilotDeliveryPath)))
        
    writemissionname( "Rescue/Rescue %s pilot from %s in %s, %s. Autopayment %i credits."%(rescueFac.capitalize(),enemyFac.capitalize(),processSystem(path[-1]), searchOption, creds), path, 0)
    writemissionvars( { 'MISSION_TYPE' : mistype } )


fighters = {
    "retro" :    [  ("talon.retrobounty", 900)  ],
    "pirates" :  [  ("talon.piratesbounty", 800), ("talon.pirion", 1000)  ],
    "kilrathi" : [  ("dralthi", 2000), ("dralthi.tachyon", 2500), ("dralthi.ion", 2500), ("dralthi.ion", 2500),
                    ("gothri", 4000), ("gothri.particle", 4000), ("gothri.tachyon", 4000), ("gothri.plasma", 5000)  ],
    "criminal" : [  ("demon", 1500), ("demon.tachyon", 2000), ("demon.tachyon", 2000), ("demon.ion", 2000), ("demon.ion", 2000),
                    ("orion.hunter", 3000), ("orion.ionturret", 4000), ("orion.plasma", 3500),
                    ("centurion", 4000), ("centurion.tachpar", 4500), ("centurion.ion", 4500), ("centurion.plasma", 5000)  ]
}

lightFighters = {
    "retro" :    [  ("talon", 600), ("talon.retro2", 700)  ],
    "pirates" :  [  ("talon", 800), ("talon.pirlaser", 700), ("talon.pirmeson", 600)  ],
    "kilrathi" : [  ("dralthi", 2000)  ],
    "criminal" : [  ("demon", 1500), ("demon.laser", 1500)  ]
}

def getRandomFighter(faction, shipMatrix):
    ships = shipMatrix.get(faction, [])
    ship = ships[ vsrandom.randrange(0, len(ships)) ]
    #print "PODXX getRandomFighter [" + faction + "]: " + str(ship) + " from: " + str(ships)
    return ship
    

BountySplitPaths = [ ['Gemini/Junction', 'Gemini/XXN-1927', 'Gemini/119ce', 'Gemini/New_Constantinople'],
    ['Gemini/XXN-1927', 'Gemini/Junction', 'Gemini/119ce', 'Gemini/New_Constantinople'],
    ['Gemini/New_Constantinople', 'Gemini/Rikel', 'Gemini/44-p-im', 'Gemini/New_Detroit'],
    ['Gemini/Rikel', 'Gemini/New_Constantinople', 'Gemini/44-p-im', 'Gemini/New_Detroit'],
    ['Gemini/Regallis', 'Gemini/Pyrenees', 'Gemini/Freyja', 'Gemini/Troy'],
    ['Gemini/Pyrenees', 'Gemini/Regallis', 'Gemini/Freyja', 'Gemini/Troy'],
    ['Gemini/Nitir', 'Gemini/Tingerhoff', 'Gemini/CMF-A', 'Gemini/Perry'],
    ['Gemini/Tingerhoff', 'Gemini/Nitir', 'Gemini/CMF-A', 'Gemini/Perry'],
    ['Gemini/New_Detroit', 'Gemini/44-p-im', 'Gemini/Rikel', 'Gemini/New_Constantinople'],
    ['Gemini/Perry', 'Gemini/Rikel', 'Gemini/Midgard', 'Gemini/New_Detroit'] ]

    
KilrathiInfestedSystemList = ["KM-252", "Capella", "Nexus", "Tingerhoff", "Palan", "Xytani", "Rygannon", "Nitir", "Surtur", "Ragnarok", "CMF-A", "Hyades", "Lisacc", "41-gs", "Blockade_Point_Alpha", "Blockade_Point_Charlie", "Blockade_Point_Tango"]

    
def generateBountyPodMission( path, enemyFaction):
    adjacentSystems = universe.getAdjacentSystemList( path[-1])
    if len( path) > 3 or len( adjacentSystems) < 2 or path[-1][7:] in ["Perry", "New_Detroit", "New_Constantinople"]:
        return
    missionKey = "bounty " + str( path[-1])
    if isExcessiveMission( missionKey, 1):
        return
    increaseMissionsCounter( missionKey)

    if (enemyFaction == "retro" and vsrandom.random() < .3) or (enemyFaction == "pirates" and vsrandom.random() < .15) or (enemyFaction == "kilrathi" and path[-1][7:] not in KilrathiInfestedSystemList and vsrandom.random() < .4):
        enemyFaction = "criminal"

    ### Ships
    enemyShipTypesList = []
    if path[-1][7:] in ["119ce", "Nexus", "Sherwood", "Telar", "Capella", "Crab-12", "Regallis", "17-ar", "Famine", "J900"] and enemyFaction in ["pirates", "criminal"] and vsrandom.random() < .2:
        enemyShipTypesList.append( "galaxy.pirpar")
        shipValue = 2000
        escortChance = 1
    else:
        rf = getRandomFighter( enemyFaction, fighters)
        enemyShipTypesList.append( rf[0])
        shipValue = rf[1]
        escortChance = .5
        
    shipTypeFormatted = str( formatShip( enemyShipTypesList[0]))
    commaInd = shipTypeFormatted.find( ".")
    if commaInd >= 0:
        shipTypeFormatted = shipTypeFormatted[0:commaInd]
        
    escortValue = 0
    if vsrandom.random() < escortChance:
        et = getRandomFighter( enemyFaction, lightFighters)
        enemyShipTypesList.append( et[0])
        escortValue += et[1]
        if getSystemDifficulty( path[-1]) > 2 and (enemyFaction == "retro" or enemyFaction == "pirates") and vsrandom.random() > .5:
            et = getRandomFighter(enemyFaction, lightFighters)
            enemyShipTypesList.append( et[0])
            escortValue += et[1]
    
    if enemyShipTypesList[0] == "galaxy.pirpar":   # Demon as escort is great but we don't want hunters inside the Galaxy
        enemyFaction = "pirates"
        
    ### Systems
    if len( path) == 3:
        for nsp in BountySplitPaths:
            if path[0] == nsp[0] and path[2] == nsp[1]:
                print "PODXXdynmis splitPath: " + str( path)
                if vsrandom.random() > .5:
                    path[1] = nsp[2]
                else:
                    path[1] = nsp[3]
                print "PODXXdynmis splitPath changed to: " + str( path)
                break
        firstAdjSystem = path[1]
    else:
        firstAdjSystem = adjacentSystems[ vsrandom.randrange( 0, len( adjacentSystems))]
        
    systemNamesList = [path[-1]]
    systemNamesList.append( firstAdjSystem)
    adjacentSystems.remove( firstAdjSystem)
    systemNamesList.append( adjacentSystems[ vsrandom.randrange( 0, len( adjacentSystems))])
        
    npValue = 0
    for ns in systemNamesList:
        numNavPoints = faction_ships.numPatrolPoints[ns]
        q = .75
        if npValue > 0:
            q = .5
        npValue += q * numNavPoints * vsrandom.randrange( 300, 400) * getSystemDifficulty( ns)
     
    ### Creds
    pathLengthBonus = 250 + 500 * (len( path) - 1)
    creds = int( randomCredModifier() + shipValue + escortValue + npValue + pathLengthBonus)

    bcreds = creds
    addstr = ""
    if vsrandom.random() < min( .9, creds/9000.0):
        if (creds*1.3) <= 5000:
          creds *= 1.3
        elif (creds*1.25) <= 7500:
          creds *= 1.25
        elif (creds*1.2) <= 10000:
          creds *= 1.2
        elif (creds*1.15) <= 12500:
          creds *= 1.15
        elif (creds*1.1) <= 15000:
          creds *= 1.1
        addstr += "#G#Bounty#\n"
    elif use_missioncomputer:
        addstr += "#C#Bounty#\n"

    creds *= getPriceModifier( False)

    print "PODXXX " + addstr + " [" + enemyFaction + "] ships: " + str( enemyShipTypesList) + "] creds [" + str( bcreds) + "/" + str( creds) + "] systems: " + str( systemNamesList)

    addInfo = "The ship in question "
    if len( enemyShipTypesList) > 1:
        addInfo += "is thought to have an escort and "
    addInfo += "can travel to " + processSystem( systemNamesList[1]) + " or " + processSystem( systemNamesList[2]) + " systems."

    writemissionsavegame( addstr + mission_script_template % dict(
        module = 'bounty_pod',
        constructor = 'bounty_pod',
        args = (creds, enemyFaction, enemyShipTypesList, systemNamesList)))
    
    targetstr = shipTypeFormatted
    if shipTypeFormatted == "Talon":     # to distinguish retro/pirates Talons
      targetstr = enemyFaction.capitalize() + " " + targetstr
      
    randCompany = GetRandomCompanyName()
    bountyb = GetRandomBountyBrief()
    if enemyShipTypesList[0] == "galaxy.pirpar":
        bountyb = "Militia seeks a skilled pilot to track and eliminate the smuggler Galaxy operating around the $DS system. $PY credits tendered by automatic transfer. $AI"
    composedBrief = bountyb.replace( '$CL', randCompany)
    composedBrief = composedBrief.replace( '$MT', targetstr)
    composedBrief = composedBrief.replace( '$DS', processSystem( path[-1]))
    composedBrief = composedBrief.replace( '$PY', str( int( creds)))
    composedBrief = composedBrief.replace( '$AI', addInfo)
    #if len( path) == 1:
    #    mistype = 'IN-SYSTEM BOUNTY'
    #else:
    mistype = 'BOUNTY'
    writedescription( "\n" + composedBrief)

    writemissionname ( "Bounty/Find and eliminate %s %s in %s system. %s Autopayment %i credits." % (enemyFaction.capitalize(), shipTypeFormatted, processSystem( path[-1]), addInfo, creds), path, isFixerString( addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )

    
def generateDefendPodMission( path, attackfac):
    defendfac = "merchant"    #PODXX decided to hardcode this b/c it kinda strange to see a non-merchant Drayman    
    
    attackfg = fg_util.RandomFlightgroup( attackfac)
    attacktyp = fg_util.RandomShipIn( attackfg, attackfac)                    
    
    attackStrength = 0
    quantity = 0
    if str(attacktyp) in ["talon","gladius"]:
      if attackfac == "retro":
        attackStrength = 850
        quantity = vsrandom.randrange(2,4)
      else:
        attackStrength = 1000
        quantity = vsrandom.randrange(2,4)
    elif str(attacktyp) in ["dralthi","demon","stiletto"]:
      attackStrength = 2000
      quantity = vsrandom.randrange(1,4)
    elif str(attacktyp) in ["gothri","centurion","orion"]:
      attackStrength = 3000
      quantity = vsrandom.randrange(1,3)
    else:
      return

    missionKey = "defend " + str(path[-1])
    if isExcessiveMission(missionKey, 1):
      return
    increaseMissionsCounter(missionKey)

    creds = int( randomCredModifier() + 2000 + attackStrength*quantity + 800*calcPathDifficulty(path) + calcDeadEndBonus(path[0],path[-1]) )
    
    bcreds = creds
    addstr = ""
    if vsrandom.random() < min( .9, creds/6000.0):
        creds*=1.3
        addstr+="#G#Defend#\n"
    elif use_missioncomputer:
        addstr+="#C#Defend#\n"

    creds*=getPriceModifier(False)

    print "PODXXX " + addstr + " [" + defendfac + "] from [" + attackfac + "-" + str(attacktyp) + "] quantity [" + str(quantity) + "] creds [" + str(bcreds) + "/" + str(creds) + "] path " + str(path)

    writemissionsavegame (addstr+mission_script_template % dict(
        module='defend',
        constructor='defend',
        args=(attackfac,0,quantity,2000.0,5000.0,creds,True,False,defendfac,path,'',attackfg,attacktyp,'',0,universe.getRandomGreeting("common"))))
    iscapitol=""
    if True:
        iscapitol="capital "
    randCompany = GetRandomCompanyName()
    defendb = GetRandomDefendBrief()
    composedBrief = defendb.replace('$CL',randCompany)
    composedBrief = composedBrief.replace('$DT',iscapitol)
    composedBrief = composedBrief.replace('$DS',processSystem(path[-1]))
    composedBrief = composedBrief.replace('$PY',str(int(creds)))
    composedBrief = composedBrief.replace('$MT',attackfac.capitalize())
    if len(path)==1:
        mistype = 'IN-SYSTEM DEFEND'
    else:
        mistype = 'DEFEND'
    writedescription( "\n" + composedBrief)
    writemissionname("Defend/Defend %s Drayman from %s in %s. Autopayment %i credits."%(defendfac.capitalize(), attackfac.capitalize(), processSystem(path[-1]), creds),path,isFixerString(addstr))
    writemissionvars( { 'MISSION_TYPE' : mistype } )


def generateWingmanMission(fg, faction):
    numships=vsrandom.randrange(1,4)
    creds=10000+15000*numships
    writemissionsavegame ('#\n' + mission_script_template % dict(
        module='wingman',
        constructor='wingman',
        args=(creds,faction,numships,0)))
    s="A pilot"
    EorA="a"
    are="is"
    if numships > 1:
        s=str(numships)+" pilots"
        EorA="e"
        are="are"
    isFixer=vsrandom.random()
    if isFixer<fixerpct and fixer_has_wingman:
        creds*=2
        addstr+="#F#bases/fixers/merchant.spr#Talk to the Merchant#Thank you. I entrust you will make the delivery successfully.#\n"
    elif isFixer<guildpct:
        creds*=1.5
        addstr+="#G#Wingman#\n"
    elif use_missioncomputer:
        addstr+="#C#Wingman#\n"
    writedescription(s+" in the %s faction %s willing to help you out and fight with you as long as you pay %d credits."%(faction, are, creds))
    writemissionname("Wingmen/Hire_%d_%s_Wingm%sn"%(numships,faction,EorA),[VS.getSystemFile()],0)
    writemissionvars( { 'MISSION_TYPE' : 'CONTRACT WINGMAN' } )
    
    
def GetFactionToDefend(thisfaction, fac, cursys):
    m = fg_util.FGsInSystem ("merchant",cursys)
    nummerchant=len(m)
    m+=fg_util.FGsInSystem (thisfaction,cursys)
    numthisfac=len(m)
    m+=fg_util.FGsInSystem (fac,cursys)
    return (m,nummerchant,numthisfac)

    
def setFactionRelation(faction, newrel):
    rel = VS.GetRelation(faction,"privateer")
    while (rel - newrel) > 0.01 or (rel - newrel) < -0.01:
        #print "PODXX rel: " + str(rel) + ", newrel: " + str(newrel)
        VS.AdjustRelation(faction,"privateer",newrel-rel,1.0)
        rel=VS.GetRelation(faction,"privateer")


def isEqualLists( lst1, lst2):
    if len( lst1) <> len( lst2):
        return False
    for i in range ( len( lst1)):
        if lst1[i] <> lst2[i]:
            return False
    return True
    
        
def getIndexOf( lst1, lst2):
    if lst1[0] not in lst2:
        return -1
    ii = lst2.index( lst1[0])
    subLst2 = lst2[ii:ii + len( lst1)]
    #print "PODXXsubp ii: " + str( ii) + ", ii+len( lst1): " + str( ii+len( lst1)) + ", subLst2: " + str( subLst2)
    if isEqualLists( subLst2, lst1):
        return ii
    else:
        return -1         
        

badSubpathsAndReplacements = [ ['Gemini/Junction', 'Gemini/119ce', 'Gemini/XXN-1927'], ['Gemini/Junction', 'Gemini/New_Constantinople', 'Gemini/XXN-1927'],
    ['Gemini/XXN-1927', 'Gemini/119ce', 'Gemini/Junction'], ['Gemini/XXN-1927', 'Gemini/New_Constantinople', 'Gemini/Junction'],
    ['Gemini/New_Constantinople', 'Gemini/44-p-im', 'Gemini/Rikel'], ['Gemini/New_Constantinople', 'Gemini/New_Detroit', 'Gemini/Rikel'],
    ['Gemini/Rikel', 'Gemini/44-p-im', 'Gemini/New_Constantinople'], ['Gemini/Rikel', 'Gemini/New_Detroit', 'Gemini/New_Constantinople'],
    ['Gemini/Regallis', 'Gemini/Freyja', 'Gemini/Pyrenees'], ['Gemini/Regallis', 'Gemini/Troy', 'Gemini/Pyrenees'],
    ['Gemini/Pyrenees', 'Gemini/Freyja', 'Gemini/Regallis'], ['Gemini/Pyrenees', 'Gemini/Troy', 'Gemini/Regallis'],
    ['Gemini/Nitir', 'Gemini/CMF-A', 'Gemini/Tingerhoff'], ['Gemini/Nitir', 'Gemini/Perry', 'Gemini/Tingerhoff'],
    ['Gemini/Tingerhoff', 'Gemini/CMF-A', 'Gemini/Nitir'], ['Gemini/Tingerhoff', 'Gemini/Perry', 'Gemini/Nitir'],
    ['Gemini/Junction', 'Gemini/Nexus', 'Gemini/Tingerhoff', 'Gemini/Perry'], ['Gemini/Junction', 'Gemini/New_Constantinople', 'Gemini/New_Detroit', 'Gemini/Perry'],
    ['Gemini/Perry', 'Gemini/Tingerhoff', 'Gemini/Nexus', 'Gemini/Junction'], ['Gemini/Perry', 'Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/Junction'],
    ['Gemini/New_Detroit', 'Gemini/Rikel', 'Gemini/44-p-im'], ['Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/44-p-im'],
    ['Gemini/Nexus', 'Gemini/Tingerhoff', 'Gemini/Perry', 'Gemini/Midgard', 'Gemini/Rikel'], ['Gemini/Nexus', 'Gemini/Junction', 'Gemini/New_Constantinople', 'Gemini/New_Detroit', 'Gemini/Rikel'],
    ['Gemini/Rikel', 'Gemini/New_Detroit', 'Gemini/Perry', 'Gemini/Tingerhoff', 'Gemini/Nexus'], ['Gemini/Rikel', 'Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/Junction', 'Gemini/Nexus'],
    ['Gemini/Perry', 'Gemini/Midgard', 'Gemini/Rikel', 'Gemini/44-p-im'], ['Gemini/Perry', 'Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/44-p-im'],
    ['Gemini/Perry', 'Gemini/Midgard', 'Gemini/Rikel'], ['Gemini/Perry', 'Gemini/New_Detroit', 'Gemini/Rikel'],
    ['Gemini/Nexus', 'Gemini/Capella', 'Gemini/Sherwood', 'Gemini/Regallis'], ['Gemini/Nexus', 'Gemini/Junction', 'Gemini/Penders_Star', 'Gemini/Troy', 'Gemini/Regallis'],
    ['Gemini/Regallis', 'Gemini/Sherwood', 'Gemini/Capella', 'Gemini/Nexus'], ['Gemini/Regallis', 'Gemini/Troy', 'Gemini/Penders_Star', 'Gemini/Junction', 'Gemini/Nexus'],
    ['Gemini/Nexus', 'Gemini/Tingerhoff', 'Gemini/Perry', 'Gemini/Newcastle'], ['Gemini/Nexus', 'Gemini/Junction', 'Gemini/New_Constantinople', 'Gemini/Newcastle'],
    ['Gemini/Nexus', 'Gemini/Tingerhoff', 'Gemini/Perry', 'Gemini/New_Detroit'], ['Gemini/Nexus', 'Gemini/Junction', 'Gemini/New_Constantinople', 'Gemini/New_Detroit'],
    ['Gemini/New_Detroit', 'Gemini/Perry', 'Gemini/Tingerhoff', 'Gemini/Nexus'], ['Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/Junction', 'Gemini/Nexus'],
    ['Gemini/Newcastle', 'Gemini/Perry', 'Gemini/Tingerhoff', 'Gemini/Nexus'], ['Gemini/Newcastle', 'Gemini/New_Constantinople', 'Gemini/Junction', 'Gemini/Nexus'],
    # 50% chance from here, i > 41
    ['Gemini/Oxford', 'Gemini/XXN-1927', 'Gemini/New_Detroit'], ['Gemini/Oxford', 'Gemini/Saxtogue', 'Gemini/New_Detroit'],
    ['Gemini/XXN-1927', 'Gemini/New_Detroit', 'Gemini/Saxtogue'], ['Gemini/XXN-1927', 'Gemini/Oxford', 'Gemini/Saxtogue'],
    ['Gemini/Saxtogue', 'Gemini/New_Detroit', 'Gemini/XXN-1927'], ['Gemini/Saxtogue', 'Gemini/Oxford', 'Gemini/XXN-1927'],
    ['Gemini/New_Detroit', 'Gemini/Perry', 'Gemini/Newcastle'], ['Gemini/New_Detroit', 'Gemini/New_Constantinople', 'Gemini/Newcastle'],
    ['Gemini/New_Detroit', 'Gemini/Saxtogue', 'Gemini/Oxford'], ['Gemini/New_Detroit', 'Gemini/XXN-1927', 'Gemini/Oxford'],
    ['Gemini/Newcastle', 'Gemini/Perry', 'Gemini/New_Detroit'], ['Gemini/Newcastle', 'Gemini/New_Constantinople', 'Gemini/New_Detroit'],
    ['Gemini/Newcastle', 'Gemini/New_Constantinople', 'Gemini/XXN-1927'], ['Gemini/Newcastle', 'Gemini/Metsor', 'Gemini/XXN-1927'],
    ['Gemini/XXN-1927', 'Gemini/New_Constantinople', 'Gemini/Newcastle'], ['Gemini/XXN-1927', 'Gemini/Metsor', 'Gemini/Newcastle'],
    ['Gemini/Perry', 'Gemini/Newcastle', 'Gemini/New_Constantinople'], ['Gemini/Perry', 'Gemini/New_Detroit', 'Gemini/New_Constantinople'],
    ['Gemini/New_Constantinople', 'Gemini/Newcastle', 'Gemini/Perry'], ['Gemini/New_Constantinople', 'Gemini/New_Detroit', 'Gemini/Perry'],
    ['Gemini/New_Caledonia', 'Gemini/Sherwood', 'Gemini/Capella'], ['Gemini/New_Caledonia', 'Gemini/Crab-12', 'Gemini/Capella'],
    ['Gemini/Capella', 'Gemini/Sherwood', 'Gemini/New_Caledonia'], ['Gemini/Capella', 'Gemini/Crab-12', 'Gemini/New_Caledonia'] ]


def replaceBadSubpaths( path):
    i = 0
    while i < len( badSubpathsAndReplacements):
        nextSubpath = badSubpathsAndReplacements[i]
        j = getIndexOf( nextSubpath, path)
        if j >= 0:
            #print "PODXXsubp next subPath: " + str( nextSubpath) + ", index: " + str( j)
            if i > 41 and vsrandom.random() > .5:
                return path
            newPath = path[:j] + badSubpathsAndReplacements[i+1] + path[ j + len( badSubpathsAndReplacements[i]):]
            if len( newPath) > 5:
                #print "PODXXsubp newPath too long: " + str( newPath)
                return path
            #print "PODXXsubp newPath: " + str( newPath)
            return newPath
        i += 2
    
    return path
    

def getEnemiesListForSystem( systemName):
    if systemName[:7].lower() == "gemini/":
        systemName = systemName[7:]

    if systemName in ["Hinds_Variable_N", "Padre", "Auriga", "Shangri_La", "Aldebran", "DN-N1912", "Saxtogue", "ND-57", "Raxis", "Varnus", "Oxford", "New_Detroit"]:
        return ["pirates", "pirates", "retro", "retro", "retro", "kilrathi"]

    if systemName in ["Perry", "Palan", "Tingerhoff", "Rygannon", "Xytani", "Ragnarok", "Nitir", "Surtur", "CMF-A",
                      "Blockade_Point_Alpha", "Blockade_Point_Charlie", "Hyades", "Blockade_Point_Tango", "Lisacc", "41-gs"]:
        return ["pirates", "pirates", "retro", "kilrathi", "kilrathi"]
    
#        "New_Constantinople","Troy","Manchester","Newcastle","Nexus","Rikel","Pyrenees","Regallis","Midgard",
#        "Junction","XXN-1927","Metsor","Penders_Star","44-p-im","119ce","Pentonville","Castor",
#        "Freyja","J900","Crab-12","Sherwood","New_Caledonia","Prasepe","Pollux","CM-N1054",
#        "Capella","KM-252","Telar","17-ar","Death","Pestilence","War","Famine","Valhalla",
    return ["pirates", "pirates", "pirates", "retro", "retro", "kilrathi"]
    
    
def getRandomEnemyFaction( systemName):
    enemies = getEnemiesListForSystem( systemName)
    return enemies[ vsrandom.randrange( 0, len( enemies))]

    
def contractMissionsFor( minsysaway, maxsysaway):
    # makes it very hard to become friendly with Kilrathi
    setFactionRelation( 'kilrathi', -2)
    
    resetPerSystemMissionsCounters()
    curSystem = VS.getSystemFile()
    #cursysFaction = VS.GetGalaxyFaction( curSystem)
    #if curSystem in ['Gemini/Hyades']:
    #    cursysFaction = "confed"           # strange thing, otherwise Hyades always 'belongs' to kilrathi...
    
    ### Scout local
    for i in range( min( 4, len( universe.getNonBaseSignificants()))):
        generateScoutLocalMission( [curSystem], getRandomEnemyFaction( curSystem))
    
    for numJumps in range( minsysaway, maxsysaway + 1):
        nextRangePathsList = getSystemsKAwayNoFaction( curSystem, numJumps)
        vsrandom.shuffle( nextRangePathsList)

        for nextPath in nextRangePathsList:
            print "PODXXsubp nextPath: " + str( nextPath)
            nextPath = replaceBadSubpaths( nextPath)
            nextDestSystem = nextPath[-1]
            if nextDestSystem in ["Gemini/Eden", "Gemini/Beta", "Gemini/Delta", "Gemini/Gamma", "Gemini/Delta_Prime", "Gemini/Pentonville"]:
                continue
            sysDiff = getSystemDifficulty( nextDestSystem)
            
            ### Bounty
            if vsrandom.random() < 1.0/ max( 1, numJumps - .5):
                generateBountyPodMission( nextPath, getRandomEnemyFaction( nextDestSystem))

            ### Rescue
            if numJumps <= 1 and vsrandom.random() < min( .66, .05 + sysDiff*0.5):
                rescFacs = ["merchant", "merchant", "confed", "militia"]
                rescueFaction = rescFacs[ vsrandom.randrange( 0, len( rescFacs))]
                generateRescueMission( nextPath, rescueFaction, getRandomEnemyFaction( nextDestSystem))

            ### Defend
            if numJumps <= 1 and vsrandom.random() < sysDiff:
                generateDefendPodMission( nextPath, getRandomEnemyFaction( nextDestSystem))

            ### Patrol
            if numJumps <= 2 and vsrandom.random() < 1.0/ max( 1, numJumps + .2):
                generatePatrolMission( nextPath, numPatrolPoints( nextDestSystem, 0), getRandomEnemyFaction( nextDestSystem))
            
            ### Attack
            patrolOnlySystems = ["Gemini/Perry", "Gemini/New_Constantinople", "Gemini/New_Detroit"] 
            nxtEnemyFac = getRandomEnemyFaction( nextDestSystem)
            if numJumps <= 3 and nextDestSystem not in patrolOnlySystems and vsrandom.random() < 1.0/ max( 1, numJumps + .6):
                if nxtEnemyFac == "kilrathi" and nextDestSystem[7:] not in KilrathiInfestedSystemList:
                    if vsrandom.random() > .5:
                        nxtEnemyFac = "retro"
                    else:
                        nxtEnemyFac = "pirates"
                generateAttackMission( nextPath, nxtEnemyFac)
                
            ### Escort
            if isHabitable( nextDestSystem) and vsrandom.random() < 1.0/ max( 1.5, min( numJumps, 4)):
                generateEscortPodMission( nextPath)
                
            ### Cargo
            if isHabitable( nextDestSystem) and vsrandom.random() < 1.0/ max( 1.35, min( numJumps, 2.5)):
                generateCargoMission( nextPath)
                if vsrandom.random() < (.1 * numJumps + .05):
                    generateCargoMission( nextPath)
                    

def CreateMissions( minsys = 0, maxsys = 4):
    generate_dyn_universe.KeepUniverseGenerated()
    if VS.networked():
        # No generating stuff while networked.
        return
    #i=0
    global plr,basefac,baseship
    plrun=VS.getPlayer()
    plr=plrun.isPlayerStarship()
    eraseExtras()
    #i = VS.getUnitList()
    #while(i.notDone() and not i.current().isDocked(plrun)):
    #    i.advance()
    #if (i.notDone()):
    #    basefac=i.current().getFactionName()
    #if (basefac=='neutral'):
    #    basefac=VS.GetGalaxyFaction(VS.getSystemFile())
    #contractMissionsFor(basefac,baseship,minsys,maxsys)
    
    contractMissionsFor( minsys, maxsys)

#    import news
#    news.processNews(plr)
#    print "GOOG OGOO"
