
    script_variables

         bool mSoarInputPrintsOn = false; // gates calls to methods that print debug info from Soar
         bool mSoarOutputPrintsOn = false; // gates calls to methods that print debug info from Soar
         bool mSoarTracePrintsOn = false; // gates calls to methods that print debug info from Soar

         // Inputs to RIPR
         double ownshipSpeed              = 0;
         double ownshipAmmo               = 0;

         double ownshipEngagementRangeMin = 0; // set later GetWeaponRangeMin(PLATFORM, mWeaponArray);
         double ownshipEngagementRangeMax = 0; // set later GetWeaponRangeMax(PLATFORM, mWeaponArray);
         double ownshipClosingSpeedMin    = cCLOSING_SPEED_MIN;
         double ownshipClosingSpeedMax    = cCLOSING_SPEED_MAX;
         double ownshipThreatTolerance    = cTHREAT_TOLERANCE;
         int    ownshipWeaponsIncoming    = 0;

         double weightCurrentTarget       = cWEIGHT_CURRENT_TARGET;
         double weightClosingSpeedOf      = cWEIGHT_CLOSING_SPEED_OF;
         double weightSlantRangeTo        = cWEIGHT_SLANT_RANGE_TO;
         double weightOthersTargeting     = cWEIGHT_OTHERS_TARGETING;
         double weightWeaponsInFlight     = cWEIGHT_WEAPONS_IN_FLIGHT;

         Array<WsfPlatform>     mIncoming               = Array<WsfPlatform>();
         string                 mState                  = "WAIT";
         string                 mOldCommandComment      = "no command";
         WsfRIPRJob             mCurrentJob;
         WsfGeoPoint            mCurrentPointIntercept;

         Map<string,double> mTrackWeaponActiveMap = Map<string,double>();

         string mPursuitMode = "";

         // the following ints are really pointers in C++, so don't change their values!
         int  riprInputLink = 0;
         int  riprOutputLink = 0;
         int  riprInputJob = 0;

         int inpOwnshipSpeed              = 0;
         int inpOwnshipAmmo               = 0;
         int inpOwnshipEngagementRangeMin = 0;
         int inpOwnshipEngagementRangeMax = 0;
         int inpOwnshipClosingSpeedMax    = 0;
         int inpOwnshipClosingSpeedMin    = 0;
         int inpOwnshipThreatTolerance    = 0;
         int inpOwnshipWeaponsIncoming    = 0;

         int inpWeightCurrentTarget       = 0;
         int inpWeightClosingSpeedOf      = 0;
         int inpWeightSlantRangeTo        = 0;
         int inpWeightOthersTargeting     = 0;
         int inpWeightWeaponsInFlight     = 0;

         int inpCurrentTime           = 0;

         int inpPointRoot             = 0;
         int inpTrackRoot             = 0;
         int inpOrdersRoot            = 0;
      end_script_variables





      script void aiai_initialize()

         extern double GetWeaponRangeMax (WsfPlatform, Array<Map<string, Object>>);
         extern double GetWeaponRangeMin (WsfPlatform, Array<Map<string, Object>>);

         ownshipEngagementRangeMin = GetWeaponRangeMin(PLATFORM, mWeaponArray);
         ownshipEngagementRangeMax = GetWeaponRangeMax(PLATFORM, mWeaponArray);

         mTrackWeaponActiveMap = Map<string,double>();


