/* ====================================================================
 * Copyright (c) 2003-2007, Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "StringUtil.h"

// qt
#include <QtCore/QString>

namespace sc
{

int compare( const QString& s1, const QString& s2 )
{
  int cnt = 0;

  while( (cnt < s1.size()) && (cnt < s2.size()) )
  //while( !(s1[cnt].isNull()) && !(s2[cnt].isNull()) )
  {
    QChar qc1 = s1[cnt];
    QChar qc2 = s2[cnt];

    bool d1 = qc1.isDigit();
    bool d2 = qc2.isDigit();

    if( d1 && d2 )
    {
      int dCnt1 = 0;
      int dCnt2 = 0;

      // cnt digit characters
      while( cnt+dCnt1 < s1.size() && s1[cnt+dCnt1].isDigit() )
        dCnt1++;
      while( cnt+dCnt2 < s2.size() && s2[cnt+dCnt2].isDigit() )
        dCnt2++;

      // this will break the compare if the numbers are
      // greater than 2^64 ..
      qulonglong n1 = s1.mid( cnt, dCnt1 ).toULongLong();
      qulonglong n2 = s2.mid( cnt, dCnt2 ).toULongLong();

      if( n1 < n2 )
      {
        return -1;
      }
      else if( n1 > n2 )
      {
        return 1;
      }
      else
      {
        // number are equal, so dCnt1 == dCnt2
        // skip number
        cnt += dCnt1;
      }
    }
    else
    {
      if( qc1 < qc2 )
      {
        return -1;
      }
      else if( qc1 > qc2 )
      {
        return 1;
      }
      {
        // equal, check next char
        cnt++;
      }
    }
  }


  if( s1.length() < s2.length() )
  {
    return -1;
  }
  else if( s1.length() > s2.length() )
  {
    return 1;
  }
  else // s1.length() == s2.length()
  {
    return 0;
  }
}


} // namespace
