def main():

    #"""
    #Modified BGE Gameplay Recorder Version 2
    #originally written by Nicholas Anderson, aka Red Frost Games.
    #"""

    #####Tweakables###############
    #Watch out! These numbers might bite!
    frame_rate = 60    #Set this to the framerate of your game.
    optimization = 1    #An integer, must be at least 1! Higher value will make a smaller saved file size. I do not reccomend setting it to anything other than 1 though.
    recording_cutoff = 7300 #3600   #Frames at which the oldest recorded frame will be deleted. 0 is no cutoff.
    recorder_state = 1   #This is the main state of the recorder object. State will be reverted to this value when the user breaks out of the playback.
    allow_playback_break = True   #Allow the player to resume playing from the position in the recording.
    #####Sensor names#############
    record_sensor = "Record"
    save_recording_sensor = "Save"
    load_recording_sensor = "Load"
    track_left_sensor = "Left"
    track_right_sensor = "Right"
    break_sensor = "Break"
    ##############################

    from bge import logic
    import Record
    import SortData

    cont = logic.getCurrentController()
    own = cont.owner

    cont.sensors[record_sensor].skippedTicks = optimization
    dict = logic.globalDict

    #dict['recorder_on'] = recorder_on
    recorder_on = dict.get('recorder_on')
    own['recorder_on'] = recorder_on
    #print("recorder on: ", recorder_on) 

    if recorder_on == 1:
        #----
        scene = logic.getCurrentScene()
        scene_list = logic.getSceneList()
        camList = scene.cameras
        followcam = camList["followcam"]
        freecam = camList["freecam"]
        skater = scene.objects["Char4"]
        cube = scene.objects["control_cube.002"]
        deck = scene.objects["deck"]
        trucks = scene.objects["trucks"]
        replay_cam_axis = own['replay_cam_axis']
        cam = own.actuators['Camera']
        #----
        joybutsens = "joyBut"
        #butt = cont.sensors[joybutsens]
        #aXis = cont.sensors["joysticksens"]
        #bk_but = 4
        back_on = dict['bkBut']
        #a_but = 0
        a_on = dict['aBut']
        #b_but = 1
        b_on = dict['bBut']
        #print(a on)
        last_back = own['last_back_but']
        #last_back = own['last_a_but']
    #    reduction = 400000
    #    axisTh = 0.03 
    #    lt = 4
    #    rt = 5
    #    lts_pr = 7
    #    rts_pr = 8

    #    lar_lts = 0
    #    uad_lts = 1
    #    lar_rts = 2 
    #    uad_rts = 3 
        #lts_pr = 7
        #rts_pr = 8
    #    lTrig = aXis.axisValues[lt] / reduction
    #    rTrig = aXis.axisValues[rt] / reduction
    #    lLR = aXis.axisValues[lar_lts] / reduction
    #    lUD = aXis.axisValues[uad_lts] / reduction
    #    rLR = aXis.axisValues[lar_rts] / reduction
    #    rUD = aXis.axisValues[uad_rts] / reduction
    #    ltsBut = butt.getButtonStatus(lts_pr)
    #    rtsBut = butt.getButtonStatus(rts_pr) 
    #        
        lLR = dict['lLR']
        lUD = dict['lUD']
        rLR = dict['rLR']
        rUD = dict['rUD']
        lTrig = dict['lTrig']
        rTrig = dict['rTrig']
        aBut = dict['aBut']
        bBut = dict['bBut']
        xBut = dict['xBut']
        yBut = dict['yBut']
        lBump = dict['lBump']
        rBump = dict['rBump']
        bkBut = dict['bkBut']
        stBut = dict['stBut']
        xbBut = dict['xbBut']
        ltsBut = dict['ltsBut']
        rtsBut = dict['rtsBut']
        ldPad = dict['ldPad']
        rdPad = dict['rdPad']
        udPad = dict['udPad']
        ddPad = dict['ddPad']    
            
        try:
            pause_state = dict['npause']
            last_pause = dict['last_npause']
        except:
            dict['npause'] = 0
            dict['last_npause'] = 0
            pause_state = 0
            last_pause = 0          
           
        #trigs results range 0 - .08
        #print(lTrig, rTrig)

        #if cont.sensors[record_sensor].positive:
        if own["playback"] != True:    
            Record.main(recording_cutoff, cube)
            
        if cont.sensors[save_recording_sensor].positive:
            SortData.writeData.saveAll()
            
        #if cont.sensors[load_recording_sensor].positive or (cube["sel"] == 1 and cube["last_sel"] == 0):
        if own['back_state'] == 1 and back_on == 1 and last_back == 0:
            cube["last_sel"] == 1
            SortData.writeData.saveAll()
            own["playback"] = True
            own["playbackBroken"] = False
            freecam.worldPosition = own.worldPosition
            followcam.worldPosition = own.worldPosition
            cube['grindcement_vol'] = 0
            cube['grindcement_pitch'] = 0
            cube['grindrail_vol'] = 0
            cube['grindrail_pitch'] = 0 
            cube['sroll_vol'] = 0
            cube['sroll_pitch'] = 0             
            

        if own["playback"]:
            Record.loadData()
        #..................
        if cont.sensors[track_left_sensor].positive:
            own["objIndex"] -= 2
            logic.setLogicTicRate(frame_rate*own["playbackSpeed"])
            
        if cont.sensors[track_right_sensor].positive:
            own["objIndex"] += 2
            logic.setLogicTicRate(frame_rate*own["playbackSpeed"])

        if own["playback"] == True:    
            if rTrig > .01 and rTrig < .02:
                own["objIndex"] += 2
                logic.setLogicTicRate(frame_rate*.5) 
            if (rTrig >= .02 and rTrig < .06) or own['loop_play'] == 1:
                own["objIndex"] += 2
                logic.setLogicTicRate(frame_rate*1)
                #print(own['objIndex'])
            if rTrig >= .06 and rTrig < .09:
                own["objIndex"] += 2
                logic.setLogicTicRate(frame_rate*1.5) 
            if lTrig > .01 and lTrig < .02:
                own["objIndex"] -= 2
                logic.setLogicTicRate(frame_rate*.5) 
            if lTrig >= .02 and lTrig < .06:
                own["objIndex"] -= 2
                logic.setLogicTicRate(frame_rate*1)
            if lTrig >= .06 and lTrig < .09:
                if own['loop_play'] == 1:
                    own["objIndex"] -= 6
                    #logic.setLogicTicRate(frame_rate*1.5)
                else:    
                    own["objIndex"] -= 2
                    logic.setLogicTicRate(frame_rate*1.5)
            if b_on == True and pause_state == 0:
                #print("bbut_on")
                own['objIndex'] = 0
                own['valueIndex'] = 0 
                logic.setLogicTicRate(frame_rate*1)                       

        #....................
        if allow_playback_break:

            if own['back_state'] == 0 and back_on == 1 and last_back == 0:       
                own["playbackBroken"] = True
                own["playback"] = False
                #print("break - add hud, remove stance (back_state == False)")
                #cont.activate(own.actuators['add_hud'])
                #cont.activate(own.actuators['remove_stance'])
                #removescene = cont.actuators["remove_hud"]
                #removescene.scene = "replay_HUD"
                #addscene = cont.actuators["add_hud"]
                #addscene.scene = "stance"
                #cont.activate(addscene)        
                #cont.activate(removescene)
            elif own["playbackBroken"] and back_on == 0:
                Record.breakOut()
                #cont.activate(own.actuators['remove_hud'])
                #cont.activate(own.actuators['add_stance'])
                #addscene = cont.actuators["add_hud"]
                #addscene.scene = "replay_HUD"
                #removescene = cont.actuators["remove_hud"]
                #removescene.scene = "stance"
                #cont.activate(addscene)
                #cont.activate(removescene)
                
                logic.setLogicTicRate(frame_rate)
                #set value index
                own.state = recorder_state
                own["playbackBroken"] = False
                skater.stopAction(9999)
                deck.stopAction(9999)
                trucks.stopAction(9999)
                cont.activate(own.actuators['replayCam'])
                #print("unbreak")
                own['loop_play'] = 0
                #own['valueIndex'] = 0
                #own["objIndex"] += 2
                #logic.setLogicTicRate(frame_rate*1)
                #own['objectIndex'] = 0
                #print("valueIndex = ", own['valueIndex'])
        if back_on == 1 and own['back_but'] == 0:
            #print("change back state")
            if own['back_state'] == True:
                own['back_state'] = False
            #elif own['back_state'] == False:
            else:
                own['back_state'] = True
    ###
        if own['last_playback'] != own['playback']:
            if own['last_playback'] == True:
                cont.activate(own.actuators['remove_hud'])
                cont.activate(own.actuators['add_stance']) 
                own['camnum'] = 0
                cam = camList["Camera.003"]
                scene.active_camera = cam                        
                #print("turning replay off", own['playback'])
                
              
            if own['last_playback'] == False:
                #print("turning replay on", own['playback'])
                cont.activate(own.actuators['add_hud'])
                cont.activate(own.actuators['remove_stance'])
                own['objIndex'] = 0
                own['valueIndex'] = 3
                logic.setLogicTicRate(frame_rate*1)  
                
                
              
                
        if dict['rtsBut'] == False and dict['last_rtsBut'] == True and own['playback'] == True:
            
            if 'pause' in scene_list:    
                #cont.activate(own.actuators['remove_overlay']) 
                cont.activate(own.actuators['add_hud'])
            else:
                #cont.activate(own.actuators['add_overlay']) #pause
                cont.activate(own.actuators['remove_hud']) #replay 
                cont.activate(own.actuators['pause_replay_remove']) 
                                            
        if pause_state == 1 and last_pause == 1 and own["playback"]:
            #print('pause_on')
            if 'pause_replay' not in scene_list:
                cont.activate(own.actuators['pause_replay_add'])
                #print('pause_on')
                
        if pause_state != 1 and own["playback"]:
            if 'pause_replay' in scene_list:
                cont.activate(own.actuators['pause_replay_remove'])                    
        if own['playback'] and 'pause' in scene_list:
            cont.activate(cube.actuators['remove_overlay'])                         
                             
    ####
        if a_on == 1 and own['a_but'] == False and pause_state == 0:
            if own['loop_play'] == 1:
                own['loop_play'] = 0
            else:
                own['loop_play'] = 1            
        if rLR > .05 and own["playback"]:
            act = cont.actuators["replayCam"]
            if rLR > .07:
                act.dLoc = [ .06, 0.0, 0.0]
            else:
                act.dLoc = [ .03, 0.0, 0.0]
            #cont.deactivate(own.actuators['Camera'])
            cont.activate(own.actuators['replayCam']) 
            #print("move") 
        elif rLR < -.05 and own["playback"]:
            act = cont.actuators["replayCam"]
            if rLR < -.07:
                act.dLoc = [ -.06, 0.0, 0.0]
            else:    
                act.dLoc = [ -.03, 0.0, 0.0]
            #cont.deactivate(own.actuators['Camera'])
            #act.damping = 6
            cont.activate(own.actuators['replayCam']) 
            #print("move")         
        else:  
            #pass      
            cont.deactivate(own.actuators['replayCam'])
            #cont.activate(own.actuators['Camera'])
        #print("back state: ", own['back_state'], "last_back_but: ", own['last_back_but'], "back_but :", own['back_but'])  
        #integer
        # 
        #0 = +X axis
        # 
        #1 = +Y axis
        # 
        #2 = +Z axis
        # 
        #3 = -X axis
        # 
        #4 = -Y axis
        # 
        #5 = -Z axis
    #    if rLR > .05 and own["playback"]:
    #        if own['last_rtsBut'] == True and rtsBut == False:
    #            if replay_cam_axis == 0:
    #               replay_cam_axis = 1
    #            elif replay_cam_axis == 1:
    #                replay_cam_axis = 3
    #            elif replay_cam_axis == 3 :
    #                replay_cam_axis = 4
    #            elif replay_cam_axis == 4:
    #                replay_cam_axis = 0 
    #        cam.axis = replay_cam_axis
    #        cont.activate(cam)
    #        print("set replay_cam_axis: ", replay_cam_axis)
    #        own['replay_cam_axis'] = replay_cam_axis
        if own['last_ltsBut'] == True and ltsBut == False and own['playback']:
            # get camera named SecurityCam
            if own['camnum'] == 1:
                own['camnum'] = 2
            elif own['camnum'] == 0:
                own['camnum'] = 1 
            elif own['camnum'] == 2:
                own['camnum'] = 0    
        if own['last_rtsBut'] == True and rtsBut == False and own['playback']:
            # get camera named SecurityCam
            if "replay_HUD" in scene_list:
                cont.activate(own.actuators['remove_hud'])
            else:
                cont.activate(own.actuators['add_hud'])
        if own['camnum'] == 1 and own['playback']:
            
            scene.active_camera = followcam 
            #################
            camspeed1 = .04 #.015
            camspeed2 = .1 #.055
            camrot1 = .02 #.005
            camrot2 = .04 #.02
