/*****************************
File:       PacketSequenceChecker.CPP
Language:   C++ (header)
Project:    H3DNetworkingUtils
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.

The Original Code is H3DNetworkingUtils v1.0.

The Initial Developer of the Original Code is CSIRO.
Portions created by the Initial Developer are Copyright (C) 1009 CSIRO. All Rights Reserved.
Contributor(s):
    Chris Gunn  <Chris.Gunn@csiro.au> <ChrisJGunn@gmail.com>
***************************/
#include "H3DNetworkingUtils/PacketSequenceChecker.h"
#include <iostream>

// Code from http://mirror.aarnet.edu.au/pub/ietf/rfc/rfc1889.txt

using namespace H3DNetworkingUtils;
using namespace std;

const int PacketSequenceChecker::MIN_SEQUENTIAL = 3;
const int PacketSequenceChecker::MAX_ALLOWABLE_DIFF = 4;
const int PacketSequenceChecker::WRAP_CHECK = 65535;

// ------------------------------------------------------
PacketSequenceChecker::PacketSequenceChecker() :
prev_seq_num        (0),
probation      (MIN_SEQUENTIAL)
{
   cout << "PacketSequenceChecker::PacketSequenceChecker" << endl;

}

// ------------------------------------------------------  
bool PacketSequenceChecker::inSequence(u_int16 seq) {
   static u_int32 restart_tries = 0;
  
   // The idea here is:
   // Seq numbers should come in ascending order.
   // If there is a jump of a few numbers, we don't care, just expect sequenced
   // numbers from then on.
   // If the jump is too high, we better check that the sequence is continuing
   // correctly until trusting it.
   // We shouldn't get a 'drop back' in numbers - ignore it.
   // The numbers should wrap around to the start at some stage, mustn't confuse
   // this with a drop back.

   int jump = seq - prev_seq_num;
   //if ((seq > 65440) || (seq < 10)) {
   //   cout << seq << endl;
   //}
   bool ret = false;

   // Source is not valid until MIN_SEQUENTIAL packets with
   // sequential sequence numbers have been received.
   if (probation > 0) {
      if ((jump >= 0) || (jump <= MAX_ALLOWABLE_DIFF) || (jump == -WRAP_CHECK)) {
         probation--;
      }
      prev_seq_num = seq;
      ret = false;
   } else if ((jump <= MAX_ALLOWABLE_DIFF) && (jump > 0)) {
      prev_seq_num = seq;
      ret = true;
   } else if (jump == 0) { // same packet as before, just ignore
      ret = false;
   } else if (jump == -WRAP_CHECK) { // number has wrapped round to 0
      prev_seq_num = seq;
      ret = true;
   } else {
      probation = MIN_SEQUENTIAL;
      prev_seq_num = seq;
      ret = false;
   }
   return ret;
}