#         // Pass in the agent's name and the Soar watch level we're interested in
#         // 0: proposals and selections
#         // 1: state and operator selected (basically same as level 0)
#         // 2: phases (basically same as level 0)
#         // 3: rule firings and retractions
#         // 4: WME creation and deletion (lots of data)
#         CreateAgent(agentName, 0);
#         bool success = LoadProductions(agentProductions, true);
#         // if the productions fail to load we should abort
#         if (!success)
#         {
#            writeln("Failure to load ", agentProductions);
#         }
#         else
#         {
#            writeln_d("Created agent ", agentName, " with productions ", agentProductions);
#         }
#         writeln_d( "weightCurrentTarget:   ", weightCurrentTarget   );
#         writeln_d( "weightClosingSpeedOf:  ", weightClosingSpeedOf  );
#         writeln_d( "weightSlantRangeTo:    ", weightSlantRangeTo    );
#         writeln_d( "weightOthersTargeting: ", weightOthersTargeting );
#         writeln_d( "weightWeaponsInFlight: ", weightWeaponsInFlight );
#         riprInputLink = GetInputLink();
#         riprOutputLink = 0; // this will be null until after we run to output the first time
#
#         // Create all these WMEs and get back pointers to them
#         extern int GetBucket(double, double);
#         inpOwnshipClosingSpeedMin    = CreateWME(riprInputLink, "ownship-closing-speed-min",    GetBucket(ownshipClosingSpeedMin, cBUCKET_BASE));
#         inpOwnshipClosingSpeedMax    = CreateWME(riprInputLink, "ownship-closing-speed-max",    GetBucket(ownshipClosingSpeedMax, cBUCKET_BASE));
#         inpOwnshipThreatTolerance    = CreateWME(riprInputLink, "ownship-threat-tolerance",     ownshipThreatTolerance);
#         inpCurrentTime               = CreateWME(riprInputLink, "current-time",                 TIME_NOW);
#         inpOwnshipSpeed              = CreateWME(riprInputLink, "ownship-speed",                GetBucket(ownshipSpeed, cBUCKET_BASE));
#         inpOwnshipAmmo               = CreateWME(riprInputLink, "ownship-ammo",                 ownshipAmmo);
#         inpOwnshipEngagementRangeMin = CreateWME(riprInputLink, "ownship-engagement-range-min", GetBucket(ownshipEngagementRangeMin, cBUCKET_BASE));
#         inpOwnshipEngagementRangeMax = CreateWME(riprInputLink, "ownship-engagement-range-max", GetBucket(ownshipEngagementRangeMax, cBUCKET_BASE));
#         inpOwnshipWeaponsIncoming    = CreateWME(riprInputLink, "ownship-weapons-incoming",     ownshipWeaponsIncoming);
#
#         inpWeightCurrentTarget       = CreateWME(riprInputLink, "weight-current-target",        weightCurrentTarget);
#         inpWeightClosingSpeedOf      = CreateWME(riprInputLink, "weight-closing-speed-of",      weightClosingSpeedOf);
#         inpWeightSlantRangeTo        = CreateWME(riprInputLink, "weight-slant-range-to",        weightSlantRangeTo);
#         inpWeightOthersTargeting     = CreateWME(riprInputLink, "weight-others-targeting",      weightOthersTargeting);
#         inpWeightOthersTargeting     = CreateWME(riprInputLink, "weight-weapons-in-flight",     weightWeaponsInFlight);
#
#         inpPointRoot                 = CreateWME(riprInputLink, "point-root");
#         inpTrackRoot                 = CreateWME(riprInputLink, "track-root");
#         inpOrdersRoot                = CreateWME(riprInputLink, "orders-root");
#
#         // Create orders
#         writeln_d("   -Creating orders for ", agentName);
#         int tempWME = 0;
#
#         foreach( string categoryStr : double categoryPriority in ThreatTypePriority )
#         {
#            tempWME = CreateWME(inpOrdersRoot, "prefer-target-type");
#            CreateWME(tempWME, "target-type", categoryStr);
#            CreateWME(tempWME, "weight", categoryPriority);
#         }
#
#         // We must call Commit() after we modify the input link.
#         Commit();

      end_script






      /*
       *  bool UpdateInterceptLocationWithPathing ()
       *
       *       Intercept aTarget.  This should eventually be replaced by methods in the mover.
       */

      script bool UpdateInterceptLocationWithPathing (WsfTrack aTarget, string pursuitMode)
      
         if (aTarget.IsNull())
         {
            writeln_d("    UpdateInterceptLocationWithPathing, aTarget is null");
            return false;
         }

         // If we got the altitude from the TRACK, match it
         //double interceptAltitude = cDEFAULT_ALTITUDE;
         double interceptAltitude = PLATFORM.Altitude();
         double interceptHeading  = PLATFORM.Heading();
         double distanceToTarget  = PLATFORM.SlantRangeTo(aTarget);
         bool useIntercept = false;

         if (aTarget.ElevationValid() || aTarget.LocationValid())
         {
           if (aTarget.Altitude() > interceptAltitude)
           {
             interceptAltitude = aTarget.Altitude();
           }
         }

         if (aTarget.VelocityValid())
         {
            extern double EffectiveRange(WsfPlatform, WsfTrack);

            extern double GetWeaponRangeMax (WsfPlatform, Array<Map<string, Object>>);
            extern double GetWeaponRangeMin (WsfPlatform, Array<Map<string, Object>>);

            double rangeMin = GetWeaponRangeMin(PLATFORM, mWeaponArray);
            double rangeMax = GetWeaponRangeMax(PLATFORM, mWeaponArray);

            double speedOfTarget = aTarget.Speed();
            double effRange      = EffectiveRange(PLATFORM, aTarget);
            double missileWindow = rangeMax - rangeMin;
            double speedWindow   = cINTERCEPT_SPEED - speedOfTarget;

            if (effRange > rangeMax)
            {
               PLATFORM.GoToSpeed(cINTERCEPT_SPEED);
            }
            else if(effRange > rangeMin)
            {
               double rangeScale = (effRange - rangeMin) / missileWindow;
               double desireSpeed = speedOfTarget + (speedWindow * rangeScale);
               PLATFORM.GoToSpeed(desireSpeed);
            }
            else
            {
               PLATFORM.GoToSpeed(speedOfTarget);
            }
         }

         if (1) //aTarget.TargetDamaged() < 1)
         {
            if (pursuitMode == "lead")
            {
               double timeToIntercept = 0.0;
               WsfWaypoint interceptPoint = WsfWaypoint();

               timeToIntercept = PLATFORM.InterceptLocation3D(aTarget, interceptPoint);
               // If timeToIntercept is positive then we know intercept is possible
               if (timeToIntercept > 0.0)
               {
                  writeln_d("    T=", TIME_NOW, " TTI=", timeToIntercept, " range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", interceptPoint.Heading());
                  writeln_d("      lead pursuit: ", interceptPoint.Latitude(), ", ", interceptPoint.Longitude(), ", ", interceptPoint.Altitude());

                  WsfGeoPoint startGeoPoint = PLATFORM.Location();
                  WsfGeoPoint endGeoPoint = aTarget.ReportedLocation();
                  PLATFORM.FindAndSetPath(startGeoPoint, endGeoPoint);
               }
               else
               {
                  writeln_d("    lead pursuit attempt with timeToIntercept < 0");
               }
            }
            else if (pursuitMode == "f-pole")
            {
               extern double MaximizeFPole(WsfPlatform, WsfTrack, double);
               interceptHeading = MaximizeFPole(PLATFORM, aTarget, mFPoleAngle);
               writeln_d("    T=", TIME_NOW, ", range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", PLATFORM.TrueBearingTo(aTarget));
               writeln_d("      ", pursuitMode, " pursuit");
            }
            else
            {
               WsfGeoPoint startGeoPoint = PLATFORM.Location();
               WsfGeoPoint endGeoPoint = aTarget.ReportedLocation();
               PLATFORM.FindAndSetPath(startGeoPoint, endGeoPoint);

               writeln_d("    T=", TIME_NOW, ", range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", PLATFORM.TrueBearingTo(aTarget),
                  " (", endGeoPoint.Latitude(), "/", aTarget.Latitude(), ",", endGeoPoint.Longitude(), "/", aTarget.Longitude(), ")");
               writeln_d("      ", pursuitMode, " pursuit");
            }

            if (MATH.Fabs(interceptAltitude - PLATFORM.Altitude()) > 5)
            {
               writeln_d("GoToAltitude: ",interceptAltitude);
               PLATFORM.GoToAltitude(interceptAltitude);
            }
            return true;
         }
         return false;
      end_script





      /*
       *  bool UpdateInterceptLocation ()
       *
       *       Intercept aTarget.  This should eventually be replaced by methods in the mover.
       */
       
      script bool UpdateInterceptLocation (WsfTrack aTarget, string pursuitMode)
      
         if (aTarget.IsNull())
         {
            writeln_d("    UpdateInterceptLocation, aTarget is null");
            return false;
         }

         // If we got the altitude from the TRACK, match it
         //double interceptAltitude = cDEFAULT_ALTITUDE;
         double interceptAltitude = PLATFORM.Altitude();
         double interceptHeading  = PLATFORM.Heading();
         double distanceToTarget  = PLATFORM.SlantRangeTo(aTarget);
         bool useIntercept = false;

         if (aTarget.ElevationValid() || aTarget.LocationValid())
         {
           if (aTarget.Altitude() > interceptAltitude)
           {
             interceptAltitude = aTarget.Altitude();
           }
         }

         if (aTarget.VelocityValid())
         {
            extern double EffectiveRange(WsfPlatform, WsfTrack);

            extern double GetWeaponRangeMax (WsfPlatform, Array<Map<string, Object>>);
            extern double GetWeaponRangeMin (WsfPlatform, Array<Map<string, Object>>);

            double rangeMin = GetWeaponRangeMin(PLATFORM, mWeaponArray);
            double rangeMax = GetWeaponRangeMax(PLATFORM, mWeaponArray);

            double speedOfTarget = aTarget.Speed();
            double effRange      = EffectiveRange(PLATFORM, aTarget);
            double missileWindow = rangeMax - rangeMin;
            double speedWindow   = cINTERCEPT_SPEED - speedOfTarget;

            if (effRange > rangeMax)
            {
               PLATFORM.GoToSpeed(cINTERCEPT_SPEED);
            }
            else if (effRange > rangeMin)
            {
               double rangeScale = (effRange - rangeMin) / missileWindow;
               double desireSpeed = speedOfTarget + (speedWindow * rangeScale);
               PLATFORM.GoToSpeed(desireSpeed);
            }
            else
            {
               PLATFORM.GoToSpeed(speedOfTarget);
            }
         }

         if (1) //aTarget.TargetDamaged() < 1)
         {
            if (pursuitMode == "lead")
            {
               double timeToIntercept = 0.0;
               WsfWaypoint interceptPoint = WsfWaypoint();

               timeToIntercept = PLATFORM.InterceptLocation3D(aTarget, interceptPoint);
               // If timeToIntercept is positive then we know intercept is possible
               if (timeToIntercept > 0.0)
               {
                  writeln_d("    T=", TIME_NOW, " TTI=", timeToIntercept, " range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", interceptPoint.Heading());
                  writeln_d("      lead pursuit: ", interceptPoint.Latitude(), ", ", interceptPoint.Longitude(), ", ", interceptPoint.Altitude());

                  interceptHeading = interceptPoint.Heading();
                  useIntercept = true;
               }
               else
               {
                  writeln_d("    lead pursuit attempt with timeToIntercept < 0");
               }
            }
            else if (pursuitMode == "f-pole")
            {
               extern double MaximizeFPole(WsfPlatform, WsfTrack, double);
               interceptHeading = MaximizeFPole(PLATFORM, aTarget, mFPoleAngle);
               useIntercept = true;
               writeln_d("    T=", TIME_NOW, ", range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", PLATFORM.TrueBearingTo(aTarget));
               writeln_d("      ", pursuitMode, " pursuit");
            }
            else
            {
               interceptHeading = PLATFORM.TrueBearingTo(aTarget);
               useIntercept = true;

               //writeln_d("    T=", TIME_NOW, ", range: ", PLATFORM.SlantRangeTo(aTarget), " true-bearing: ", PLATFORM.TrueBearingTo(aTarget),
               //   " (", endGeoPoint.Latitude(), "/", aTarget.Latitude(), ",", endGeoPoint.Longitude(), "/", aTarget.Longitude(), ")");
               writeln_d("      ", pursuitMode, " pursuit");
            }

         if (useIntercept)
         {
            //PLATFORM.Comment("USING TURNTOHEADING");
             // Head towards the target using the interceptHeading instead of Pathfinder
            PLATFORM.TurnToHeading(interceptHeading);
         }
         if (MATH.Fabs(interceptAltitude - PLATFORM.Altitude()) > 5)
         {
            writeln_d("GoToAltitude: ",interceptAltitude);
            PLATFORM.GoToAltitude(interceptAltitude);
         }
            return true;
         }

         return false;
      end_script




