#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MicroWar 2.0
see exact version with k_VERSION in mwarbasic.py

Main script, do start up and main loop

Build with :
    Python 2.5.4
    Pygame 1.9.1
    py2app 0.4.2

See Source.rtf for licence and usage
"""

# Import Python Modules
import os,random,datetime,time,sys
import webbrowser
from BeautifulSoup import *
from urllib2 import urlopen
import urllib
if '-profile' in sys.argv:
    import cProfile, pstats

# Import local modules
from configobj import *
import pygame
from pygame.locals import *

# Import source
from fgame import *
from mwarbasic import *
from screen import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

# Classes for our game objects
        
class FHighScores(object):
    def __init__(self):
        self.highScore=['4000', '3500', '2000', '1500', '1000', '800', '750', '700', '650', '600']
        self.highName=['william higinbotham', 'steve russell', 'ralph baer', 'nolan bushnell', 'tomohiro nishikado', 'lyle rains & ed logg', 'toru iwatani', 'eugene jarvis', 'shigeri miyamoto', 'ikegami tsushinki']
        self.highLevel=['1958', '1961', '1966', '1972', '1979', '1979', '1980', '1980', '1981', '1982']
        self.highID=[]
        
    def load(self):
        """ load score from file """
        try:
            config=ConfigObj(get_score_path())
            v=config.as_int('version')
            if v==kScoreVersion: # if pref file is current version
                self.version=v
                self.highScore=config['highscore']
                self.highName=config['highname']
                self.highLevel=config['highlevel']
                self.highID=config.as_intList('highid')
        except:
            print "error loading score file"
            print sys.exc_info()
            self.save()
        if len(self.highScore)<kHighScoreLen:
            for i in range(kHighScoreLen-len(self.highScore)):
                self.highScore.append('0')
        if len(self.highName)<kHighScoreLen:
            for i in range(kHighScoreLen-len(self.highName)):
                self.highName.append('-')
        if len(self.highLevel)<kHighScoreLen:
            for i in range(kHighScoreLen-len(self.highLevel)):
                self.highLevel.append('1984')
        if len(self.highID)<kHighScoreLen:
            for i in range(kHighScoreLen-len(self.highID)):
                self.highID.append(-1)
        
    def save(self):
        """ save score to file """
        config=ConfigObj()
        config.filename=get_score_path()
        config['version']=kScoreVersion
        config['highscore']=self.highScore
        config['highname']=self.highName
        config['highlevel']=self.highLevel
        config['highid']=self.highID
        config.write()

    def set_score(self,name,score,level):
        """ check if the score is a best score, if so add it and return TRUE """
        pos=0
        best=-1
        for s in self.highScore:    # check if this score could go into highScore list
            if score>int(s):
                self.highScore.insert(pos,"%s" % score)
                self.highName.insert(pos,name)
                self.highLevel.insert(pos,"%s" % (1984+level))
                self.highID.insert(pos,-1)
                best=pos
                break
            pos+=1
        if best>=0:     # reduce the list to the max length
            self.highScore=self.highScore[:kMaxHighScore]
            self.highName=self.highName[:kMaxHighScore]
            self.highLevel=self.highLevel[:kMaxHighScore]
            self.highID=self.highID[:kMaxHighScore]
            self.save()
        return best
        
    def search(self,id):
        for s in self.highID:
            if id==s:
                return True
        return False
    
class FPreferences(object):
    """ Preference class to store and handle game preferences
        Handle game settings and highScore list
        
        use ConfigObj for load and save to disk """
    
    def __init__(self):
        self.version=kPrefVersion
        self.fullScreen=True
        self.firstRun=True
        self.language=0         # english
        self.interface=0        # keyboard
        self.audioVolume=0.3
        self.musicVolume=0.2
        self.userName='no name'
        self.update=True
        self.lastUpdateYear=2008
        self.lastUpdateMonth=1
        self.lastUpdateDay=1
        self.maxFrameRate=90
        
    def load(self,scores):
        """ load preference from file """
        try:
            config=ConfigObj(get_pref_path())
            v=config.as_int('version')
            if v==kPrefVersion: # if pref file is current version
                self.version=v
                self.fullScreen=config.as_bool('fullscreen')
                self.firstRun=config.as_bool('firstrun')
                self.interface=config.as_int('interface')
                self.language=config.as_int('language')
                self.audioVolume=config.as_float('audiovolume')
                self.musicVolume=config.as_float('musicvolume')
                self.userName=config['username']
                self.update=config.as_bool('update')
                self.lastUpdateYear=config.as_int('year')
                self.lastUpdateMonth=config.as_int('month')
                self.lastUpdateDay=config.as_int('day')
                self.maxFrameRate=config.as_int('fps')
            elif v==4:  # handle loading an old (version 4) pref file
                self.version=v
                self.fullScreen=config.as_bool('fullscreen')
                self.firstRun=config.as_bool('firstrun')
                self.interface=config.as_int('interface')
                self.language=config.as_int('language')
                self.audioVolume=config.as_float('audiovolume')
                self.musicVolume=config.as_float('musicvolume')
                self.userName=config['username']
                scores.highScore=config['highscore']
                scores.highName=config['highname']
                scores.highLevel=config['highlevel']
                scores.highID=config['highid']
                self.update=config.as_bool('update')
                self.lastUpdateYear=config.as_int('year')
                self.lastUpdateMonth=config.as_int('month')
                self.lastUpdateDay=config.as_int('day')
            elif v==3:  # handle loading an old (version 3) pref file
                self.version=v
                self.fullScreen=config.as_bool('fullscreen')
                self.firstRun=config.as_bool('firstrun')
                self.interface=config.as_int('interface')
                self.language=config.as_int('language')
                self.audioVolume=config.as_float('audiovolume')
                self.musicVolume=config.as_float('musicvolume')
                self.userName=config['username']
                scores.highScore=config['highscore']
                scores.highName=config['highname']
                scores.highLevel=config['highlevel']
                self.update=config.as_bool('update')
                self.lastUpdateYear=config.as_int('year')
                self.lastUpdateMonth=config.as_int('month')
                self.lastUpdateDay=config.as_int('day')
            elif v==2:  # handle loading an old (version 2) pref file
                self.version=v
                self.fullScreen=True
                self.firstRun=config.as_bool('firstrun')
                self.language=config.as_int('language')
                self.audioVolume=config.as_float('audiovolume')
                self.musicVolume=config.as_float('musicvolume')
                scores.userName=config['username']
                scores.highScore=config['highscore']
                scores.highName=config['highname']
                self.highLevel=config['highlevel']
            elif v==1:  # handle loading and old (version 1) pref file
                self.version=kPrefVersion
                self.fullScreen=True
                self.firstRun=config.as_bool('firstrun')
                self.language=config.as_int('language')
                self.audioVolume=config.as_float('audiovolume')
                self.musicVolume=config.as_float('musicvolume')
                self.userName=config['username']                
        except:
            print "error loading preference file"
            print sys.exc_info()
            self.save()
   
    def save(self):
        """ save preference to file """
        config=ConfigObj()
        config.filename=get_pref_path()
        config['version']=kPrefVersion
        config['fullscreen']=self.fullScreen
        config['firstrun']=self.firstRun
        config['language']=self.language
        config['interface']=self.interface
        config['audiovolume']=self.audioVolume
        config['musicvolume']=self.musicVolume
        config['username']=self.userName
        config['update']=self.update
        config['year']=self.lastUpdateYear
        config['month']=self.lastUpdateMonth
        config['day']=self.lastUpdateDay
        config['fps']=self.maxFrameRate
        config.write()

class MicroWar(FGame):
    """ MicroWar Class
        Handle the whole game into this class
        All Screen is handled here, depending on the mode :
            "intro"  : the splash screen while loading
            "menu"   : main menu
            "score"  : show high scores
            "option" : game options menu
            "help"   : help/instruction screen
            "play"   : do the game
    """

    def __init__(self,fullScreen,width=kSCREEN_WIDTH,height=kSCREEN_HEIGHT):
        FGame.__init__(self,fullScreen,width,height)

        self.showFPS=False
        self.fps=None
        self.keyInUserName=False
        self.screen=None
        self.success=0   # number of successful shoot in a series
        
    def start(self):
        FGame.start(self,self.pref.audioVolume,self.pref.musicVolume)
        
    def build_splash_labels(self,withCredits=False):
        """ just create some standard labels for all screen, except "play" """       
        title=self.get_widget('title')
        title.set_text(k_NAME)
        subTitle=self.get_widget('subtitle')
        copyright=self.get_widget('copyright')
        cp=self.get_widget('strcopyright')
        copyright.set_text(u"%s - version %s" % (cp.get_text(self.pref.language),k_VERSION))
        
        if withCredits==True:
            credit=self.get_widget('credit')
    
    def new_screen(self,name):
        """ create a display screen, according to name (menu dispatch) """
        
        self.mode=name
        
        if name=="intro":
            screen=IntroScreen(self,name)
        elif name=="menu":
            screen=MenuScreen(self,name)
        elif name=="help":
            screen=HelpScreen(self,name)
        elif name=="option":
            screen=OptionScreen(self,name)
        elif name=="score":
            screen=ScoreScreen(self,name)
        elif name=="lscore":
            screen=SharedScoreScreen(self,name)
        elif name=="first":
            screen=FirstScreen(self,name)
        elif name=="askupdate":
            screen=AskUpdateScreen(self,name)
        elif name=="update":
            screen=UpdateScreen(self,name)
        elif name=="play":
            screen=PlayScreen(self,name)
        else:
            self.screen=None
            print "error, screen %s do not exist"  

    def update(self):
        """ update the game, simply display display speed (FPS) if required,
            then delegate update to standard game update """
            
        if self.showFPS:
            self.fps.set_text("FPS: %.1f" % self.screen.clock.get_fps())
            
        FGame.update(self)

    def load_data(self):
        """ load game data, read the INI file, and preprocess data """
        
        now=time.time() # chronometer (see at the end)

        # Read 'data.ini' to build resources lists
        try:
            self.screen.do_one_frame(2.0)
            
            # 1/ open the INI file
            config=ConfigObj(make_path((self.dataPath,kDataFilename)),file_error=True,raise_errors=True)
            
            #read raw data from section RESOURCES
            section1=config['Resources']
            backimagelist=section1['backimagelist']
            screenlist=section1['screenlist']
            explosionlist=section1['explosionlist']
            sexplosionlist=section1['sexplosionlist']
            ilist=section1['ilist']
            maclist=section1['maclist']
            macslist=section1['macslist']
            maclifelist=section1['maclifelist']
            shotlist=section1['shotlist']
            shotslist=section1['shotslist']
            slist=section1['slist']
            pclist=section1['pclist']
            pcoslist=section1['pcoslist']
            bomblist=section1['bomblist']
            saucerlist=section1['saucerlist']
            bonuslist=section1['bonuslist']
            bonusanimlist=section1['bonusanim']
            interfacelist=section1['interfacelist']
            viruslist=section1['viruslist']
            levellist=section1['levellist']
            helplist=section1['helplist']
            
            # 2/ read raw data from section GAMECONFIG
            section2=config['GameConfig']
            self.macModels=section2['macModels']
            self.macScreenX=section2.as_intList('macScreenX')
            self.macScreenY=section2.as_intList('macScreenY')
            self.macScreenW=section2.as_intList('macScreenW')
            self.macScreenH=section2.as_intList('macScreenH')
            self.macModelProcessor=section2.as_intList('macModelProcessor')
            self.macSystemLevel=section2.as_intList('macSystemLevel')
            self.macSystems=section2['macSystems']
            self.macProcessorProducer=section2['macProcessorProducer']
            self.macProcessors=section2['macProcessors']
            self.macProcessorProd=section2.as_intList('macProcessorProd')
            self.macProcessorLevel=section2.as_intList('macProcessorLevel')
            self.pcFamilly=section2.as_floatList('pcFamilly')
            self.c64Familly=section2.as_floatList('c64Familly')
            self.atariFamilly=section2.as_floatList('atariFamilly')
            self.amigaFamilly=section2.as_floatList('amigaFamilly')
            self.amstradFamilly=section2.as_floatList('amstradFamilly')
            self.pcForces=section2.as_intList('pcForces')
            self.pcForcesL=section2.as_intList('pcForcesL')
            self.pcScreenX=section2.as_intList('pcScreenX')
            self.pcScreenY=section2.as_intList('pcScreenY')
            self.pcScreenW=section2.as_intList('pcScreenW')
            self.pcScreenH=section2.as_intList('pcScreenH')
            self.msdos=section2.as_floatList('msdos')
            self.msdosImages=section2.as_intList('msdosImages')
            self.win10=section2.as_floatList('win10')
            self.win10Images=section2.as_intList('win10Images')
            self.win20=section2.as_floatList('win20')
            self.win20Images=section2.as_intList('win20Images')
            self.win30=section2.as_floatList('win30')
            self.win30Images=section2.as_intList('win30Images')
            self.win95=section2.as_floatList('win95')
            self.win95Images=section2.as_intList('win95Images')
            self.win98=section2.as_floatList('win98')
            self.win98Images=section2.as_intList('win98Images')
            self.winxp=section2.as_floatList('winxp')
            self.winxpImages=section2.as_intList('winxpImages')
            self.winvs=section2.as_floatList('winvs')
            self.winvsImages=section2.as_intList('winvsImages')
            self.win70=section2.as_floatList('win70')
            self.win70Images=section2.as_intList('win70Images')
            self.os2Images=section2.as_intList('os2Images')
            self.c64Images=section2.as_intList('c64Images')
            self.cAmstradImages=section2.as_intList('cAmstradImages')
            self.cAtariImages=section2.as_intList('cAtariImages')
            self.cAmigaImages=section2.as_intList('cAmigaImages')
            self.apple1=section2.as_floatList('apple1')
            self.apple2=section2.as_floatList('apple2')
            self.motorola=section2.as_floatList('motorola')
            self.ibm=section2.as_floatList('ibm')
            self.intel=section2.as_floatList('intel')
            self.clarus=section2.as_floatList('clarus')
            self.newton=section2.as_floatList('newton')
            self.ipod=section2.as_floatList('ipod')
            self.iphone=section2.as_floatList('iphone')
            self.ram=section2.as_floatList('ram')
            
            # 3/ LOAD IMAGES AND SOUNDS read from INI file
            # + update the progress bar (do_one_frame)
            
            self.imagePath=kBackgroundPath
            self.backImages=[]
            for i in backimagelist: 
                self.backImages.append(self.load_image(i))
            self.screen.do_one_frame(40.0)
            self.screenImages=[]
            for i in screenlist:
                self.screenImages.append(self.load_image(i))
                
            self.screen.do_one_frame(60.0)
            self.imagePath=kSpritePath
            self.explosionImages=[]
            for i in explosionlist:
                self.explosionImages.append(self.load_image(i))
            self.explosionSmallImages=[]
            for i in sexplosionlist:
                self.explosionSmallImages.append(self.load_image(i))
            self.infoIcons=[]
            for i in ilist:
                self.infoIcons.append(self.load_image(i))
            self.macImages=[]
            for i in maclist:
                self.macImages.append(self.load_image(i))
            self.macLifeImages=[]
            for i in maclifelist:
                self.macLifeImages.append(self.load_image(i))
            self.shotImages=[]
            for i in shotlist:
                self.shotImages.append(self.load_image(i))
            self.pcImages=[]
            for i in pclist:
                self.pcImages.append(self.load_image(i))
            self.pcOSImages=[]
            for i in pcoslist:
                self.pcOSImages.append(self.load_image(i))
            self.bombImages=[]
            for i in bomblist:
                self.bombImages.append(self.load_image(i))
            self.saucerImages=[]
            for i in saucerlist:
                self.saucerImages.append(self.load_image(i))
            self.bonusImages=[]
            for i in bonuslist:
                self.bonusImages.append(self.load_image(i))
            self.bonusAnimImages=[]
            for i in bonusanimlist:
                self.bonusAnimImages.append(self.load_image(i))
            self.virusImages=[]
            self.virusImages.append(self.load_image(viruslist))
            self.macSounds=[]
            for i in macslist:
                self.macSounds.append(self.load_sound(i))
            self.screen.do_one_frame(68.0)
            self.shotSounds=[]
            for i in shotslist:
                self.shotSounds.append(self.load_sound(i))
            self.gameSounds=[]
            for i in slist:
                self.gameSounds.append(self.load_sound(i))
            self.screen.do_one_frame(72.0)
            self.interfaceSounds=[]
            for i in interfacelist:
                self.interfaceSounds.append(self.load_sound(i))
            self.levelImages=[]
            for i in levellist:
                self.levelImages.append(self.load_image(i))
            self.helpImages=[]
            for i in helplist:
                self.helpImages.append(self.load_image(i))
            
            # just a chronomer to measure loading speed
            self.screen.do_one_frame(80.0)
            now=time.time()-now
            print "Loading : %.1f seconds" % now
            
            #just make a little pause if loading is too fast (make sure it's more than 3 seconds)
            now=2.0-now
            if now>0.0:
                pygame.time.wait(int(1000*now))
            self.screen.do_one_frame(100.0)
                
            return 0
            
        except ParseError:
            print 'Loading Data : ParseError'
            return 1
        except IOError:
            print 'Loading Data : IOError, file data.ini do not exist'
            return 2
        except DuplicateError:
            print 'Loading Data : DuplicateError, duplicate keyword'
            return 3
        except KeyError,k:
            print 'Loading Data : KeyError, key do not exist'
            print k
            return 4
        except:
            print 'Loading Data : error loading data' 
            print sys.exc_info()
            return 99
    
    def check_update(self,currentVersion):
        """ check for a game update available """
        
        d=datetime.date.today()
        ld=datetime.date(self.pref.lastUpdateYear,self.pref.lastUpdateMonth,self.pref.lastUpdateDay)
        delta=(d-ld).days
        self.pref.lastUpdateYear=d.year
        self.pref.lastUpdateMonth=d.month
        self.pref.lastUpdateDay=d.day
        self.pref.save()
        
        # check update over internet, every kUpdateDelay days
        url=None
        version=None
        if delta>=kUpdateDelay:
            print "do update check, %d days" % delta
            try:    # read the URL to get the last available version
                stream,length=create_download(k_UPDATE_URL)
                version=stream.readline().strip('\n')
                if version_compare(version,currentVersion)>0:
                    urldarwin=stream.readline().strip('\n')
                    urlwin32=stream.readline().strip('\n')
                    urllinux=stream.readline().strip('\n')
                    txt=stream.readline().strip('\n')
                    if sys.platform=='darwin':
                        url=urldarwin
                    elif sys.platform=='win32':
                        url=urlwin32
                    else:
                        url=urllinux
                    print "update available, %s to download at %s" % (version,url)
                else:
                    print "no update available, %s running" % currentVersion
                stream.close()
                
            except Exception,e:
                print "Error downloading %s: %s" % (k_UPDATE_URL, e)
                url=None

        return url,version
        
    def get_level(self):
        """ simple wrapper to avoid using a very long access name """
        if self.screen==None:
            return -1
        elif self.screen.name=="play":
            return self.screen.level.get_level()
        else :
            return -1

def profile_main():
    print "-- profiling %s %s --------------------------" % (k_NAME,k_VERSION)
    print "pygame %s" % pygame.__version__
    scores=FHighScores()
    pref=FPreferences()
    pref.load(scores)
    game=MicroWar(pref.fullScreen)
    game.scores=scores
    game.scores.load()
    game.set_caption('profiling %s %s' % (k_NAME,k_VERSION))
    game.pref=pref
    game.language=game.pref.language
    game.maxFrameRate=game.pref.maxFrameRate
    game.dataPath=kDataPath
    game.imagePath=kSpritePath
    game.soundPath=kSoundPath
    game.fontPath=kFontPath    
    game.load_widgets(kWidgetFilename)
    game.new_screen("intro")
    game.show()
    err=game.load_data()
    if err!=0: return err
    
    game.new_screen("play")
    game.start()
    
    game.pref.save()
    game.scores.save()
    pygame.quit()


def main():
    """ main sequence runtime """
    print "-- %s %s log --------------------------" % (k_NAME,k_VERSION)
    print "pygame %s" % pygame.__version__
    
    # load preferences
    scores=FHighScores()
    pref=FPreferences()
    pref.load(scores)

    # create the game container
    game=MicroWar(pref.fullScreen)
    game.scores=scores
    game.scores.load()
    game.set_caption('%s %s' % (k_NAME,k_VERSION))
    game.pref=pref
    game.language=game.pref.language
    game.maxFrameRate=game.pref.maxFrameRate
       
    # Read 'widget.ini' to build the widget tree
    game.dataPath=kDataPath
    game.imagePath=kSpritePath
    game.soundPath=kSoundPath
    game.fontPath=kFontPath    
    game.load_widgets(kWidgetFilename)

    # display the IntroScene and load ressources (splash screen)
    game.new_screen("intro")
    game.show()
    err=game.load_data()
    if err!=0: return err

    fname=make_path((kDataPath,kSoundPath,'generic.ogg'))
    if not pygame.mixer or not pygame.mixer.get_init():
        print "error with pygame.mixer"
        return(999)
    pygame.mixer.music.load(fname)
    pygame.mixer.music.set_volume(game.pref.musicVolume)
    pygame.mixer.music.play(-1)
    
    # check for the first run : user can choose language
    if game.pref.firstRun:
        game.userChoice="first"
        game.pref.firstRun=False
        game.pref.save()
    else:
        game.userChoice="menu"
        # check for game update on the internet
        if game.pref.update:
            (game.url,game.updateVersion)=game.check_update(k_VERSION)
            if game.url!=None:
                game.userChoice="askupdate"
                    
    # do the game (menu and fork to other mode depending on user choice
    # mode : name of the current screen
    # userchoice : what's the user choose for the next screen (will became mode)
    terminate=False
    game.bestScore=-1 # no score record brake during last game
    while not terminate: #default screen is main menu when no userChoix match (see else below)
        if game.userChoice=="option":   # option screen
            game.new_screen("option")
            game.start()
            game.pref.save()
            if game.userChoice=="quit":
                game.userChoice="menu"
        elif game.userChoice=="score":  # high score screen
            game.new_screen("score")
            game.start()
            if game.bestScore>=0: # if high score
                if game.pref.update:    # if internet connection allowed
                    fscore=FInternetScore()
                    id=fscore.save(game.scores.highName[game.bestScore],game.scores.highScore[game.bestScore],game.scores.highLevel[game.bestScore])
                else:
                    id=-1
                game.scores.highID[game.bestScore]=id
                game.scores.save()
                game.bestScore=-1
            if game.userChoice=="quit":
                game.userChoice="menu"
        elif game.userChoice=="lscore": # high score over internet
            game.new_screen("lscore")
            game.start()
            if game.userChoice=="quit":
                game.userChoice="menu"
        elif game.userChoice=="help":   # help screen
            game.new_screen("help")
            game.start()
            if game.userChoice=="quit":
                game.userChoice="menu"
        elif game.userChoice=="first":  # first launch screen : basic settings
            game.new_screen("first")
            game.start()
            if game.userChoice=="english":
                game.pref.language=kEnglish
            elif game.userChoice=="french":
                game.pref.language=kFrench
            elif game.userChoice=="german":
                game.pref.language=kGerman
            elif game.userChoice=="spanish":
                game.pref.language=kSpanish
            elif game.userChoice=="italian":
                game.pref.language=kItalian
            game.language=game.pref.language
            game.pref.save()
            game.userChoice="menu"
        elif game.userChoice=="askupdate":  # update screen
            game.new_screen("askupdate")
            game.start()
            if game.userChoice=="yes":
                webbrowser.open(game.url,1,1)
                terminate=True
            elif game.userChoice=="never":
                game.pref.update=False
            else:
                game.userChoice="menu"
        elif game.userChoice=="play":   # play screen
            game.new_screen("play")
            pygame.mixer.music.pause()
            game.start()
            pygame.mixer.music.unpause()
            
            #Game Over, check for best score
            print "%s fps: %.1f" % (k_NAME,game.screen.clock.get_fps())
            game.bestScore=-1
            game.userChoice="menu"
            if (not game.screen.abort) and (not game.screen.cheat):
                game.bestScore=game.scores.set_score(game.pref.userName,game.screen.score.value,game.get_level())
                if game.bestScore>=0 :
                    game.keyInUserName=True
                    game.userChoice="score"
        elif game.userChoice=="quit":   # quit : no screen, just terminate (exit the loop)
            terminate=True
        else: # default screen is menu, when no ither userChoice match
            game.bestScore=-1
            game.new_screen("menu")
            game.start()
        
    pygame.mixer.music.fadeout(100)
    game.pref.save()
    game.scores.save()
    pygame.quit()

#this calls the 'main' function when this script is executed
if __name__ == '__main__': 
    if '-profile' in sys.argv:
        cProfile.run('profile_main()','microwar.profile')
        p=pstats.Stats('microwar.profile')
        p.strip_dirs()
        p.sort_stats('time')
        p.print_stats()
    else:
        main()
