'===========================================================================
' Subject: MATCH FILENAME W/WILDCARD SPECS    Date: 09-01-98 (15:11)       
'  Author: Dave Navarro, Jr.                  Code: PB                     
'  Origin: dave@powerbasic.com              Packet: PB.ABC
'===========================================================================
'===========================================================================
'                   Source code snippet: PowerBASIC for DOS
'
'           Author: Dave Navarro, Jr.
' Copyright status: Public Domain
'
' Match a filename against a given wild-card filespec.
'
'===========================================================================

Filename$ = "PROGRAM.EXE"
Wildcard$ = "PR?G*.E??"

PRINT Filename$; " = "; Wildcard$; " is ";

IF WildMatchFile(Filename$, Wildcard$) THEN
  PRINT "True"
ELSE
  PRINT "False"
END IF

'===========================================================================
' WildMatchFile -  Match a filename against a valid DOS filespec.  Returns
'                  true if filename matches wildcard specification.
'
' FileName = Name of file to check against wildcard
' WildCard = Wildcard specification to match against the file name
'
FUNCTION WildMatchFile(BYVAL FileName AS STRING, BYVAL WildCard AS STRING)

  DIM FilePos  AS INTEGER
  DIM WildPos  AS INTEGER
  DIM FileByte AS INTEGER
  DIM WildByte AS INTEGER

  '-- "*.*" matches everything --------

  IF WildCard = "*.*" THEN
    WildMatchFile = -1
    EXIT FUNCTION
  END IF

  '-- Convert strings to upper case

  FileName = UCASE$(FileName)
  WildCard = UCASE$(WildCard)

  FilePos = 1
  WildPos = 1

  DO

    '-- Get one byte from each string

    FileByte = ASCII(MID$(FileName, FilePos, 1))
    WildByte = ASCII(MID$(WildCard, WildPos, 1))

    '-- End of wildcard?  See if we have a match

    IF WildPos > LEN(WildCard) THEN
      WildMatchFile = (FilePos >= LEN(FileName))
      EXIT FUNCTION

    ' --- End of filename?  No match

    ELSEIF FilePos > LEN(FileName) THEN
      WildMatchFile = 0
      EXIT FUNCTION

    '-- Do bytes match?  Or is WildByte a question mark?

    ELSEIF (WildByte = FileByte) OR (WildByte = 63) THEN

      INCR WildPos
      INCR FilePos

    '-- Is WildByte an asterisk? (matches everything)

    ELSEIF (WildByte = 42) THEN

      '-- Skip to period or end of filename

      WHILE (FileByte<>32) AND (FileByte<>46) AND (FilePos < LEN(FileName))
        INCR FilePos
        FileByte = ASCII(MID$(FileName, FilePos, 1))
      WEND

      INCR WildPos

    '-- No match, so exit

    ELSE
      WildMatchFile = 0
      EXIT FUNCTION

    END IF

  LOOP

END FUNCTION