/*
      // Updates the RIPR SOAR input link with a job & state data
      script int UpdateInputLink(WsfRIPRJob aJob)
        int tempJobPtr = 0; // this will be returned so it can be deleted later
        extern bool TestTrackCategory(WsfTrack, string);
        extern double GetWeaponQuantityRemainingMax(WsfPlatform, Array<Map<string, Object>>);
        // Update the ownship stuff
        ownshipSpeed = PLATFORM.Speed();
        ownshipAmmo = GetWeaponQuantityRemainingMax(PLATFORM, mWeaponArray);
        extern int GetBucket(double, double);
        UpdateWME(inpOwnshipSpeed,                 GetBucket(ownshipSpeed, cBUCKET_BASE));
        UpdateWME(inpOwnshipEngagementRangeMin,    GetBucket(ownshipEngagementRangeMin, cBUCKET_BASE));
        UpdateWME(inpOwnshipEngagementRangeMax,    GetBucket(ownshipEngagementRangeMax, cBUCKET_BASE));
        #UpdateWME(inpOwnshipAmmo,                  ownshipAmmo);
        #UpdateWME(inpCurrentTime,                  TIME_NOW);
        #UpdateWME(inpOwnshipThreatTolerance,       ownshipThreatTolerance);
        #UpdateWME(inpOwnshipWeaponsIncoming,       ownshipWeaponsIncoming);
        writeln_d("    - Feeding job to soar: ", aJob.Name(), ", desc: ", aJob.GetDescription());
        if (aJob.Name() == "pursue-target")
        {
          Map<string, Object>tempData = aJob.GetData();
          string name = (string)tempData["targetTrackName"];
          extern WsfTrack GetTrackByName(WsfPlatform, string);
          WsfTrack track = GetTrackByName(PLATFORM, name);
          // if the track is not a foe or is damaged, we'll ignore it
          if (!(track.IsValid()) || !(track.IFF_Foe()))
          {
            writeln("!!! No track for aJob: ", aJob.Name(), ", ", aJob.GetDescription());
            if (aJob.IsValid())
            {
               // bid the job the maximum negative amount
               aJob.BidJob(PROCESSOR, cMIN_JOB_BID, 0);
            }
            if (track.IsValid())
            {
               writeln("    ", !(track.IsValid()), ", ", !(track.IFF_Foe()), ", ", (track.TargetDamaged() >= 1));
               writeln("    IFF unk, amb, foe, friend: ", track.IFF_Unknown(), track.IFF_Ambiguous(), track.IFF_Foe(), track.IFF_Friend());
            }
            Commit();
            return 0;
          }
          extern string DetermineTrackCategory (WsfTrack);
          string targetType = DetermineTrackCategory(track);
          if (TestTrackCategory(track, "unknown"))
          {
            if (aJob.IsValid())
            {
              // bid the job the maximum negative amount
              aJob.BidJob(PROCESSOR, cMIN_JOB_BID, 0);
            }

            writeln("!!! Target type unknown for current job. ");
            Commit();
            return 0;
          }
          extern string CalculatePositioning(WsfPlatform, WsfTrack, double);
          string positioning = CalculatePositioning(PLATFORM, track, mFPoleAngle);
          double currentlyTargeted = 0;
          if (GetTargetName() == name)
          {
             currentlyTargeted = 1.0;
          }
          // set the target type
          //writeln_d("   -Creating track record for ", name, " -- ", targetType);
          //have to create a new WME
          writeln_d("    Creating WME for track: ", name );
          tempJobPtr = CreateWME(inpTrackRoot, name);
          //create all children WMEs
          CreateWME(tempJobPtr, "target-name", name);
          CreateWME(tempJobPtr, "update-time", track.UpdateTime());
          extern int GetBucket(double, double);
          CreateWME(tempJobPtr, "speed", GetBucket(track.Speed(), cBUCKET_BASE));
          CreateWME(tempJobPtr, "slant-range-to", GetBucket(PLATFORM.SlantRangeTo(track), cBUCKET_BASE));
          CreateWME(tempJobPtr, "positioning", positioning);
        }
        // Commit our input link
        Commit();
        return tempJobPtr;
      end_script
*/




      // This script calls the Soar agent and then returns a string indicating the next state to enter
      
      script string Think()

        extern double GetWeaponQuantityRemainingMax(WsfPlatform,Array<Map<string, Object>>);
        double wRemaining = GetWeaponQuantityRemainingMax(PLATFORM, mWeaponArray);
        if (wRemaining < 1)
        {
			writeln_d("   no weapons left, WAITing");
			return "WAIT";
        }else {
			writeln_d("   weapons left: ", wRemaining);
        }

        writeln_d("    Jobs:");

        Array<WsfRIPRJob> jobs = GetRIPRCommanderProcessor().GetJobs();
        writeln_d("    (fetched)");

