// Mask.C  -*- C++ -*-
// Copyright (c) 1997, 1998 Etienne BERNARD

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.

#include <string.h>

#include "Mask.H"

Mask::Mask(String s)
  : mask(s)
{ }

String
Mask::getMask()
{
  return mask;
}

bool
Mask::matches(String s)
{
  return match((const char *)mask, (const char *)s);
}

bool
Mask::matches(Mask & m)
{
  return match((const char *)mask, (const char *)m.mask);
}

bool
Mask::match(const char * m, const char * n)
{
  if (!*m) {
    if (!*n)
      return true;
    else
      return false;
  } else
    if (!*n)
      return false;

  if (m[0] == '*') {
    while (*m && (m[0] == '*' || m[0] == '?'))
      m++;
    
    if (*m == '\0')
      return true;
    
    const char *c = n;
    while ((c = strchr(c, *m)) != 0) {
      if (match(m, c))
        return 1;
      c++;
    }
  }

  if ((m[0] == n[0]) ||
      (m[0] == '?') ||
      ((m[0] == '\\') && ((m[1] == '?' && n[0] == '?') ||
                          (m[1] == '*' && n[0] == '*'))))
    return match(++m, ++n);

  return false;
}


syntax highlighted by Code2HTML, v. 0.9.1