#            perc = (lUD * 100 * (10 / 80)) *2
#            perc = round(perc,2)
#            print(perc)
#            perc = .025 * perc
#            newUD = (lUD * .1) * 5
#            if lUD > .0005 or lUD < -.0005:
#                camspeed1 = abs(perc)
#                camspeed2 = abs(perc)
            #up
            if lUD < -0.080:
                followcam.actuators["up"].dLoc = [ 0, 0, -camspeed2]
                cont.activate(followcam.actuators["up"])
                print("fastup")
            else:
                cont.deactivate(followcam.actuators["up"])    
    #            #down    
            if lUD > .080:
                followcam.actuators["down"].dLoc = [ 0, 0, camspeed2]
                cont.activate(followcam.actuators["down"])
            else:
                cont.deactivate(followcam.actuators["down"])                    
    #            #left
            if lLR < -0.080:
                followcam.actuators["left"].dLoc = [-camspeed2, 0, 0]                
                cont.activate(followcam.actuators["left"])
            else:
                cont.deactivate(followcam.actuators["left"])                    
    #            #right
            if lLR > 0.080:         
                followcam.actuators["right"].dLoc = [camspeed2, 0, 0]                
                cont.activate(followcam.actuators["right"])
            else:
                cont.deactivate(followcam.actuators["right"])  
            #up
            if rUD < -0.080:
                followcam.actuators["rotup"].dLoc = [0, 0, camrot2]
                cont.activate(followcam.actuators["rotup"])
                #print("uppppppppppppppppppppppppppp")
            else:
                cont.deactivate(followcam.actuators["rotup"])    
    #            #down    
            if rUD > .080:
                followcam.actuators["rotdown"].dLoc = [0, 0, -camrot2]                
                cont.activate(followcam.actuators["rotdown"])
            else:
                cont.deactivate(followcam.actuators["rotdown"])                    
    #            #left
            if rLR < -0.080:
                followcam.actuators["rotleft"].dRot = [0, 0, camrot2]                
                cont.activate(followcam.actuators["rotleft"])
            else:
                cont.deactivate(followcam.actuators["rotleft"])                    
    #            #right
            if rLR > 0.080:         
                followcam.actuators["rotright"].dRot = [0, 0, -camrot2]
                cont.activate(followcam.actuators["rotright"])
            else:
                cont.deactivate(followcam.actuators["rotright"]) 

    #*********************************************                
                
            if lUD > -0.080 and lUD < -0.030:
                followcam.actuators["up"].dLoc = [ 0, 0, -camspeed1]
                cont.activate(followcam.actuators["up"])
                #print(lUD)
            else:
                cont.deactivate(followcam.actuators["up"])    
    #            #down    
            if lUD < .080 and lUD > .03:
                followcam.actuators["down"].dLoc = [ 0, 0, camspeed1]                
                cont.activate(followcam.actuators["down"])
            else:
                cont.deactivate(followcam.actuators["down"])                    
    #            #left
            if lLR > -0.080 and lLR < -0.030:
                followcam.actuators["left"].dLoc = [-camspeed1, 0, 0]                
                cont.activate(followcam.actuators["left"])
            else:
                cont.deactivate(followcam.actuators["left"])                    
    #            #right
            if lLR < .080 and lLR > .03:       
                followcam.actuators["right"].dLoc = [camspeed1, 0, 0]
                cont.activate(followcam.actuators["right"])
            else:
                cont.deactivate(followcam.actuators["right"])  
            #up
            if rUD > -0.080 and rUD < -0.030:
                followcam.actuators["rotup"].dRot = [camrot1, 0, 0]                
                cont.activate(followcam.actuators["rotup"])
            else:
                cont.deactivate(followcam.actuators["rotup"])    
    #            #down    
            if rUD < .080 and rUD > .03:
                followcam.actuators["rotdown"].dRot = [-camrot1, 0, 0]                
                cont.activate(followcam.actuators["rotdown"])
            else:
                cont.deactivate(followcam.actuators["rotdown"])                    
    #            #left
            if rLR > -0.080 and rLR < -0.030:
                followcam.actuators["rotleft"].dRot = [0, 0, camrot1]
                cont.activate(followcam.actuators["rotleft"])
            else:
                cont.deactivate(followcam.actuators["rotleft"])                    
    #            #right
            if rLR < .080 and rLR > .03:         
                followcam.actuators["rotright"].dRot = [0, 0, -camrot1]
                cont.activate(followcam.actuators["rotright"])
            else:
                cont.deactivate(followcam.actuators["rotright"])          
            
            #################
            
        if own['camnum'] == 2 and own['playback']:
            
            scene.active_camera = freecam
            
            #act = freecam.actuators[
            camspeed1 = .015
            camspeed2 = .055
            camrot1 = .005
            camrot2 = .02
            #up
            if lUD < -0.080:
                freecam.actuators["up"].dLoc = [ 0, 0, -camspeed2]
                cont.activate(freecam.actuators["up"])
                #print("fastup")
            else:
                cont.deactivate(freecam.actuators["up"])    
    #            #down    
            if lUD > .080:
                freecam.actuators["down"].dLoc = [ 0, 0, camspeed2]
                cont.activate(freecam.actuators["down"])
            else:
                cont.deactivate(freecam.actuators["down"])                    
    #            #left
            if lLR < -0.080:
                freecam.actuators["left"].dLoc = [-camspeed2, 0, 0]                
                cont.activate(freecam.actuators["left"])
            else:
                cont.deactivate(freecam.actuators["left"])                    
    #            #right
            if lLR > 0.080:         
                freecam.actuators["right"].dLoc = [camspeed2, 0, 0]                
                cont.activate(freecam.actuators["right"])
            else:
                cont.deactivate(freecam.actuators["right"])  
            #up
            if rUD < -0.080:
                freecam.actuators["rotup"].dRot = [camrot2, 0, 0]
                cont.activate(freecam.actuators["rotup"])
            else:
                cont.deactivate(freecam.actuators["rotup"])    
    #            #down    
            if rUD > .080:
                freecam.actuators["rotdown"].dRot = [-camrot2, 0, 0]                
                cont.activate(freecam.actuators["rotdown"])
            else:
                cont.deactivate(freecam.actuators["rotdown"])                    
    #            #left
            if rLR < -0.080:
                freecam.actuators["rotleft"].dRot = [0, 0, camrot2]                
                cont.activate(freecam.actuators["rotleft"])
            else:
                cont.deactivate(freecam.actuators["rotleft"])                    
    #            #right
            if rLR > 0.080:         
                freecam.actuators["rotright"].dRot = [0, 0, -camrot2]
                cont.activate(freecam.actuators["rotright"])
            else:
                cont.deactivate(freecam.actuators["rotright"]) 

    #*********************************************                
                
            if lUD > -0.080 and lUD < -0.030:
                freecam.actuators["up"].dLoc = [ 0, 0, -camspeed1]
                cont.activate(freecam.actuators["up"])
                #print(lUD)
            else:
                cont.deactivate(freecam.actuators["up"])    
    #            #down    
            if lUD < .080 and lUD > .03:
                freecam.actuators["down"].dLoc = [ 0, 0, camspeed1]                
                cont.activate(freecam.actuators["down"])
            else:
                cont.deactivate(freecam.actuators["down"])                    
    #            #left
            if lLR > -0.080 and lLR < -0.030:
                freecam.actuators["left"].dLoc = [-camspeed1, 0, 0]                
                cont.activate(freecam.actuators["left"])
            else:
                cont.deactivate(freecam.actuators["left"])                    
    #            #right
            if lLR < .080 and lLR > .03:       
                freecam.actuators["right"].dLoc = [camspeed1, 0, 0]
                cont.activate(freecam.actuators["right"])
            else:
                cont.deactivate(freecam.actuators["right"])  
            #up
            if rUD > -0.080 and rUD < -0.030:
                freecam.actuators["rotup"].dRot = [camrot1, 0, 0]                
                cont.activate(freecam.actuators["rotup"])
            else:
                cont.deactivate(freecam.actuators["rotup"])    
    #            #down    
            if rUD < .080 and rUD > .03:
                freecam.actuators["rotdown"].dRot = [-camrot1, 0, 0]                
                cont.activate(freecam.actuators["rotdown"])
            else:
                cont.deactivate(freecam.actuators["rotdown"])                    
    #            #left
            if rLR > -0.080 and rLR < -0.030:
                freecam.actuators["rotleft"].dRot = [0, 0, camrot1]
                cont.activate(freecam.actuators["rotleft"])
            else:
                cont.deactivate(freecam.actuators["rotleft"])                    
    #            #right
            if rLR < .080 and rLR > .03:         
                freecam.actuators["rotright"].dRot = [0, 0, -camrot1]
                cont.activate(freecam.actuators["rotright"])
            else:
                cont.deactivate(freecam.actuators["rotright"])        
    ########################################                 
        if own['camnum'] == 0:
            cam = camList["Camera.003"]
            scene.active_camera = cam          
        valueIndex = own['valueIndex']
        n = (valueIndex / recording_cutoff) * 1000
        n = int(round(n))
        #n = 10
        #print("n: ", n, "--", valueIndex, recording_cutoff)
        #dict = logic.globalDict #Get the global dictionary
        dict['playhead'] = n 
          
        own['last_back_but'] = own['back_but']           
        own['back_but'] = back_on
        own['last_a_but'] = own['a_but']           
        own['a_but'] = a_on
        own['last_ltsBut'] = ltsBut
        own['last_rtsBut'] = rtsBut
        own['last_playback'] = own['playback']
        dict['playback'] = own['playback']