// bid on jobs

        foreach (WsfRIPRJob aJob in jobs)
        {
          double current_bid = 0;
          writeln_d("    - ", aJob.Name(), ", desc: ", aJob.GetDescription());

          if (aJob.Name() == "pursue-target")
          {
            Map<string, Object>tempData = aJob.GetData();
            string name = (string)tempData["targetTrackName"];
            extern WsfTrack GetTrackByName(WsfPlatform, string);
            WsfTrack track = GetTrackByName(PLATFORM, name);

            // if the track is not a foe or is damaged, we'll ignore it
            if (!(track.IsValid()) || !(track.IFF_Foe()))
            {
              writeln("!!! No track for aJob: ", aJob.Name(), ", ", aJob.GetDescription());
              if (aJob.IsValid())
              {
                 // bid the job the maximum negative amount
                 aJob.BidJob(PROCESSOR, cMIN_JOB_BID, 0);
              }

              if (track.IsValid())
              {
                 writeln("    ", !(track.IsValid()), ", ", !(track.IFF_Foe()), ", ", (track.TargetDamaged() >= 1));
                 writeln("    IFF unk, amb, foe, friend: ", track.IFF_Unknown(), track.IFF_Ambiguous(), track.IFF_Foe(), track.IFF_Friend());
              }

              continue;
            }

            extern string DetermineTrackCategory (WsfTrack);

            string targetType = DetermineTrackCategory(track);

            //writeln_d("      track category: ",targetType);

            extern bool TestTrackCategory(WsfTrack, string);

            if (TestTrackCategory(track, "unknown"))
            {
              if( aJob.IsValid() )
              {
                // bid the job the maximum negative amount
                aJob.BidJob(PROCESSOR, cMIN_JOB_BID, 0);
              }

              writeln("!!! Target type unknown for current job. ");
              continue;
              //Commit();
              //return false;
            }

            extern string CalculatePositioning(WsfPlatform, WsfTrack, double);
            string positioning = CalculatePositioning(PLATFORM, track, mFPoleAngle);

            int othersTargeting = GetRIPRCommanderProcessor().SubsTargeting( track, PLATFORM );
            writeln_d("      Others Targeting: ", othersTargeting );

            double currentlyTargeted = 0;

            if (GetTargetName() == name)
            {
               currentlyTargeted = 1.0;
            }
            writeln_d("      Currently Targeted: ", currentlyTargeted );

            // set the target type
            //writeln_d("   -Creating track record for ", name, " -- ", targetType);
            //writeln_d("      track closing speed: ", PLATFORM.ClosingSpeedOf(track) );
            //writeln_d("      track slant range: ", PLATFORM.SlantRangeTo(track) );
            
            // account for bidding parameters
            extern int GetBucket(double, double);
            //writeln_d("      GetBucket(track closing speed): ", GetBucket(PLATFORM.ClosingSpeedOf(track), cBUCKET_BASE) );
            //writeln_d("      GetBucket(track slant range): ", GetBucket(PLATFORM.SlantRangeTo(track), cBUCKET_BASE) );

            current_bid = current_bid + weightCurrentTarget * currentlyTargeted;
            current_bid = current_bid + weightClosingSpeedOf * GetBucket(PLATFORM.ClosingSpeedOf(track), cBUCKET_BASE);
            current_bid = current_bid + weightSlantRangeTo * GetBucket(PLATFORM.SlantRangeTo(track), cBUCKET_BASE);
            current_bid = current_bid + weightOthersTargeting * othersTargeting;
            current_bid = current_bid + weightWeaponsInFlight * PROCESSOR.WeaponsActive(track);

            if( ThreatTypePriority.Exists( targetType ) )
            {
              current_bid = current_bid + ThreatTypePriority.Get( targetType );
            }
          }
          else if( aJob.Name() == "pursue-point" )
          {
            Map<string, Object>tempData = aJob.GetData();
            string name = (string)tempData["targetTrackName"];

            WsfGeoPoint point = (WsfGeoPoint)tempData["targetPoint"];

            if( ! point.IsValid() ) {
              if( aJob.IsValid() ) {
                // bid the job the maximum negative amount
                aJob.BidJob(PROCESSOR, cMIN_JOB_BID, 0);
              }
              writeln("!!! Invalid point for current job: ",aJob.Name(), ", ", aJob.GetDescription() );
              continue;
            }

            // account for bidding parameters
            extern int GetBucket(double, double);
            current_bid = current_bid + weightSlantRangeTo * GetBucket(PLATFORM.SlantRangeTo(point), cBUCKET_BASE);
          }

          aJob.BidJob(PROCESSOR, current_bid, 0);
          writeln_d("      bidding: ", current_bid);
        }

// win a job
        // now check the board to see what we've won!
        mCurrentJob = GetRIPRCommanderProcessor().GetJobFor(TIME_NOW, PROCESSOR);

         if (!(mCurrentJob.IsValid()))
         {
            writeln_d("    no valid job from job board, WAITing");
            return "WAIT";
         }

         string commandComment = "Job: " + mCurrentJob.Name() + ", " + mCurrentJob.GetDescription(); // + " pursuit-mode: " + mPursuitMode;
         writeln_d("    - ", commandComment);

         if (commandComment != mOldCommandComment)
         {
           PLATFORM.Comment(commandComment);
           mOldCommandComment = commandComment;
         }

// execute job

        // Clear the variables we'll use to store the agent's output
        ClearTarget();

        if (mCurrentJob.Name() == "pursue-target")
        {
          extern int      GetBucket             (double, double);
          extern WsfTrack GetTrackByName        (WsfPlatform, string);
          extern bool     TestTrackCategory     (WsfTrack, string);
          extern string   CalculatePositioning  (WsfPlatform, WsfTrack, double);
          extern string   DetermineTrackCategory(WsfTrack);
          
          Map<string, Object> tempData    = mCurrentJob.GetData();
          string              targetName  = (string)tempData["targetTrackName"];
          WsfTrack            targetTrack = GetTrackByName(PLATFORM, targetName);
          
          if (targetTrack.IsValid())
          {
            writeln_d("    Setting target to ", targetName, ", type: ", DetermineTrackCategory(targetTrack));
            SetTarget(targetName);
          }
          else
          {
            writeln_d("    No track found for target named ", targetName);
            ClearTarget();
          }
          
          //get target from ripr processor, to be sure
          targetTrack = GetTarget();

          if (!targetTrack.IsValid()  ||
              !targetTrack.IFF_Foe()  ||
              TestTrackCategory(targetTrack, "unknown"))
          {
            writeln_d("    No valid target set yet, continue to WAIT.");
            return "WAIT";
          }

          double ownSpeed       = GetBucket(PLATFORM.Speed(), cBUCKET_BASE);
          double engageRangeMin = GetBucket(ownshipEngagementRangeMin, cBUCKET_BASE);
          double engageRangeMax = GetBucket(ownshipEngagementRangeMax, cBUCKET_BASE);
          double slantRangeTo   = GetBucket(PLATFORM.SlantRangeTo(targetTrack), cBUCKET_BASE);
          double targetSpeed    = GetBucket(targetTrack.Speed(), cBUCKET_BASE);
          string positioning    = CalculatePositioning(PLATFORM, targetTrack, mFPoleAngle);
          int    weaponsActive  = WeaponsActive(targetTrack);

          if (weaponsActive > 0)
          {
            mPursuitMode = "f-pole";
          }
          else if (slantRangeTo >= engageRangeMax &&
                   positioning  != "head-to-head" &&
                   positioning  != "head-to-tail" &&
                   targetSpeed  >= ownSpeed)
          {
            mPursuitMode = "lead";
          }
          else if (slantRangeTo <= engageRangeMax &&
                   positioning  != "head-to-head" &&
                   positioning  != "head-to-tail")
          {
            mPursuitMode = "lag";
          }
          else if (slantRangeTo  > engageRangeMax ||
                   (slantRangeTo <= engageRangeMax &&
                    (positioning  == "head-to-head" ||
                     positioning  == "head-to-tail")))
          {
            mPursuitMode = "pure";
          }
          else
          {
            mPursuitMode = "pure";
          }

          //target is valid if this line is reached
          //pursuit mode should be set, its a go
          return "INTERCEPT";


          #int targetWme = UpdateInputLink(mCurrentJob);
          #if (targetWme == 0)
          #{
          #  return "WAIT";
          #}
          #
          #// Print out the input link
          #if (mSoarInputPrintsOn)
          #{
          #  writeln("    - Input link:");
          #  PrintTree(riprInputLink);
          #}
          #// Run the agent and print the trace
          #writeln_d("Running to output...");
          #RunSelfTilOutput(); // til output or 15 decision cycles
          #if (mSoarTracePrintsOn)
          #{
          #   PrintTrace();
          #}
          #// Get the output link and print it out
          #riprOutputLink = GetOutputLink();
          #if (mSoarOutputPrintsOn)
          #{
          #   writeln("    - Output link:");
          #   PrintTree(riprOutputLink);
          #   writeln("--------------------------");
          #}
          #// Get the number of commands on the output link
          #int numberCommands = GetNumberCommands();
          #writeln_d("    numberCommands: ", numberCommands);
          #
          #// Loop on the commands and bid on them
          #// (just one command now, haha, no loop necessary)
          #for (int i = 0; i < numberCommands; i=i+1)
          #{
          #   string outTargetName = "";
          #   string outPursuitMode = "";
          #   double outJobBid = 0;
          #   string commandName = GetCommandName(i);
          #
          #   if (commandName == "pursue-target")
          #   {
          #      // Pursue who?  How?
          #      outTargetName = GetCommandValue(i, "target-name");
          #      outPursuitMode = GetCommandValue(i, "pursuit-mode");
//        #        outJobBid = (double)GetCommandValue(i, "job-bid");
          #      mPursuitMode = outPursuitMode;
          #
          #      writeln_d("    T: ", TIME_NOW, " commandName: ", commandName, ", target-name: ", outTargetName, " pursuit-mode: ", outPursuitMode);//, ", bid: ", outJobBid);
          #
          #      WsfRIPRJob temp = GetRIPRCommanderProcessor().GetJobByData("targetTrackName", outTargetName);
          #   }
          #   else
          #   {
          #      writeln("!!! Invalid command: ", commandName);
          #   }
          #
          #   // Then mark the command as completed
          #   AddStatusComplete(i);
          #}
          #DestroyWME((int)targetWme);
          
        }

        // Clear the variables we'll use to store the agent's output
        ClearTarget();
        
        
        

        // If we're supposed to fly towards a point, go for it!
        if (mCurrentJob.Name() == "pursue-point")
        {
          Map<string,Object> tempData = mCurrentJob.GetData();
          mCurrentPointIntercept = (WsfGeoPoint)tempData["targetPoint"];
          return "POINT";
        }

        // If we don't have a target, just keep waiting
        return "WAIT";
      end_script




      script bool CheckAndFire (WsfTrack aTarget)

         bool launched = false;

         if (aTarget.IsNull())
         {
            writeln_d("    No target to fire on");
            return launched;
         }

         if (WeaponsActive(aTarget) > 0)
         {
            mLastActiveWeaponTime   = TIME_NOW;
            mTrackWeaponActiveMap[aTarget.TargetName()] = TIME_NOW;
            writeln_d("    Weapons already active against ", aTarget.TargetName());
            return launched;
         }

         //if ((TIME_NOW - mLastActiveWeaponTime) < mInactiveLaunchDelay)
         if ((TIME_NOW - mTrackWeaponActiveMap[aTarget.TargetName()]) < mInactiveLaunchDelay)
         {
            writeln_d("    Waiting to see what last active weapon did, score a kill?");
            return launched;
         }

         writeln_d("    CheckAndFire() against: ", aTarget.TargetName(), " Index: ", aTarget.TargetIndex(), " Type: ", aTarget.TargetType());

         // We can launch once we have a target-quality track.
         //TODO probably need something to test for failure to lockon
         writeln_d ("    aTarget.TrackQuality == ", aTarget.TrackQuality());

         if (aTarget.TrackQuality() > cLAUNCH_TQ && MATH.Fabs(PLATFORM.RelativeBearingTo( aTarget )) < mMaxFiringAngle)
         {
            // Launch the weapon.  Returns false if not launched.
            extern bool LaunchWeapon(WsfPlatform, WsfTrack, WsfWeapon);
            extern string GetBestWeapon(WsfPlatform, WsfTrack, Array<Map<string, Object>>, double);
            string selectedWeapon = GetBestWeapon(PLATFORM, aTarget, mWeaponArray, mLaunchPercentRangeMax);

            if (selectedWeapon == "")
            {
               writeln_d("    No weapon available");
               return launched;
            }
            
            WsfWeapon weaponToLaunch = PLATFORM.Weapon(selectedWeapon);
            
            extern int GetWeaponNumberActiveMax(string, Array<Map<string, Object>>);
            if (WeaponsActiveOfType(weaponToLaunch) >= GetWeaponNumberActiveMax(selectedWeapon,mWeaponArray))
            {
               writeln_d("    Max number of ", selectedWeapon, " weapon type are already active!");
               return launched;
            }

            launched = LaunchWeapon(PLATFORM, aTarget, weaponToLaunch);

            writeln_d("    launched == ", launched, ", weapon: ", selectedWeapon);

            if (launched == true)
            {
               mLastWeaponFiredTime = TIME_NOW;

               writeln_d("    F-pole after shot fired");
               PLATFORM.Comment("Fired " + selectedWeapon + " at " + aTarget.TargetName());
               mPursuitMode = "f-pole";
               writeln_d("    mPursuitMode == ", mPursuitMode);
            }
         }

         return launched;
      end_script






      // These Transition methods are intended to handle any bookkeeping required when changing
      // into a certain state.

      script void TransitionToWAIT(bool resumeDefaultRoute)
      
         if (resumeDefaultRoute)
         {
            //PLATFORM.GoToLocation(0, 0, 0); // trying to trick mover so next FollowRoute works right
            PLATFORM.FollowRoute("DEFAULT_ROUTE", "CLOSEST_POINT");
         }

         PROCESSOR.SetUpdateInterval(cSLOW_UPDATE_RATE);
         PLATFORM.GoToSpeed(cWAIT_SPEED);             //stay at wait speed
         PLATFORM.GoToAltitude(PLATFORM.Altitude());	//stay at same altitude
         PLATFORM.TurnToHeading(PLATFORM.Heading());  //stay at same heading
         
         ownshipThreatTolerance = cTHREAT_TOLERANCE;
         writeln_d("    Transition to WAIT due to Think()");
      end_script


      script void TransitionToINTERCEPT(WsfTrack aTarget, string pursuitMode)
         PROCESSOR.SetUpdateInterval(cFAST_UPDATE_RATE);
         PLATFORM.GoToSpeed(cINTERCEPT_SPEED);
         ownshipThreatTolerance = cTHREAT_TOLERANCE;
         writeln_d("    Transition to INTERCEPT due to pursuing ", aTarget.TargetName(), " mode ", pursuitMode);
      end_script


      script void TransitionToPOINT()
         PROCESSOR.SetUpdateInterval(cSLOW_UPDATE_RATE);
         PLATFORM.GoToSpeed(cINTERCEPT_SPEED);
         ownshipThreatTolerance = cTHREAT_TOLERANCE;
         writeln_d("    Transition to pursue POINT!");
      end_script


      script void TransitionToEVADE_INCOMING()
         PROCESSOR.SetUpdateInterval(cFAST_UPDATE_RATE);
         PLATFORM.GoToSpeed(cINTERCEPT_SPEED);
         ownshipThreatTolerance = cTHREAT_TOLERANCE;
         writeln_d("    Transition to EVADE_INCOMING");
      end_script




      script void aiai_update()

         extern bool TestTrackCategory(WsfTrack, string);

         //double duration = 0.0;
         //double lStartTime = GetWallClockTime();
         mIncoming = Array<WsfPlatform>(); // clear the existing incoming weapons
         ownshipWeaponsIncoming = WeaponsIncoming(mIncoming);

         writeln_d("--- on_update Platform: ", PLATFORM.Name(), ", State: ", mState, ", Time: ", TIME_NOW);

         //just so I know when this part starts
         //GetFollowingFormationIndex();

         string oldState = mState;

         if (ownshipWeaponsIncoming > 0)
         {
            mState = "EVADE_INCOMING";
         }
         // If we've got enough fuel, keep thinking.
         else if (PLATFORM.FuelRemaining() < PLATFORM.FuelBingoQuantity())
         {
            mState = "BINGO_FUEL";
         }
         else
         {
            // Hmmm what should we do?
            mState = Think();
            
#            if ((1.0/(TIME_NOW-mLastTimeSoarCalled)) <= GetSoarCallRate())
#            {
#               mLastTimeSoarCalled = TIME_NOW + ((MATH.RandomUniform() - 0.5) / 5);
#               mState = Think();
#            }
         }

         if (oldState != mState)
         {
            PLATFORM.Comment("State: " + oldState + " --> " + mState);
         }

         if (mState == "POINT")
         {
            if (oldState != "POINT")
            {
              TransitionToPOINT();
            }

            if (mUsePathFinder)
            {
              extern bool UpdatePointInterceptLocationWithPathing(WsfPlatform, WsfGeoPoint);
              UpdatePointInterceptLocationWithPathing (PLATFORM, mCurrentPointIntercept);
            }
            else
            {
              extern bool UpdatePointInterceptLocation(WsfPlatform, WsfGeoPoint);
              UpdatePointInterceptLocation (PLATFORM, mCurrentPointIntercept);
            }

            //duration = GetWallClockTime() - lStartTime;
            //writeln_d("--- on_update Platform: ", PLATFORM.Name(), ", Process Time: ", duration);
            return;
         }

         WsfTrack curTarget = GetTarget();

         string targetType;

         // Process our state
         if (mState == "EVADE_INCOMING")
         {
            if (oldState != "EVADE_INCOMING")
            {
               TransitionToEVADE_INCOMING();
            }

            CheckAndFire(curTarget);

            writeln_d("    Evading incoming");
            extern bool EvadeIncoming(WsfPlatform, WsfAIAIProcessor);
            EvadeIncoming(PLATFORM, PROCESSOR);
            //duration = GetWallClockTime() - lStartTime;
            //writeln_d("--- on_update Platform: ", PLATFORM.Name(), ", Process Time: ", duration);
            return;
         }

         if (TestTrackCategory(curTarget, "unknown"))
         {
            writeln_d("    curTarget unknown or not valid, default mode to WAIT.");
              mState = "WAIT";
         }

         if (mState == "INTERCEPT")
         {
            if (oldState != "INTERCEPT")
            {
               TransitionToINTERCEPT( curTarget, mPursuitMode );
            }

            CheckAndFire(curTarget);

            // Our track quality may not be good enough yet, so keep moving towards the target.
            if (mUsePathFinder)
            {
              UpdateInterceptLocationWithPathing (curTarget, mPursuitMode);
            }else {
              UpdateInterceptLocation (curTarget, mPursuitMode);
            }


            WsfAIFLProcessor lCommander = (WsfAIFLProcessor)GetRIPRCommanderProcessor();

            // after we've fired on primary target, look for other targets of opportunity
            if (WeaponsActive( curTarget ) > 0)
            {
               //don't fire instantly on all possible targets, give delay
               if ((TIME_NOW - mLastWeaponFiredTime) > mLaunchWeaponDelay)
               {
                  WsfLocalTrackList possibleTargets =  lCommander.FlightTrackList();
                  WsfTrack extraTarget;
                  double extraTargetPriority = -MATH.DOUBLE_MAX();
                  
                  //determine which existing targets are candidates to be fired upon
                  foreach (WsfTrack possibleTarget in possibleTargets)
                  {
                     if (possibleTarget.IsValid() && !TestTrackCategory(possibleTarget,"unknown"))
                     {
                        if (PeersWeaponsActive( possibleTarget ) <= 0 && PeersTargeting( possibleTarget ) <= 0)
                        {
                           WsfTrackId tid = possibleTarget.TrackId();
                           writeln_d("    Looking to fire on: ", tid.Name(), ".", tid.Number(), " -> ", possibleTarget.TargetName());

                           //must be within reasonable radar tracking angles
                           if (MATH.Fabs( PLATFORM.RelativeBearingTo( possibleTarget ) ) < mMaxFiringAngle)
                           {
                              //don't fire last weapon at target thats not primary target
                              extern double GetWeaponQuantityRemainingMax(WsfPlatform, Array<Map<string, Object>>);
                              if (GetWeaponQuantityRemainingMax(PLATFORM, mWeaponArray) > 1)
                              {
                                 extern double GetWeaponRangeMax (WsfPlatform, Array<Map<string, Object>>);
                                 double rangeMax = GetWeaponRangeMax(PLATFORM, mWeaponArray);
                                 //must be within max missile range
                                 if (PLATFORM.SlantRangeTo( possibleTarget ) < rangeMax) // < (mMissileRangeMax*mLaunchPercentRangeMax) )
                                 {
                                    extern string DetermineTrackCategory(WsfTrack);
                                    string targetType = DetermineTrackCategory(possibleTarget);
                                    if (ThreatTypePriority.Exists(targetType))
                                    {
                                       double tempP = ThreatTypePriority.Get(targetType);
                                       if (tempP > extraTargetPriority)
                                       {
                                          extraTargetPriority = tempP;
                                          extraTarget = possibleTarget;
                                       }
                                    }
                                 }
                              }
                           }
                        }
                     }
                  }
                  
                  if (extraTarget.IsValid())
                  {
                     CheckAndFire(extraTarget);
                  }
               }
            }

            writeln_d("    Heading: ", PLATFORM.Heading (), " Altitude: ", PLATFORM.Altitude (), " Speed: ", PLATFORM.Speed());
            writeln_d("        (", PLATFORM.Latitude(), ", ", PLATFORM.Longitude(), ", ", PLATFORM.Altitude(), ")");
            //duration = GetWallClockTime() - lStartTime;
            //writeln_d("--- on_update Platform: ", PLATFORM.Name(), ", Process Time: ", duration);
            return;
         }
         else if (mState == "BINGO_FUEL")
         {
            writeln_d("   bingo_fuel, return to base or something");
            PLATFORM.Comment("Bingo fuel");
            PLATFORM.GoToSpeed(0);
         }
         else //if (mState == "WAIT")
         {
            mState = "WAIT";
            if (oldState != "WAIT")
            {
               TransitionToWAIT(false);	//LBM try this
               //TransitionToWAIT(true);
            }
         }

         //duration = GetWallClockTime() - lStartTime;
         //writeln_d("--- on_update Platform: ", PLATFORM.Name(), ", Process Time: ", duration);

      end_script
