System.Directory___DTString

// ==++==
// 
//   
//    Copyright (c) 2002 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
// 
// ==--==
////////////////////////////////////////////////////////////////////////////
//
//  Class:    DateTimeParse
//
//
//  Purpose:  This class is called by DateTime to parse a date/time string.
//
//  Date:     July 8, 1999
//
////////////////////////////////////////////////////////////////////////////


namespace System {
    using System;
    using System.Text;
    using System.Globalization;
    using System.Threading;
    using System.Collections;

    ////////////////////////////////////////////////////////////////////////
    /*
     NOTENOTE                     :


     There are some nasty cases in the parsing of date/time:

     0x438    fo  (country:Faeroe Islands, languge:Faeroese)
        LOCALE_STIME=[.]
        LOCALE_STIMEFOR=[HH.mm.ss]
        LOCALE_SDATE=[-]
        LOCALE_SSHORTDATE=[dd-MM-yyyy]
        LOCALE_SLONGDATE=[d. MMMM yyyy]

        The time separator is ".", However, it also has a "." in the long date format.

     0x437: (country:Georgia, languge:Georgian)
        Short date: dd.MM.yy
        Long date:  yyyy ???? dd MM, dddd

        The order in long date is YDM, which is different from the common ones: YMD/MDY/DMY.

     0x0404: (country:Taiwan, languge:Chinese)
        LOCALE_STIMEFORMAT=[tt hh:mm:ss]

        When general date is used, the pattern is "yyyy/M/d tt hh:mm:ss". Note that the "tt" is after "yyyy/M/d".
        And this is different from most cultures.

     0x0437: (country:Georgia, languge:Georgian)
        Short date: dd.MM.yy
        Long date:  yyyy ???? dd MM, dddd

     0x0456:        
     */
    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////
    /*
     */
    ////////////////////////////////////////////////////////////////////////
    //This class contains only static members and does not require the serializable attribute.
    
    internal 
    class DateTimeParse {
        private static String alternativeDateSeparator = "-";
        private static DateTimeFormatInfo invariantInfo = DateTimeFormatInfo.InvariantInfo;

        //
        // This is used to cache the lower-cased month names of the invariant culture.
        //
        private static String[] invariantMonthNames = null;
        private static String[] invariantAbbrevMonthNames = null;

        //
        // This is used to cache the lower-cased day names of the invariant culture.
        //
        private static String[] invariantDayNames = null;
        private static String[] invariantAbbrevDayNames = null;

        private static String invariantAMDesignator = invariantInfo.AMDesignator;
        private static String invariantPMDesignator = invariantInfo.PMDesignator;

        private static DateTimeFormatInfo m_jajpDTFI = null;
        private static DateTimeFormatInfo m_zhtwDTFI = null;

        internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) {
            if (s == null || format == null) {
                throw new ArgumentNullException((s == null ? "s" : "format"),
                    Environment.GetResourceString("ArgumentNull_String"));
            }

            if (s.Length == 0) {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            
            if (format.Length == 0) {
                throw new FormatException(Environment.GetResourceString("Format_BadFormatSpecifier"));
            }
            
            if (dtfi == null)
            {
                dtfi = DateTimeFormatInfo.CurrentInfo;
            }

            DateTime result;
            if (DoStrictParse(s, format, style, dtfi, true, out result)) {
                return (result);
            }
            //
            // This is just used to keep compiler happy.
            // This is because DoStrictParse() alwyas does either:
            //      1. Return true or
            //      2. Throw exceptions if there is error in parsing.
            // So we will never get here.
            //
            return (new DateTime());
        }

        internal static bool ParseExactMultiple(String s, String[] formats, 
                                                DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) {
            if (s == null || formats == null) {
                throw new ArgumentNullException((s == null ? "s" : "formats"),
                    Environment.GetResourceString("ArgumentNull_String"));
            }

            if (s.Length == 0) {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }

            if (formats.Length == 0) {
                throw new FormatException(Environment.GetResourceString("Format_BadFormatSpecifier"));
            }

            if (dtfi == null) {
                dtfi = DateTimeFormatInfo.CurrentInfo;
            }

            //
            // Do a loop through the provided formats and see if we can parse succesfully in 
            // one of the formats.
            //
            for (int i = 0; i < formats.Length; i++) {
                if (formats[i] == null || formats[i].Length == 0) {
                    throw new FormatException(Environment.GetResourceString("Format_BadFormatSpecifier"));
                }
                if (DoStrictParse(s, formats[i], style, dtfi, false, out result)) {
                    return (true);
                } 
            }
            result = new DateTime(0);
            return (false);
        }

        ////////////////////////////////////////////////////////////////////////////
        //
        // separator types
        //
        ////////////////////////////////////////////////////////////////////////////

        private const int SEP_Unk        = 0;    // Unknown separator.
        private const int SEP_End        = 1;    // The end of the parsing string.
        private const int SEP_Space      = 2;    // Whitespace (including comma).
        private const int SEP_Am         = 3;    // AM timemark.
        private const int SEP_Pm         = 4;    // PM timemark.
        private const int SEP_Date       = 5;    // date separator.
        private const int SEP_Time       = 6;    // time separator.
        private const int SEP_YearSuff   = 7;    // Chinese/Japanese/Korean year suffix.
        private const int SEP_MonthSuff  = 8;    // Chinese/Japanese/Korean month suffix.
        private const int SEP_DaySuff    = 9;    // Chinese/Japanese/Korean day suffix.
        private const int SEP_HourSuff   = 10;   // Chinese/Japanese/Korean hour suffix.
        private const int SEP_MinuteSuff = 11;   // Chinese/Japanese/Korean minute suffix.
        private const int SEP_SecondSuff = 12;   // Chinese/Japanese/Korean second suffix.
        private const int SEP_LocalTimeMark = 13;   // 'T'
        private const int SEP_Max        = 14;


        ////////////////////////////////////////////////////////////////////////////
        // Date Token Types (DTT_*)
        //
        // Following is the set of tokens that can be generated from a date
        // string. Notice that the legal set of trailing separators have been
        // folded in with the date number, and month name tokens. This set
        // of tokens is chosen to reduce the number of date parse states.
        //
        ////////////////////////////////////////////////////////////////////////////

        private const int DTT_End        = 0;    // '/0'
        private const int DTT_NumEnd     = 1;    // Num[ ]*[/0]
        private const int DTT_NumAmpm    = 2;    // Num[ ]+AmPm
        private const int DTT_NumSpace   = 3;    // Num[ ]+^[Dsep|Tsep|'0/']
        private const int DTT_NumDatesep = 4;    // Num[ ]*Dsep
        private const int DTT_NumTimesep = 5;    // Num[ ]*Tsep
        private const int DTT_MonthEnd   = 6;    // Month[ ]*'/0'
        private const int DTT_MonthSpace = 7;    // Month[ ]+^[Dsep|Tsep|'/0']
        private const int DTT_MonthDatesep=8;    // Month[ ]*Dsep
        private const int DTT_NumDatesuff= 9;    // Month[ ]*DSuff
        private const int DTT_NumTimesuff= 10;   // Month[ ]*TSuff
        private const int DTT_DayOfWeek  = 11;   // Day of week name
        private const int DTT_YearSpace    = 12;   // Year+^[Dsep|Tsep|'0/']
        private const int DTT_YearDateSep= 13;  // Year+Dsep
        private const int DTT_YearEnd    = 14;  // Year+['/0']
        private const int DTT_TimeZone   = 15;  // timezone name
        private const int DTT_Era       = 16;  // era name
        private const int DTT_NumUTCTimeMark = 17;      // Num + 'Z'
        // When you add a new token which will be in the
        // state table, add it after DTT_NumLocalTimeMark.
        private const int DTT_Unk        = 18;   // unknown
        private const int DTT_NumLocalTimeMark = 19;    // Num + 'T'
        private const int DTT_Max        = 20;   // marker


        private const int TM_AM      = 0;
        private const int TM_PM      = 1;

        //
        // Year/Month/Day suffixes
        //
        private const String CJKYearSuff             = "/u5e74";
        private const String CJKMonthSuff            = "/u6708";
        private const String CJKDaySuff              = "/u65e5";

        private const String KoreanYearSuff          = "/ub144";
        private const String KoreanMonthSuff         = "/uc6d4";
        private const String KoreanDaySuff           = "/uc77c";


        private const String CJKHourSuff             = "/u6642";
        private const String ChineseHourSuff         = "/u65f6";

        private const String CJKMinuteSuff           = "/u5206";
        private const String CJKSecondSuff           = "/u79d2";

        private const String LocalTimeMark           = "T";

        ////////////////////////////////////////////////////////////////////////////
        //
        // DateTime parsing state enumeration (DS_*)
        //
        ////////////////////////////////////////////////////////////////////////////

        private const int DS_BEGIN   = 0;
        private const int DS_N       = 1;        // have one number
        private const int DS_NN      = 2;        // have two numbers

        // The following are known to be part of a date

        private const int DS_D_Nd    = 3;        // date string: have number followed by date separator
        private const int DS_D_NN    = 4;        // date string: have two numbers
        private const int DS_D_NNd   = 5;        // date string: have two numbers followed by date separator

        private const int DS_D_M     = 6;        // date string: have a month
        private const int DS_D_MN    = 7;        // date string: have a month and a number
        private const int DS_D_NM    = 8;        // date string: have a number and a month
        private const int DS_D_MNd   = 9;        // date string: have a month and number followed by date separator
        private const int DS_D_NDS   = 10;       // date string: have one number followed a date suffix.

        private const int DS_D_Y        = 11;        // date string: have a year.
        private const int DS_D_YN    = 12;        // date string: have a year and a number
        private const int DS_D_YM    = 13;        // date string: have a year and a month

        private const int DS_D_S     = 14;       // have numbers followed by a date suffix.
        private const int DS_T_S     = 15;       // have numbers followed by a time suffix.

        // The following are known to be part of a time

        private const int DS_T_Nt    = 16;          // have num followed by time separator
        private const int DS_T_NNt   = 17;       // have two numbers followed by time separator


        private const int DS_ERROR   = 18;

        // The following are terminal states. These all have an action
        // associated with them; and transition back to DS_BEGIN.

        private const int DS_DX_NN   = 19;       // day from two numbers
        private const int DS_DX_NNN  = 20;       // day from three numbers
        private const int DS_DX_MN   = 21;       // day from month and one number
        private const int DS_DX_NM   = 22;       // day from month and one number
        private const int DS_DX_MNN  = 23;       // day from month and two numbers
        private const int DS_DX_DS   = 24;       // a set of date suffixed numbers.

        private const int DS_DX_DSN  = 25;       // day from date suffixes and one number.
        private const int DS_DX_NDS  = 26;       // day from one number and date suffixes .
        private const int DS_DX_NNDS = 27;       // day from one number and date suffixes .

        private const int DS_DX_YNN = 28;       // date string: have a year and two number
        private const int DS_DX_YMN = 29;       // date string: have a year, a month, and a number.
        private const int DS_DX_YN  = 30;       // date string: have a year and one number
        private const int DS_DX_YM  = 31;       // date string: have a year, a month.

        private const int DS_TX_N    = 32;       // time from one number (must have ampm)
        private const int DS_TX_NN   = 33;       // time from two numbers
        private const int DS_TX_NNN  = 34;       // time from three numbers
        private const int DS_TX_TS   = 35;       // a set of time suffixed numbers.

        private const int DS_DX_NNY  = 36;

        private const int DS_MAX     = 37;       // marker: end of enum

        ////////////////////////////////////////////////////////////////////////////
        //
        // NOTE: The following state machine table is dependent on the order of the
        // DS_ and DTT_ enumerations.
        //
        // For each non terminal state, the following table defines the next state
        // for each given date token type.
        //
        ////////////////////////////////////////////////////////////////////////////

//           DTT_End   DTT_NumEnd  DTT_NumAmPm DTT_NumSpace
//                                                        DTT_NumDaySep
//                                                                    DTT_NumTimesep
//                                                                               DTT_MonthEnd DTT_MonthSpace
//                                                                                                        DTT_MonthDSep
//                                                                                                                    DTT_NumDateSuff
//                                                                                                                                DTT_NumTimeSuff DTT_DayOfWeek
//                                                                                                                                                              DTT_YearSpace
//                                                                                                                                                                         DTT_YearDateSep
//                                                                                                                                                                                      DTT_YearEnd,
//                                                                                                                                                                                                  DTT_TimeZone
//                                                                                                                                                                                                             DTT_Era      DTT_UTCTimeMark
private static int[][] dateParsingStates = {
// DS_BEGIN                                                                             // DS_BEGIN
new int[] { DS_BEGIN, DS_ERROR,   DS_TX_N,    DS_N,       DS_D_Nd,    DS_T_Nt,    DS_ERROR,   DS_D_M,     DS_D_M,     DS_D_S,     DS_T_S,         DS_BEGIN,     DS_D_Y,     DS_D_Y,     DS_ERROR,   DS_BEGIN,  DS_BEGIN,    DS_ERROR},

// DS_N                                                                                 // DS_N
new int[] { DS_ERROR, DS_DX_NN,   DS_ERROR,   DS_NN,      DS_D_NNd,   DS_ERROR,   DS_DX_NM,   DS_D_NM,    DS_D_MNd,   DS_D_NDS,   DS_ERROR,       DS_N,         DS_D_YN,    DS_D_YN,    DS_DX_YN,   DS_N,      DS_N,        DS_ERROR}, 

// DS_NN                                                                                // DS_NN
new int[] { DS_DX_NN, DS_DX_NNN,  DS_TX_N,    DS_DX_NNN,  DS_ERROR,   DS_T_Nt,    DS_DX_MNN,  DS_DX_MNN,  DS_ERROR,   DS_ERROR,   DS_T_S,         DS_NN,        DS_DX_NNY,  DS_ERROR,    DS_DX_NNY,  DS_NN,     DS_NN,       DS_ERROR},

// DS_D_Nd                                                                              // DS_D_Nd
//new int[] { DS_ERROR, DS_DX_NN,   DS_ERROR,   DS_D_NN,    DS_D_NNd,   DS_ERROR,   DS_DX_MN,   DS_D_MN,    DS_D_MNd,   DS_ERROR,   DS_ERROR,       DS_D_Nd,     DS_D_YN,    DS_D_YN,     DS_DX_YN,   DS_ERROR,      DS_D_Nd,     DS_ERROR},
new int[] { DS_ERROR, DS_DX_NN,   DS_ERROR,   DS_D_NN,    DS_D_NNd,   DS_ERROR,   DS_DX_NM,   DS_D_MN,    DS_D_MNd,   DS_ERROR,   DS_ERROR,       DS_D_Nd,     DS_D_YN,    DS_D_YN,     DS_DX_YN,   DS_ERROR,      DS_D_Nd,     DS_ERROR},

// DS_D_NN                                                                              // DS_D_NN
new int[] { DS_DX_NN, DS_DX_NNN,  DS_TX_N,    DS_DX_NNN,  DS_ERROR,   DS_T_Nt,    DS_DX_MNN,  DS_DX_MNN,  DS_ERROR,   DS_DX_DS,   DS_T_S,         DS_D_NN,     DS_DX_NNY,   DS_ERROR,   DS_DX_NNY,  DS_ERROR,  DS_D_NN,     DS_ERROR},

// DS_D_NNd                                                                             // DS_D_NNd
new int[] { DS_ERROR, DS_DX_NNN,  DS_DX_NNN,  DS_DX_NNN,  DS_DX_NNN,  DS_ERROR,   DS_DX_MNN,  DS_DX_MNN,  DS_ERROR,   DS_DX_DS,   DS_ERROR,       DS_D_NNd,     DS_DX_NNY,  DS_ERROR,   DS_DX_NNY,  DS_ERROR,  DS_D_NNd,    DS_ERROR},

// DS_D_M                                                                               // DS_D_M
new int[] { DS_ERROR, DS_DX_MN,   DS_ERROR,   DS_D_MN,    DS_D_MNd,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,       DS_D_M,       DS_D_YM,    DS_D_YM,    DS_DX_YM,   DS_ERROR,   DS_D_M,     DS_ERROR},

// DS_D_MN                                                                              // DS_D_MN
new int[] { DS_DX_MN, DS_DX_MNN,  DS_DX_MNN,  DS_DX_MNN,  DS_DX_MNN,  DS_T_Nt,    DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_DX_DS,   DS_T_S,         DS_D_MN,      DS_DX_YMN,  DS_DX_YMN,  DS_DX_YMN,  DS_ERROR,  DS_D_MN,     DS_ERROR},

// DS_D_NM                                                                              // DS_D_NM
new int[] { DS_DX_NM, DS_DX_MNN,  DS_DX_MNN,  DS_DX_MNN,  DS_ERROR,   DS_T_Nt,    DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_DX_DS,   DS_T_S,         DS_D_NM,      DS_DX_YMN,    DS_ERROR,    DS_DX_YMN,  DS_ERROR,   DS_D_NM,    DS_ERROR},

// DS_D_MNd                                                                             // DS_D_MNd
//new int[] { DS_ERROR, DS_DX_MNN,  DS_ERROR,   DS_DX_MNN,  DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,       DS_D_MNd,     DS_DX_YMN,    DS_ERROR,    DS_DX_YMN,  DS_ERROR,   DS_D_MNd,   DS_ERROR},
new int[] { DS_DX_MN, DS_DX_MNN,  DS_ERROR,   DS_DX_MNN,  DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,       DS_D_MNd,     DS_DX_YMN,    DS_ERROR,    DS_DX_YMN,  DS_ERROR,   DS_D_MNd,   DS_ERROR},

// DS_D_NDS,                                                                            // DS_D_NDS,
new int[] { DS_DX_NDS,DS_DX_NNDS, DS_DX_NNDS, DS_DX_NNDS, DS_ERROR,   DS_T_Nt,    DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_D_NDS,   DS_T_S,         DS_D_NDS,     DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_ERROR,   DS_D_NDS,   DS_ERROR},

// DS_D_Y                                                                               // DS_D_Y
new int[] { DS_ERROR, DS_ERROR,   DS_ERROR,   DS_D_YN,    DS_D_YN,    DS_ERROR,   DS_DX_YM,   DS_D_YM,    DS_D_YM,    DS_D_YM,    DS_ERROR,       DS_D_Y,     DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_ERROR,       DS_D_Y,     DS_ERROR},

// DS_D_YN                                                                              // DS_D_YN
new int[] { DS_ERROR, DS_DX_YNN,  DS_DX_YNN,  DS_DX_YNN,  DS_DX_YNN,  DS_ERROR,   DS_DX_YMN,  DS_DX_YMN,  DS_ERROR,   DS_ERROR,   DS_ERROR,       DS_D_YN,      DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_ERROR,   DS_D_YN,    DS_ERROR},

// DS_D_YM                                                                              // DS_D_YM
new int[] { DS_DX_YM, DS_DX_YMN,  DS_DX_YMN,  DS_DX_YMN,  DS_DX_YMN,  DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,       DS_D_YM,      DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_D_YM,    DS_ERROR},

// DS_D_S                                                                               // DS_D_S
new int[] { DS_DX_DS, DS_DX_DSN,  DS_TX_N,    DS_T_Nt,    DS_ERROR,   DS_T_Nt,    DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_D_S,     DS_T_S,         DS_D_S,      DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_ERROR,       DS_D_S,     DS_ERROR},

// DS_T_S                                                                               // DS_T_S
new int[] { DS_TX_TS, DS_TX_TS,   DS_TX_TS,   DS_T_Nt,    DS_D_Nd,    DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_D_S,     DS_T_S,         DS_T_S,      DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_T_S,         DS_T_S,     DS_ERROR},

// DS_T_Nt                                                                              // DS_T_Nt
//new int[] { DS_ERROR, DS_TX_NN,   DS_TX_NN,   DS_TX_NN,   DS_ERROR,   DS_T_NNt,   DS_ERROR,   DS_D_NM,    DS_ERROR,   DS_ERROR,   DS_T_S,         DS_ERROR,     DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_T_Nt,    DS_T_Nt,    DS_TX_NN},
new int[] { DS_ERROR, DS_TX_NN,   DS_TX_NN,   DS_TX_NN,   DS_ERROR,   DS_T_NNt,   DS_DX_NM,   DS_D_NM,    DS_ERROR,   DS_ERROR,   DS_T_S,         DS_ERROR,     DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_T_Nt,    DS_T_Nt,    DS_TX_NN},

// DS_T_NNt                                                                             // DS_T_NNt
new int[] { DS_ERROR, DS_TX_NNN,  DS_TX_NNN,  DS_TX_NNN,  DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_ERROR,   DS_T_S,         DS_T_NNt,      DS_ERROR,    DS_ERROR,    DS_ERROR,   DS_T_NNt,   DS_T_NNt,   DS_TX_NNN},

};
//          End       NumEnd      NumAmPm     NumSpace    NumDaySep   NumTimesep  MonthEnd    MonthSpace  MonthDSep   NumDateSuff NumTimeSuff     DayOfWeek   YearSpace YearDateSep YearEnd


        private const String GMTName = "GMT";
        private const String ZuluName = "Z";

        //
        // Search from the index of str at str.Index to see if the target string exists in the str.
        //
        // allowPartialMatch:  If true, the method will not check if the matching string
        //        is in a word boundary, and will skip to the word boundary.
        //        For example, it will return true for matching "January" in "Januaryfoo".
        //        If false, the matching word must be in a word boundary. So it will return
        //        false for matching "January" in "Januaryfoo".
        //
        private static bool MatchWord(__DTString str, String target, bool allowPartialMatch)
        {
            int length = target.Length;
            if (length > (str.Value.Length - str.Index)) {
                return false;
            }
            if (CultureInfo.CurrentCulture.CompareInfo.Compare(str.Value, 
                                                               str.Index,
                                                               length,
                                                               target, 
                                                               0,
                                                               length,
                                                               CompareOptions.IgnoreCase)!=0) {
                return (false);
            }

            int nextCharIndex = str.Index + target.Length;

            if (allowPartialMatch)
            {
                //
                // Skip the remaining part of the word.
                //
                // This is to ignore special cases like:
                //    a few cultures has suffix after MMMM, like "fi" and "eu".
                while (nextCharIndex < str.Value.Length)
                {
                    if (!Char.IsLetter(str.Value[nextCharIndex]))
                    {
                        break;
                    }
                    nextCharIndex++;
                }
            } else {
                if (nextCharIndex < str.Value.Length) {
                    char nextCh = str.Value[nextCharIndex];
                    if (Char.IsLetter(nextCh) || nextCh == '/x00a1') {
                        // The '/x00a1' is a very unfortunate hack, since
                        // gl-ES (0x0456) used '/x00a1' in their day of week names.
                        // And '/x00a1' is a puctuation.  This breaks our
                        // assumption that there is no non-letter characters
                        // following a day/month name.  
                        return (false);
            }
                }
            }
            str.Index = nextCharIndex;

            return (true);
        }

        //
        // Starting at str.Index, check the type of the separator.
        //
        private static int GetSeparator(__DTString str, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
            int separator = SEP_Space;  // Assume the separator is a space. And try to find a better one.

            //
            // Check if we found any white spaces.
            //
            if (!str.SkipWhiteSpaceComma()) {
                //
                // SkipWhiteSpaceComma() will return true when end of string is reached.
                //

                //
                // Return the separator as SEP_End.
                //
                return (SEP_End);
            }

            if (Char.IsLetter(str.GetChar())) {
                //
                // This is a beginning of a word.
                //
                if (raw.timeMark == -1)
                {
                    //
                    // Check if this is an AM time mark.
                    //
                    int timeMark;
                    if ((timeMark = GetTimeMark(str, dtfi)) != -1)
                    {
                        raw.timeMark = timeMark;;
                        return (timeMark == TM_AM ? SEP_Am: SEP_Pm);
                    }
                }
                if (MatchWord(str, LocalTimeMark, false)) {
                    separator = SEP_LocalTimeMark;
                } else if (MatchWord(str, CJKYearSuff, false) || MatchWord(str, KoreanYearSuff, false)) {
                    separator = SEP_YearSuff;
                }
                else if (MatchWord(str, CJKMonthSuff, false) || MatchWord(str, KoreanMonthSuff, false))
                {
                    separator = SEP_MonthSuff;
                }
                else if (MatchWord(str, CJKDaySuff, false) || MatchWord(str, KoreanDaySuff, false))
                {
                    separator = SEP_DaySuff;
                }
                else if (MatchWord(str, CJKHourSuff, false) || MatchWord(str, ChineseHourSuff, false))
                {
                    separator = SEP_HourSuff;
                }
                else if (MatchWord(str, CJKMinuteSuff, false))
                {
                    separator = SEP_MinuteSuff;
                }
                else if (MatchWord(str, CJKSecondSuff, false))
                {
                    separator = SEP_SecondSuff;
                }
            } else {
                //
                // Not a letter. Check if this is a date separator.
                //
                if ((MatchWord(str, dtfi.DateSeparator, false)) ||
                    (MatchWord(str, invariantInfo.DateSeparator, false)) ||
                    (MatchWord(str, alternativeDateSeparator, false)))
                {
                    //
                    // NOTENOTE                     : alternativeDateSeparator is a special case because some cultures
                    //  (e.g. the invariant culture) use "/". However, in RFC format, we use "-" as the
                    // date separator.  Therefore, we should check for it.
                    //
                    separator = SEP_Date;
                }
                //
                // Check if this is a time separator.
                //
                else if ((MatchWord(str, dtfi.TimeSeparator, false)) ||
                         (MatchWord(str, invariantInfo.TimeSeparator, false)))
                {
                    separator = SEP_Time;
                } else if (dtfi.CultureID == 0x041c) {
                    // Special case for sq-AL (0x041c)
                    // Its time pattern is "h:mm:ss.tt"
                    if (str.GetChar() == '.') {
                        if (raw.timeMark == -1)
                        {
                            //
                            // Check if this is an AM time mark.
                            //
                            int timeMark;
                            str.Index++;
                            if ((timeMark = GetTimeMark(str, dtfi)) != -1)
                            {
                                raw.timeMark = timeMark;;
                                return (timeMark == TM_AM ? SEP_Am: SEP_Pm);
                            }
                            str.Index--;
                        }                        
                    }
                }
            }
                            
            return (separator);
        }

        //
        // Check the word at the current index to see if it matches a month name.
        // Return -1 if a match is not found. Otherwise, a value from 1 to 12 is returned.
        //
        private static int GetMonthNumber(__DTString str, DateTimeFormatInfo dtfi)
        {
            //
            // Check the month name specified in dtfi.
            //
            int i;

            int monthInYear = (dtfi.GetMonthName(13).Length == 0 ? 12 : 13);
            int maxLen = 0;
            int result = -1;
            int index;
            String word = str.PeekCurrentWord();

            //
            // We have to match the month name with the longest length, 
            // since there are cultures which have more than one month names
            // with the same prefix.
            //
            for (i = 1; i <= monthInYear; i++) {
                String monthName = dtfi.GetMonthName(i);

                if ((index = str.CompareInfo.IndexOf(
                    word, monthName, CompareOptions.IgnoreCase)) >= 0) {
                    // This condition allows us to parse the month name for:
                    // 1. the general cases like "yyyy MMMM dd".
                    // 2. prefix in the month name like: "dd '/x05d1'MMMM yyyy" (Hebrew - Israel)
                    result = i;
                    maxLen = index + monthName.Length;
                } else if (str.StartsWith(monthName, true)) {
                    // The condition allows us to get the month name for cultures
                    // which has spaces in their month names.
                    // E.g. 
                    if (monthName.Length > maxLen) {
                        result = i;
                        maxLen = monthName.Length;
                    }
                }
                }
            if (result > -1) {
                str.Index += maxLen;
                return (result);
            }
            for (i = 1; i <= monthInYear; i++)
            {
                if (MatchWord(str, dtfi.GetAbbreviatedMonthName(i), false))
                {
                    return (i);
                }
            }

            //
            // Check the month name in the invariant culture.
            //
            for (i = 1; i <= 12; i++)
            {
                if (MatchWord(str, invariantInfo.GetMonthName(i), false))
                {
                    return (i);
                }
            }

            for (i = 1; i <= 12; i++)
            {
                if (MatchWord(str, invariantInfo.GetAbbreviatedMonthName(i), false))
                {
                    return (i);
                }
            }

            return (-1);
        }

        //
        // Check the word at the current index to see if it matches a day of week name.
        // Return -1 if a match is not found.  Otherwise, a value from 0 to 6 is returned.
        //
        private static int GetDayOfWeekNumber(__DTString str, DateTimeFormatInfo dtfi) {
            //
            // Check the month name specified in dtfi.
            //

            DayOfWeek i;
            
            int maxLen = 0;
            int result = -1;
            //
            // We have to match the day name with the longest length, 
            // since there are cultures which have more than one day of week names
            // with the same prefix.
            //
            int endIndex = str.FindEndOfCurrentWord();
            String dayName=null;
            for (i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) {
                dayName = dtfi.GetDayName(i);
                if (str.MatchSpecifiedWord(dayName, endIndex)) {
                    if (dayName.Length > maxLen) {
                        result = (int)i;
                        maxLen = dayName.Length;
                    }
                }
                }

            if (result > -1) {
                str.Index = endIndex;
                return (result);
            }

            for (i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
            {
                if (MatchWord(str, dtfi.GetAbbreviatedDayName(i), false))
                {
                    return ((int)i);
                }
            }

            //
            // Check the month name in the invariant culture.
            //
            for (i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
            {
                if (MatchWord(str, invariantInfo.GetDayName(i), false))
                {
                    return ((int)i);
                }
            }

            for (i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
            {
                if (MatchWord(str, invariantInfo.GetAbbreviatedDayName(i), false))
                {
                    return ((int)i);
                }
            }

            return (-1);
        }

        //
        // Check the word at the current index to see if it matches GMT name or Zulu name.
        //
        private static bool GetTimeZoneName(__DTString str)
        {
            //
            //
            if (MatchWord(str, GMTName, false)) {
                return (true);
            }
            
            if (MatchWord(str, ZuluName, false)) {
                return (true);
            }

            return (false);
        }

        //
        // Create a Japanese DTFI which uses JapaneseCalendar.  This is used to parse
        // date string with Japanese era name correctly even when the supplied DTFI
        // does not use Japanese calendar.
        // The created instance is stored in global m_jajpDTFI.
        //
        private static void GetJapaneseCalendarDTFI() {
            // Check Calendar.ID specifically to avoid a lock here.
            if (m_jajpDTFI == null || m_jajpDTFI.Calendar.ID != Calendar.CAL_JAPAN) {
                m_jajpDTFI = new CultureInfo("ja-JP", false).DateTimeFormat;
                m_jajpDTFI.Calendar = JapaneseCalendar.GetDefaultInstance();
            }
        }

        //
        // Create a Taiwan DTFI which uses TaiwanCalendar.  This is used to parse
        // date string with era name correctly even when the supplied DTFI
        // does not use Taiwan calendar.
        // The created instance is stored in global m_zhtwDTFI.
        //
        private static void GetTaiwanCalendarDTFI() {
            // Check Calendar.ID specifically to avoid a lock here.
            if (m_zhtwDTFI == null || m_zhtwDTFI.Calendar.ID != Calendar.CAL_TAIWAN) {
                m_zhtwDTFI = new CultureInfo("zh-TW", false).DateTimeFormat;
                m_zhtwDTFI.Calendar = TaiwanCalendar.GetDefaultInstance();
            }
        }
        
        private static int GetEra(__DTString str, DateTimeResult result, ref DateTimeFormatInfo dtfi) {
            int[] eras = dtfi.Calendar.Eras;

            if (eras != null) {
                String word = str.PeekCurrentWord();
                int era;
                if ((era = dtfi.GetEra(word)) > 0) {
                    str.Index += word.Length;
                    return (era);
                }
                
                switch (dtfi.CultureID) {
                    case 0x0411:                    
                        // 0x0411 is the culture ID for Japanese.
                        if (dtfi.Calendar.ID != Calendar.CAL_JAPAN) {
                            // If the calendar for dtfi is Japanese, we have already
                            // done the check above. No need to re-check again.
                            GetJapaneseCalendarDTFI();                            
                            if ((era = m_jajpDTFI.GetEra(word)) > 0) {
                                str.Index += word.Length;
                                result.calendar = JapaneseCalendar.GetDefaultInstance();
                                dtfi = m_jajpDTFI;
                                return (era);
                            }
                        } 
                        break;
                   case 0x0404:
                        // 0x0404 is the culture ID for Taiwan.
                        if (dtfi.Calendar.ID != Calendar.CAL_TAIWAN) {
                            GetTaiwanCalendarDTFI();                            
                            if ((era = m_zhtwDTFI.GetEra(word)) > 0) {
                                str.Index += word.Length;
                                result.calendar = TaiwanCalendar.GetDefaultInstance();
                                dtfi = m_zhtwDTFI;
                                return (era);
                            }
                        } 
                        break;
                        
                }
            }
            return (-1);
        }

        private static int GetTimeMark(__DTString str, DateTimeFormatInfo dtfi) {
            if (((dtfi.AMDesignator.Length > 0) && MatchWord(str, dtfi.AMDesignator, false)) || MatchWord(str, invariantAMDesignator, false))
            {
                return (TM_AM);
            }
            else if (((dtfi.PMDesignator.Length > 0) && MatchWord(str, dtfi.PMDesignator, false)) || MatchWord(str, invariantPMDesignator, false))
            {
                //
                // Check if this is an PM time mark.
                //
                return (TM_PM);
            }
            return (-1);
        }
        
        internal static bool IsDigit(char ch) {
            //
            // How do we map full-width char        
            return (ch >= '0' && ch <= '9');
        }
        

        /*=================================ParseFraction==========================
        **Action: Starting at the str.Index, if the current character is a digit, parse the remaining
        **      numbers as fraction.  For example, if the sub-string starting at str.Index is "123", then
        **      the method will return 0.123
        **Returns:      The fraction number.
        **Arguments:
        **      str the parsing string
        **Exceptions:
        ============================================================================*/
        
        private static double ParseFraction(__DTString str) {
            double result = 0;
            double decimalBase = 0.1;
            char ch;
            while (str.Index <= str.len-1 && IsDigit(ch = str.Value[str.Index])) {
                result += (ch - '0') * decimalBase;
                decimalBase *= 0.1;
                str.Index++;
            }
            return (result);
        }

        /*=================================ParseTimeZone==========================
        **Action: Parse the timezone offset in the following format:
        **          "+8", "+08", "+0800", "+0800"
        **        This method is used by DateTime.Parse().
        **Returns:      The TimeZone offset.
        **Arguments:
        **      str the parsing string
        **Exceptions:
        **      FormatException if invalid timezone format is found.
        ============================================================================*/

        private static TimeSpan ParseTimeZone(__DTString str, char offsetChar) {
            // The hour/minute offset for timezone.
            int hourOffset = 0;
            int minuteOffset = 0;
            
            if (str.GetNextDigit()) {
                // Get the first digit, Try if we can parse timezone in the form of "+8".
                hourOffset = str.GetDigit();
                if (str.GetNextDigit()) {
                    // Parsing "+18"
                    hourOffset *= 10;
                    hourOffset += str.GetDigit();
                    if (str.GetNext()) {
                        char ch;
                        if (Char.IsDigit(ch = str.GetChar())) {
                            // Parsing "+1800"

                            // Put the char back, since we already get the char in the previous GetNext() call.
                            str.Index--;
                            if (ParseDigits(str, 2, true, out minuteOffset)) {
                                // ParseDigits() does not advance the char for us, so do it here.
                                str.Index++;
                            } else {
                                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                            }
                        } else if (ch == ':') {   
                            // Parsing "+18:00"
                            if (ParseDigits(str, 2, true, out minuteOffset)) {
                                str.Index++;
                            } else {
                                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                            }
                        } else {
                            // Not a digit, not a colon, put this char back.
                            str.Index--;
                        }
                    }
                }
                // The next char is not a digit, so we get the timezone in the form of "+8".
            } else {
                // Invalid timezone: No numbers after +/-.
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            TimeSpan timezoneOffset = new TimeSpan(hourOffset, minuteOffset, 0);
            if (offsetChar == '-') {
                timezoneOffset = timezoneOffset.Negate();
            }
            return (timezoneOffset);
        }
        
        //
        // This is the lexer. Check the character at the current index, and put the found token in dtok and
        // some raw date/time information in raw.
        //
        private static void Lex(
            int dps, __DTString str, DateTimeToken dtok, DateTimeRawInfo raw, DateTimeResult result, ref DateTimeFormatInfo dtfi) {
            
            int sep;
            dtok.dtt = DTT_Unk;     // Assume the token is unkown.

            //
            // Skip any white spaces.
            //
            if (!str.SkipWhiteSpaceComma()) {
                //
                // SkipWhiteSpaceComma() will return true when end of string is reached.
                //
                dtok.dtt = DTT_End;
                return;
            }

            char ch = str.GetChar();
            if (Char.IsLetter(ch))
            {
                //
                // This is a letter.
                //

                int month, dayOfWeek, era, timeMark;

                //
                // Check if this is a beginning of a month name.
                // And check if this is a day of week name.
                //
                if (raw.month == -1 && (month = GetMonthNumber(str, dtfi)) >= 1)
                {
                    //
                    // This is a month name
                    //
                    switch(sep=GetSeparator(str, raw, dtfi))
                    {
                        case SEP_End:
                            dtok.dtt = DTT_MonthEnd;
                            break;
                        case SEP_Space:
                            dtok.dtt = DTT_MonthSpace;
                            break;
                        case SEP_Date:
                            dtok.dtt = DTT_MonthDatesep;
                            break;
                        default:
                            //Invalid separator after month name
                            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                    }
                    raw.month = month;
                }
                else if (raw.dayOfWeek == -1 && (dayOfWeek = GetDayOfWeekNumber(str, dtfi)) >= 0)
                {
                    //
                    // This is a day of week name.
                    //
                    raw.dayOfWeek = dayOfWeek;
                    dtok.dtt = DTT_DayOfWeek;
                    //
                    // Discard the separator.
                    //
                    GetSeparator(str, raw, dtfi);
                }
                else if (GetTimeZoneName(str))
                {
                    //
                    // This is a timezone designator
                    //
                    // NOTENOTE                     : for now, we only support "GMT" and "Z" (for Zulu time).
                    //
                    dtok.dtt = DTT_TimeZone;
                    result.timeZoneUsed = true;
                    result.timeZoneOffset = new TimeSpan(0);
                } else if ((raw.era == -1) && ((era = GetEra(str, result, ref dtfi)) != -1)) {
                    raw.era = era;
                    dtok.dtt = DTT_Era;
                } else if (raw.timeMark == -1 && (timeMark = GetTimeMark(str, dtfi)) != -1) {
                    raw.timeMark = timeMark;
                    GetSeparator(str, raw, dtfi);
                } else {
                    //
                    // Not a month name, not a day of week name. Check if this is one of the
                    // known date words. This is used to deal case like Spanish cultures, which
                    // uses 'de' in their Date string.
                    // 
                    //                    
                    if (!str.MatchWords(dtfi.DateWords)) {
                        throw new FormatException(
                            String.Format(Environment.GetResourceString("Format_UnknowDateTimeWord"), str.Index));
                    }                    
                    GetSeparator(str, raw, dtfi);                    
                }
            } else if (Char.IsDigit(ch)) {
                if (raw.numCount == 3) {
                    throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                }
                //
                // This is a digit.
                //
                int number = ch - '0';

                int digitCount = 1;

                //
                // Collect other digits.
                //
                while (str.GetNextDigit())
                {
                    number = number * 10 + str.GetDigit();
                    digitCount++;
                }

                // If the previous parsing state is DS_T_NNt (like 12:01), and we got another number,
                // so we will have a terminal state DS_TX_NNN (like 12:01:02).
                // If the previous parsing state is DS_T_Nt (like 12:), and we got another number,
                // so we will have a terminal state DS_TX_NN (like 12:01:02).
                //
                // Look ahead to see if the following character is a decimal point or timezone offset.
                // This enables us to parse time in the forms of:
                //  "11:22:33.1234" or "11:22:33-08".
                if (dps == DS_T_NNt || dps == DS_T_Nt) {
                    char nextCh;
                    if ((str.Index < str.len - 1)) {
                        nextCh = str.Value[str.Index];
                        switch (nextCh) {                        
                            case '.':
                                if (dps == DS_T_NNt) {
                                    // Yes, advance to the next character.
                                    str.Index++;
                                    // Collect the second fraction.
                                    raw.fraction = ParseFraction(str);
                                }
                                break;
                            case '+':
                            case '-':
                                if (result.timeZoneUsed) {
                                    // Should not have two timezone offsets.
                                    throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                                }
                                result.timeZoneUsed = true;
                                result.timeZoneOffset = ParseTimeZone(str, nextCh);
                                break;
                        }
                    }
                }
                
                if (number >= 0)
                {
                    dtok.num = number;
                    if (digitCount >= 3)
                    {
                        if (raw.year == -1)
                        {
                            raw.year = number;
                            //
                            // If we have number which has 3 or more digits (like "001" or "0001"),
                            // we assume this number is a year. Save the currnet raw.numCount in
                            // raw.year.
                            //
                            switch (sep = GetSeparator(str, raw, dtfi))
                            {
                                case SEP_End:
                                    dtok.dtt     = DTT_YearEnd;
                                    break;
                                case SEP_Am:
                                case SEP_Pm:
                                case SEP_Space:
                                    dtok.dtt    = DTT_YearSpace;
                                    break;
                                case SEP_Date:
                                    dtok.dtt     = DTT_YearDateSep;
                                    break;
                                case SEP_YearSuff:
                                case SEP_MonthSuff:
                                case SEP_DaySuff:
                                    dtok.dtt    = DTT_NumDatesuff;
                                    dtok.suffix = sep;
                                    break;
                                case SEP_HourSuff:
                                case SEP_MinuteSuff:
                                case SEP_SecondSuff:
                                    dtok.dtt    = DTT_NumTimesuff;
                                    dtok.suffix = sep;
                                    break;
                                default:
                                    // Invalid separator after number number.
                                    throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                            }
                            //
                            // Found the token already. Let's bail.
                            //
                            return;
                        }
                        throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                    }
                } else
                {
                    //
                    // number is overflowed.
                    //
                    throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                }

                switch (sep = GetSeparator(str, raw, dtfi))
                {
                    //
                    // Note here we check if the numCount is less than three.
                    // When we have more than three numbers, it will be caught as error in the state machine.
                    //
                    case SEP_End:
                        dtok.dtt = DTT_NumEnd;
                        raw.num[raw.numCount++] = dtok.num;
                        break;
                    case SEP_Am:
                    case SEP_Pm:
                        dtok.dtt = DTT_NumAmpm;
                        raw.num[raw.numCount++] = dtok.num;
                        break;
                    case SEP_Space:
                        dtok.dtt = DTT_NumSpace;
                        raw.num[raw.numCount++] = dtok.num;
                        break;
                    case SEP_Date:
                        dtok.dtt = DTT_NumDatesep;
                        raw.num[raw.numCount++] = dtok.num;
                        break;
                    case SEP_Time:
                        if (!result.timeZoneUsed) {
                            dtok.dtt = DTT_NumTimesep;
                            raw.num[raw.numCount++] = dtok.num;
                        } else {
                            // If we already got timezone, there should be no
                            // time separator again.
                            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                        }
                        break;
                    case SEP_YearSuff:
                        dtok.num = dtfi.Calendar.ToFourDigitYear(number);
                        dtok.dtt    = DTT_NumDatesuff;
                        dtok.suffix = sep;
                        break;
                    case SEP_MonthSuff:
                    case SEP_DaySuff:
                        dtok.dtt    = DTT_NumDatesuff;
                        dtok.suffix = sep;
                        break;
                    case SEP_HourSuff:
                    case SEP_MinuteSuff:
                    case SEP_SecondSuff:
                        dtok.dtt    = DTT_NumTimesuff;
                        dtok.suffix = sep;
                        break;
                    case SEP_LocalTimeMark:
                        dtok.dtt = DTT_NumLocalTimeMark;
                        raw.num[raw.numCount++] = dtok.num;
                        break;
                    default:
                        // Invalid separator after number number.
                        throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                }
            }
            else
            {
                //
                // Not a letter, not a digit. Just ignore it.
                //
                str.Index++;
            }
            return;
        }

        private const int ORDER_YMD = 0;     // The order of date is Year/Month/Day.
        private const int ORDER_MDY = 1;     // The order of date is Month/Day/Year.
        private const int ORDER_DMY = 2;     // The order of date is Day/Month/Year.
        private const int ORDER_YDM = 3;     // The order of date is Year/Day/Month
        private const int ORDER_YM  = 4;     // Year/Month order.
        private const int ORDER_MY  = 5;     // Month/Year order.
        private const int ORDER_MD  = 6;     // Month/Day order.
        private const int ORDER_DM  = 7;     // Day/Month order.

        //
        // Decide the year/month/day order from the datePattern.
        //
        // Return 0 for YMD, 1 for MDY, 2 for DMY, otherwise -1.
        //
        private static int GetYearMonthDayOrder(String datePattern, DateTimeFormatInfo dtfi)
        {
            int yearOrder   = -1;
            int monthOrder  = -1;
            int dayOrder    = -1;
            int orderCount  =  0;

            bool inQuote = false;

            for (int i = 0; i < datePattern.Length && orderCount < 3; i++)
            {
                char ch = datePattern[i];
                if (ch == '/'' || ch == '"')
                {
                    inQuote = !inQuote;
                }

                if (!inQuote)
                {
                    if (ch == 'y')
                    {
                        yearOrder = orderCount++;

                        //
                        // Skip all year pattern charaters.
                        //
                        for(; i+1 < datePattern.Length && datePattern[i+1] == 'y'; i++)
                        {
                            // Do nothing here.
                        }
                    }
                    else if (ch == 'M')
                    {
                        monthOrder = orderCount++;
                        //
                        // Skip all month pattern characters.
                        //
                        for(; i+1 < datePattern.Length && datePattern[i+1] == 'M'; i++)
                        {
                            // Do nothing here.
                        }
                    }
                    else if (ch == 'd')
                    {

                        int patternCount = 1;
                        //
                        // Skip all day pattern characters.
                        //
                        for(; i+1 < datePattern.Length && datePattern[i+1] == 'd'; i++)
                        {
                            patternCount++;
                        }
                        //
                        // Make sure this is not "ddd" or "dddd", which means day of week.
                        //
                        if (patternCount <= 2)
                        {
                            dayOrder = orderCount++;
                        }
                    }
                }
            }

            if (yearOrder == 0 && monthOrder == 1 && dayOrder == 2)
            {
                return (ORDER_YMD);
            }
            if (monthOrder == 0 && dayOrder == 1 && yearOrder == 2)
            {
                return (ORDER_MDY);
            }
            if (dayOrder == 0 && monthOrder == 1 && yearOrder == 2)
            {
                return (ORDER_DMY);
            }
            if (yearOrder == 0 && dayOrder == 1 && monthOrder == 2)
            {
                return (ORDER_YDM);
            }
            throw new FormatException(String.Format(Environment.GetResourceString("Format_BadDatePattern"), datePattern));
        }

        //
        // Decide the year/month order from the pattern.
        //
        // Return 0 for YM, 1 for MY, otherwise -1.
        //
        private static int GetYearMonthOrder(String pattern, DateTimeFormatInfo dtfi)
        {
            int yearOrder   = -1;
            int monthOrder  = -1;
            int orderCount  =  0;

            bool inQuote = false;
            for (int i = 0; i < pattern.Length && orderCount < 2; i++)
            {
                char ch = pattern[i];
                if (ch == '/'' || ch == '"')
                {
                    inQuote = !inQuote;
                }

                if (!inQuote)
                {
                    if (ch == 'y')
                    {
                        yearOrder = orderCount++;

                        //
                        // Skip all year pattern charaters.
                        //
                        for(; i+1 < pattern.Length && pattern[i+1] == 'y'; i++)
                        {
                        }
                    }
                    else if (ch == 'M')
                    {
                        monthOrder = orderCount++;
                        //
                        // Skip all month pattern characters.
                        //
                        for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
                        {
                        }
                    }
                }
            }

            if (yearOrder == 0 && monthOrder == 1)
            {
                return (ORDER_YM);
            }
            if (monthOrder == 0 && yearOrder == 1)
            {
                return (ORDER_MY);
            }
            throw new FormatException(String.Format(Environment.GetResourceString("Format_BadDatePattern"), pattern));
        }

        //
        // Decide the month/day order from the pattern.
        //
        // Return 0 for MD, 1 for DM, otherwise -1.
        //
        private static int GetMonthDayOrder(String pattern, DateTimeFormatInfo dtfi)
        {
            int monthOrder  = -1;
            int dayOrder    = -1;
            int orderCount  =  0;

            bool inQuote = false;
            for (int i = 0; i < pattern.Length && orderCount < 2; i++)
            {
                char ch = pattern[i];
                if (ch == '/'' || ch == '"')
                {
                    inQuote = !inQuote;
                }

                if (!inQuote)
                {
                    if (ch == 'd')
                    {
                        int patternCount = 1;
                        //
                        // Skip all day pattern charaters.
                        //
                        for(; i+1 < pattern.Length && pattern[i+1] == 'd'; i++)
                        {
                            patternCount++;
                        }

                        //
                        // Make sure this is not "ddd" or "dddd", which means day of week.
                        //
                        if (patternCount <= 2)
                        {
                            dayOrder = orderCount++;
                        }

                    }
                    else if (ch == 'M')
                    {
                        monthOrder = orderCount++;
                        //
                        // Skip all month pattern characters.
                        //
                        for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
                        {
                        }
                    }
                }
            }

            if (monthOrder == 0 && dayOrder == 1)
            {
                return (ORDER_MD);
            }
            if (dayOrder == 0 && monthOrder == 1)
            {
                return (ORDER_DM);
            }
            throw new FormatException(String.Format(Environment.GetResourceString("Format_BadDatePattern"), pattern));
        }


        private static bool IsValidMonth(DateTimeResult result, int year, int month)
        {
            return (month >= 1 && month <= result.calendar.GetMonthsInYear(year));
        }

        //
        // NOTENOTE: This funciton assumes that year/month is correct. So call IsValidMonth before calling this.
        //
        private static bool IsValidDay(DateTimeResult result, int year, int month, int day)
        {
            return (day >= 1 && day <= result.calendar.GetDaysInMonth(year, month));
        }

        //
        // Adjust the two-digit year if necessary.
        //
        private static int AdjustYear(DateTimeResult result, int year)
        {
            if (year < 100)
            {
                year = result.calendar.ToFourDigitYear(year);
            }
            return (year);
        }

        private static bool SetDateYMD(DateTimeResult result, int year, int month, int day)
        {
            if (IsValidMonth(result, year, month) && IsValidDay(result, year, month, day))
            {
                result.SetDate(year, month, day);                           // YMD
                return (true);
            }
            return (false);
        }

        private static bool SetDateMDY(DateTimeResult result, int month, int day, int year)
        {
            return (SetDateYMD(result, year, month, day));
        }

        private static bool SetDateDMY(DateTimeResult result, int day, int month, int year)
        {
            return (SetDateYMD(result, year, month, day));
        }

        private static bool SetDateYDM(DateTimeResult result, int year, int day, int month)
        {
            return (SetDateYMD(result, year, month, day));
        }

        // Processing teriminal case: DS_DX_NN
        private static void GetDayOfNN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
            int n1 = raw.num[0];
            int n2 = raw.num[1];

            int year = result.calendar.GetYear(DateTime.Now);

            int order = GetMonthDayOrder(dtfi.MonthDayPattern, dtfi);

            if (order == ORDER_MD)
            {
                if (SetDateYMD(result, year, n1, n2))                           // MD
                {
                    return;
                }
            } else {
                // ORDER_DM
                if (SetDateYMD(result, year, n2, n1))                           // DM
                {
                    return;
                }
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        // Processing teriminal case: DS_DX_NNN
        private static void GetDayOfNNN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            int n1 = raw.num[0];
            int n2 = raw.num[1];;
            int n3 = raw.num[2];

            int order = GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi);

            if (order == ORDER_YMD) {
                if (SetDateYMD(result, AdjustYear(result, n1), n2, n3))         // YMD
                {
                    return;
                }
            } else if (order == ORDER_MDY) {
                if (SetDateMDY(result, n1, n2, AdjustYear(result, n3)))         // MDY
                {
                    return;
                }
            } else if (order == ORDER_DMY) {
                if (SetDateDMY(result, n1, n2, AdjustYear(result, n3)))         // DMY
                {
                    return;
                }
            } else if (order == ORDER_YDM) {
                if (SetDateYDM(result, AdjustYear(result, n1), n2, n3))         // YDM
                {
                    return;
                }
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfMN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            int currentYear = result.calendar.GetYear(DateTime.Now);
            result.Month = raw.month;

            //
            // NOTENOTE                     : in the case of invariant culture,
            // we will have an ambiguous situation when we have a string "June 11".
            // It could be 11-06-01 or CurrentYear-06-11.
            // In here, we favor CurrentYear-06-11 by checking the month/day first.
            //
            int monthDayOrder = GetMonthDayOrder(dtfi.MonthDayPattern, dtfi);
            if (monthDayOrder == ORDER_MD)
            {
                if (SetDateYMD(result, currentYear, raw.month, raw.num[0]))
                {
                    return;
                }
            } else if (monthDayOrder == ORDER_DM) {
                if (SetDateYMD(result, currentYear, raw.month, raw.num[0]))
                {
                    return;
                }
            }

            int yearMonthOrder = GetYearMonthOrder(dtfi.YearMonthPattern, dtfi);
            if (yearMonthOrder == ORDER_MY)
            {
                if (IsValidMonth(result, raw.num[0], raw.month))
                {
                    result.Year = raw.num[0];
                    result.Day  = 1;
                    return;
                }
            }

            if (IsValidDay(result, currentYear, result.Month, raw.num[0]))
            {
                result.Year = currentYear;
                result.Day = raw.num[0];
                return;
            }

            if (IsValidDay(result, raw.num[0], result.Month, 1))
            {
                result.Year = raw.num[0];
                result.Day  = 1;
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));

        }

        private static void GetDayOfNM(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            int currentYear = result.calendar.GetYear(DateTime.Now);

            result.Month = raw.month;

            // Check month/day first before checking year/month.
            // The logic here is that people often uses 4 digit for years, which will be captured by GetDayOfYM().
            // Therefore, we assume a number followed by a month is generally a month/day.
            int monthDayOrder = GetMonthDayOrder(dtfi.MonthDayPattern, dtfi);
            if (monthDayOrder == ORDER_DM)
            {
                result.Year = currentYear;
                if (IsValidDay(result, result.Year, raw.month, raw.num[0]))
                {
                    result.Day  = raw.num[0];
                    return;
                }
            }
            int yearMonthOrder = GetYearMonthOrder(dtfi.YearMonthPattern, dtfi);
            if (yearMonthOrder == ORDER_YM)
            {
                if (IsValidMonth(result, raw.num[0], raw.month))
                {
                    result.Year = raw.num[0];
                    result.Day  = 1;
                    return;
                }
            }

            //
            // NOTENOTE                     : in the case of invariant culture,
            // we will have an ambiguous situation when we have a string "June 11".
            // It is ambiguous because the month day pattern is "MMMM dd",
            // and year month pattern is "MMMM, yyyy".
            // Therefore, It could be 11-06-01 or CurrentYear-06-11.
            // In here, we favor CurrentYear-06-11 by checking the month/day first.
            //
            if (IsValidDay(result, currentYear, result.Month, raw.num[0]))
            {
                result.Year = currentYear;
                result.Day = raw.num[0];
                return;
            }

            if (IsValidDay(result, raw.num[0], result.Month, 1))
            {
                result.Year = raw.num[0];
                result.Day  = 1;
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfMNN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            int n1 = raw.num[0];
            int n2 = raw.num[1];

            int order = GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi);
            int year;

            if (order == ORDER_MDY)
            {
                if (IsValidDay(result, year = AdjustYear(result, n2), raw.month, n1))
                {
                    result.SetDate(year, raw.month, n1);      // MDY
                    return;
                }
                else if (IsValidDay(result, year = AdjustYear(result, n1), raw.month, n2))
                {
                    result.SetDate(year, raw.month, n2);      // YMD
                    return;
                }
            }
            else if (order == ORDER_YMD)
            {
                if (IsValidDay(result, year = AdjustYear(result, n1), raw.month, n2))
                {
                    result.SetDate(year, raw.month, n2);      // YMD
                    return;
                }
                else if (IsValidDay(result, year = AdjustYear(result, n2), raw.month, n1))
                {
                    result.SetDate(year, raw.month, n1);      // DMY
                    return;
                }
            }
            else if (order == ORDER_DMY)
            {
                if (IsValidDay(result, year = AdjustYear(result, n2), raw.month, n1))
                {
                    result.SetDate(year, raw.month, n1);      // DMY
                    return;
                }
                else if (IsValidDay(result, year = AdjustYear(result, n1), raw.month, n2))
                {
                    result.SetDate(year, raw.month, n2);      // YMD
                    return;
                }
            }

            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfYNN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
            int n1 = raw.num[0];
            int n2 = raw.num[1];

            if (dtfi.CultureID == 0x0437) {
                // 0x0437 = Georgian - Georgia (ka-GE)
                // Very special case for ka-GE: 
                //  Its short date patten is "dd.MM.yyyy" (ORDER_DMY).
                //  However, its long date pattern is "yyyy '/x10ec/x10da/x10d8/x10e1' dd MM, dddd" (ORDER_YDM)
                int order = GetYearMonthDayOrder(dtfi.LongDatePattern, dtfi);

                if (order == ORDER_YDM) {
                    if (SetDateYMD(result, raw.year, n2, n1)) {
                        return; // Year + DM
                    }                
                } else {
                    if (SetDateYMD(result, raw.year, n1, n2)) {
                        return; // Year + MD
                    }
                }
            } else {
                //  Otherwise, assume it is year/month/day.
                if (SetDateYMD(result, raw.year, n1, n2)) {
                    return; // Year + MD
                }
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfNNY(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
            int n1 = raw.num[0];
            int n2 = raw.num[1];

            int order = GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi);

            if (order == ORDER_MDY || order == ORDER_YMD) {
                if (SetDateYMD(result, raw.year, n1, n2)) {
                    return; // MD + Year
                }
            } else {
                if (SetDateYMD(result, raw.year, n2, n1)) {
                    return; // DM + Year
                }
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }
        

        private static void GetDayOfYMN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
            if (SetDateYMD(result, raw.year, raw.month, raw.num[0])) {
                return;
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfYN(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            if (SetDateYMD(result, raw.year, raw.num[0], 1))
            {
                return;
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void GetDayOfYM(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            if (SetDateYMD(result, raw.year, raw.month, 1))
            {
                return;
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
        }

        private static void AdjustTimeMark(DateTimeFormatInfo dtfi, DateTimeRawInfo raw) {
            // Specail case for culture which uses AM as empty string.  
            // E.g. af-ZA (0x0436)
            //    S1159                  /x0000
            //    S2359                  nm
            // In this case, if we are parsing a string like "2005/09/14 12:23", we will assume this is in AM.

            if (raw.timeMark == -1) {
                if (dtfi.AMDesignator != null && dtfi.PMDesignator != null) {
                    if (dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0) {
                        raw.timeMark = TM_AM;
                    }
                    if (dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0) {
                        raw.timeMark = TM_PM;
                    }
                } 
            }
        }
        
        //
        // Adjust hour according to the time mark.
        //
        private static int AdjustHour(DateTimeRawInfo raw)
        {
            int hour = raw.num[0];
            if (hour < 0 || hour > 12)
            {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }

            if (raw.timeMark == TM_AM)
            {
                hour = (hour == 12) ? 0 : hour;
            }
            else
            {
                hour = (hour == 12) ? 12 : hour + 12;
            }
            return (hour);
        }

        private static void GetTimeOfN(DateTimeFormatInfo dtfi, DateTimeResult result, DateTimeRawInfo raw)
        {
            //
            // In this case, we need a time mark. Check if so.
            //
            if (raw.timeMark == -1)
            {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            AdjustTimeMark(dtfi, raw);
            result.Hour = AdjustHour(raw);
        }

        private static void GetTimeOfNN(DateTimeFormatInfo dtfi, DateTimeResult result, DateTimeRawInfo raw)
        {
            if (raw.numCount < 2)
            {
                throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_InternalState));
            }
            AdjustTimeMark(dtfi, raw);
            result.Hour     = (raw.timeMark == - 1) ? raw.num[0] : AdjustHour(raw);
            result.Minute   = raw.num[1];
        }

        private static void GetTimeOfNNN(DateTimeFormatInfo dtfi, DateTimeResult result, DateTimeRawInfo raw)
        {
            if (raw.numCount < 3)
            {
                throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_InternalState));
            }
            AdjustTimeMark(dtfi, raw);
            result.Hour     =  (raw.timeMark == - 1) ? raw.num[0] : AdjustHour(raw);
            result.Minute   = raw.num[1];
            result.Second   = raw.num[2];
        }

        //
        // Processing terminal state: A Date suffix followed by one number.
        //
        private static void GetDateOfDSN(DateTimeResult result, DateTimeRawInfo raw)
        {
            if (raw.numCount != 1 || result.Day != -1)
            {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            result.Day = raw.num[0];
        }

        private static void GetDateOfNDS(DateTimeResult result, DateTimeRawInfo raw)
        {
            if (result.Month == -1)
            {
                //Should have a month suffix
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            if (result.Year != -1)
            {
                // Aleady has a year suffix
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }
            result.Year = raw.num[0];
            result.Day = 1;
        }

        private static void GetDateOfNNDS(DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
            int order = GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi);

            switch (order)
            {
                case ORDER_YMD:
                    break;
                case ORDER_MDY:
                    break;
                case ORDER_DMY:
                    if (result.Day == -1 && result.Year == -1)
                    {
                        if (IsValidDay(result, raw.num[1], result.Month, raw.num[0]))
                        {
                            result.Year = raw.num[1];
                            result.Day  = raw.num[0];
                        }
                    }
                    break;
            }
        }

        //
        // A date suffix is found, use this method to put the number into the result.
        //
        private static void ProcessDateTimeSuffix(DateTimeResult result, DateTimeRawInfo raw, DateTimeToken dtok)
        {
            switch (dtok.suffix)
            {
                case SEP_YearSuff:
                    result.Year = raw.year = dtok.num;
                    break;
                case SEP_MonthSuff:
                    result.Month= raw.month = dtok.num;
                    break;
                case SEP_DaySuff:
                    result.Day  = dtok.num;
                    break;
                case SEP_HourSuff:
                    result.Hour = dtok.num;
                    break;
                case SEP_MinuteSuff:
                    result.Minute = dtok.num;
                    break;
                case SEP_SecondSuff:
                    result.Second = dtok.num;
                    break;
            }
        }

        //
        // A terminal state has been reached, call the appropriate function to fill in the parsing result.
        // Return true if the state is a terminal state.
        //
        private static void ProcessTerminaltState(int dps, DateTimeResult result, DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
        {
        
            switch (dps)
            {
                case DS_DX_NN:
                    GetDayOfNN(result, raw, dtfi);
                    break;
                case DS_DX_NNN:
                    GetDayOfNNN(result, raw, dtfi);
                    break;
                case DS_DX_MN:
                    GetDayOfMN(result, raw, dtfi);
                    break;
                case DS_DX_NM:
                    GetDayOfNM(result, raw, dtfi);
                    break;
                case DS_DX_MNN:
                    GetDayOfMNN(result, raw, dtfi);
                    break;
                case DS_DX_DS:
                    // The result has got the correct value. No need to process.
                    break;
                case DS_DX_YNN:
                    GetDayOfYNN(result, raw, dtfi);
                    break;
                case DS_DX_NNY:
                    GetDayOfNNY(result, raw, dtfi);
                    break;
                case DS_DX_YMN:
                    GetDayOfYMN(result, raw, dtfi);
                    break;
                case DS_DX_YN:
                    GetDayOfYN(result, raw, dtfi);
                    break;
                case DS_DX_YM:
                    GetDayOfYM(result, raw, dtfi);
                    break;
                case DS_TX_N:
                    GetTimeOfN(dtfi, result, raw);
                    break;
                case DS_TX_NN:
                    GetTimeOfNN(dtfi, result, raw);
                    break;
                case DS_TX_NNN:
                    GetTimeOfNNN(dtfi, result, raw);
                    break;
                case DS_TX_TS:
                    // The result has got the correct value. No need to process.
                    break;
                case DS_DX_DSN:
                    GetDateOfDSN(result, raw);
                    break;
                case DS_DX_NDS:
                    GetDateOfNDS(result, raw);
                    break;
                case DS_DX_NNDS:
                    GetDateOfNNDS(result, raw, dtfi);
                    break;
            }

            if (dps > DS_ERROR)
            {
                //
                // We have reached a terminal state. Reset the raw num count.
                //
                raw.numCount = 0;
            }
            return;
        }

        //
        // This is the real method to do the parsing work.
        //
        internal static DateTime Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) {
            if (s == null) {
                throw new ArgumentNullException("s",
                    Environment.GetResourceString("ArgumentNull_String"));
            }
            if (s.Length == 0) {
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }            
            if (dtfi == null) {
                dtfi = DateTimeFormatInfo.CurrentInfo;
            }
        
            DateTime time;
            //
            // First try the predefined format.
            //
        
            int dps             = DS_BEGIN;     // Date Parsing State.
            bool reachTerminalState = false;

            DateTimeResult result = new DateTimeResult();       // The buffer to store the parsing result.
            DateTimeToken   dtok    = new DateTimeToken();      // The buffer to store the parsing token.
            DateTimeRawInfo raw     = new DateTimeRawInfo();    // The buffer to store temporary parsing information.
            result.calendar = dtfi.Calendar;

            //
            // The string to be parsed. Use a __DTString wrapper so that we can trace the index which
            // indicates the begining of next token.
            //
            __DTString str = new __DTString(s);

            str.GetNext();

            //
            // The following loop will break out when we reach the end of the str.
            //
            do {
                //
                // Call the lexer to get the next token.
                //
                // If we find a era in Lex(), the era value will be in raw.era.
                Lex(dps, str, dtok, raw, result, ref dtfi);

                //
                // If the token is not unknown, process it.
                // Otherwise, just discard it.
                //
                if (dtok.dtt != DTT_Unk)
                {
                    //
                    // Check if we got any CJK Date/Time suffix.
                    // Since the Date/Time suffix tells us the number belongs to year/month/day/hour/minute/second,
                    // store the number in the appropriate field in the result.
                    //
                    if (dtok.suffix != SEP_Unk)
                    {
                        ProcessDateTimeSuffix(result, raw, dtok);
                        dtok.suffix = SEP_Unk;  // Reset suffix to SEP_Unk;
                    }


                    if (dps == DS_D_YN && dtok.dtt == DTT_NumLocalTimeMark) {
                            // Consider this as ISO 8601 format:
                            // "yyyy-MM-dd'T'HH:mm:ss"                 1999-10-31T02:00:00
                            return (ParseISO8601(raw, str, styles));
                    }

                    //
                    // Advance to the next state, and continue
                    //
                    dps = dateParsingStates[dps][dtok.dtt];

                    if (dps == DS_ERROR)
                    {
                        BCLDebug.Trace("NLS", "DateTimeParse.DoParse(): dps is DS_ERROR");
                        throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
                    }
                    else if (dps > DS_ERROR)
                    {
                        ProcessTerminaltState(dps, result, raw, dtfi);
                        reachTerminalState = true;

                        //
                        // If we have reached a terminal state, start over from DS_BEGIN again.
                        // For example, when we parsed "1999-12-23 13:30", we will reach a terminal state at "1999-12-23",
                        // and we start over so we can continue to parse "12:30".
                        //
                        dps = DS_BEGIN;
                    }
                }
            } while (dtok.dtt != DTT_End && dtok.dtt != DTT_NumEnd && dtok.dtt != DTT_MonthEnd);

            if (!reachTerminalState) {
                BCLDebug.Trace("NLS", "DateTimeParse.DoParse(): terminal state is not reached");
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            }

            // Check if the parased string only contains hour/minute/second values.
            bool bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
            
            //
            // Check if any year/month/day is missing in the parsing string.
            // If yes, get the default value from today's date.
            //
            CheckDefaultDateTime(result, ref result.calendar, styles);

            try {
                if (raw.era == -1) {
                    raw.era = Calendar.CurrentEra;
                }
                time = result.calendar.ToDateTime(result.Year, result.Month, result.Day, 
                    result.Hour, result.Minute, result.Second, 0, raw.era);
                if (raw.fraction > 0) {
                    time = time.AddTicks((long)Math.Round(raw.fraction * Calendar.TicksPerSecond));
                }
            } catch (Exception)
            {
                BCLDebug.Trace("NLS", "DateTimeParse.DoParse(): time is bad");
                throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));
            } 

            //
            // NOTENOTE                     :
            // We have to check day of week before we adjust to the time zone.
            // Otherwise, the value of day of week may change after adjustting to the time zone.
            //
            if (raw.dayOfWeek != -1) {
                //
                // Check if day of week is correct.
                //
                if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time)) {
                    BCLDebug.Trace("NLS", "DateTimeParse.DoParse(): day of week is not correct");
                    throw new FormatException(Environment.GetResourceString("Format_BadDayOfWeek"));
                }
            }

            if (result.timeZoneUsed) {
                time = AdjustTimeZone(time, result.timeZoneOffset, styles, bTimeOnly);
            }
            
            return (time);
        }

        private static DateTime AdjustTimeZone(DateTime time, TimeSpan timeZoneOffset, DateTimeStyles sytles, bool bTimeOnly) {
            if ((sytles & DateTimeStyles.AdjustToUniversal) != 0) {
                return (AdjustTimeZoneToUniversal(time, timeZoneOffset));
            }

            return (AdjustTimeZoneToLocal(time, timeZoneOffset, bTimeOnly));
        }

        //
        // Adjust the specified time to universal time based on the supplied timezone.
        // E.g. when parsing "2001/06/08 14:00-07:00", 
        // the time is 2001/06/08 14:00, and timeZoneOffset = -07:00.
        // The result will be "2001/06/08 21:00"
        //
        private static DateTime AdjustTimeZoneToUniversal(DateTime time, TimeSpan timeZoneOffset) {
            long resultTicks = time.Ticks;
            resultTicks -= timeZoneOffset.Ticks;
            if (resultTicks < 0) {
                resultTicks += Calendar.TicksPerDay;
            }
            
            if (resultTicks < 0) {
                throw new FormatException(Environment.GetResourceString("Format_DateOutOfRange"));
            }
            return (new DateTime(resultTicks));
        }

        //
        // Adjust the specified time to universal time based on the supplied timezone,
        // and then convert to local time.
        // E.g. when parsing "2001/06/08 14:00-04:00", and local timezone is GMT-7.
        // the time is 2001/06/08 14:00, and timeZoneOffset = -05:00.
        // The result will be "2001/06/08 11:00"
        //
        private static DateTime AdjustTimeZoneToLocal(DateTime time, TimeSpan timeZoneOffset, bool bTimeOnly) { 
            long resultTicks = time.Ticks;
            // Convert to local ticks
            if (resultTicks < Calendar.TicksPerDay) {
                //
                // This is time of day.
                //
                
                // Adjust timezone.
                resultTicks -= timeZoneOffset.Ticks;
                // If the time is time of day, use the current timezone offset.
                resultTicks += TimeZone.CurrentTimeZone.GetUtcOffset(bTimeOnly ? DateTime.Now: time).Ticks;
                
                if (resultTicks < 0) {
                    resultTicks += Calendar.TicksPerDay;
                }
            } else {
                // Adjust timezone to GMT.
                resultTicks -= timeZoneOffset.Ticks;
                if (resultTicks > DateTime.MaxValue.Ticks) {
                    // If the result ticks is greater than DateTime.MaxValue, we can not create a DateTime from this ticks.
                    // In this case, keep using the old code.
                    // This code path is used to get around bug 78411.
                    resultTicks += TimeZone.CurrentTimeZone.GetUtcOffset(time).Ticks;                
                } else {
                    // Convert the GMT time to local time.
                    return (new DateTime(resultTicks).ToLocalTime());
                }                
            }
            if (resultTicks < 0) {
                throw new FormatException(Environment.GetResourceString("Format_DateOutOfRange"));
            }
            return (new DateTime(resultTicks));        
        }
        
        //
        // Parse the ISO8601 format string found during Parse();
        // 
        //
        private static DateTime ParseISO8601(DateTimeRawInfo raw, __DTString str, DateTimeStyles styles) {
            if (raw.year < 0 || raw.num[0] < 0 || raw.num[1] < 0) {
            }
            str.Index--;
            int hour, minute, second;
            bool timeZoneUsed = false;
            TimeSpan timeZoneOffset = new TimeSpan();
            DateTime time = new DateTime(0);
            double partSecond = 0;
            
            str.SkipWhiteSpaces();            
            ParseDigits(str, 2, true, out hour);
            str.SkipWhiteSpaces();
            if (str.Match(':')) {
                str.SkipWhiteSpaces();
                ParseDigits(str, 2, true, out minute);    
                str.SkipWhiteSpaces();
                if (str.Match(':')) {
                    str.SkipWhiteSpaces();
                    ParseDigits(str, 2, true, out second);    
                    str.SkipWhiteSpaces();
                    
                    if (str.GetNext()) {
                        char ch = str.GetChar();
                        if (ch == '+' || ch == '-') {
                            timeZoneUsed = true;
                            timeZoneOffset = ParseTimeZone(str, str.GetChar());
                        } else if (ch == '.') {
                            str.Index++;  //ParseFraction requires us to advance to the next character.
                            partSecond = ParseFraction(str); 
                        } else if (ch == 'Z' || ch == 'z') {
                            timeZoneUsed = true;
                        } else {
                            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));            
                        }
                    }
                    
                    time =new DateTime(raw.year, raw.num[0], raw.num[1], hour, minute, second);
                    time = time.AddTicks((long)Math.Round(partSecond * Calendar.TicksPerSecond));
                    if (timeZoneUsed) {
                        time = AdjustTimeZone(time, timeZoneOffset, styles, false);
                    }
                    
                    return time;
                }
            }
            throw new FormatException(Environment.GetResourceString("Format_BadDateTime"));            
        }
        
        /*=================================ParseDigits==================================
        **Action: Parse the number string in __DTString that are formatted using
        **        the following patterns:
        **        "0", "00", and "000..0"
        **Returns: the integer value
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if error in parsing number.
        ==============================================================================*/
        
        private static bool ParseDigits(__DTString str, int digitLen, bool isThrowExp, out int result) {
            result = 0;
            if (!str.GetNextDigit()) {
                return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
            }
            result = str.GetDigit();

            if (digitLen == 1) {
                // When digitLen == 1, we should able to parse number like "9" and "19".  However,
                // we won't go beyond two digits.
                //
                // So let's look ahead one character to see if it is a digit.  If yes, add it to result.
                if (str.GetNextDigit()) {
                    result = result * 10 + str.GetDigit();
                } else {
                    // Not a digit, let's roll back the Index.
                    str.Index--;
                }
            } else if (digitLen == 2) {
                if (!str.GetNextDigit()) {
                    return (ParseFormatError(isThrowExp, "Format_BadDateTime"));    
                }
                result = result * 10 + str.GetDigit();
            } else {
                for (int i = 1; i < digitLen; i++) {
                    if (!str.GetNextDigit()) {
                        return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                    }
                    result = result * 10 + str.GetDigit();
                }
            }

            return (true);
        }

        /*=================================ParseFractionExact==================================
        **Action: Parse the number string in __DTString that are formatted using
        **        the following patterns:
        **        "0", "00", and "000..0"
        **Returns: the fraction value
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if error in parsing number.
        ==============================================================================*/
        
        private static bool ParseFractionExact(__DTString str, int digitLen, bool isThrowExp, ref double result) {
            if (!str.GetNextDigit()) {
                return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
            }
            result = str.GetDigit();

            for (int i = 1; i < digitLen; i++) {
                if (!str.GetNextDigit()) {
                    return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                }
                result = result * 10 + str.GetDigit();
            }

            result = ((double)result / Math.Pow(10, digitLen));
            return (true);
        }

        /*=================================ParseSign==================================
        **Action: Parse a positive or a negative sign.
        **Returns:      true if postive sign.  flase if negative sign.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions:   FormatException if end of string is encountered or a sign
        **              symbol is not found.
        ==============================================================================*/

        private static bool ParseSign(__DTString str, bool isThrowExp, ref bool result) {
            if (!str.GetNext()) {
                // A sign symbol ('+' or '-') is expected. However, end of string is encountered.
                return (ParseFormatError(isThrowExp, "Format_BadDateTime"));    
            }
            char ch = str.GetChar();
            if (ch == '+') {
                result = true;
                return (true);
            } else if (ch == '-') {
                result = false;
                return (true);
            }
            // A sign symbol ('+' or '-') is expected.
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================ParseTimeZoneOffset==================================
        **Action: Parse the string formatted using "z", "zz", "zzz" in DateTime.Format().
        **Returns: the TimeSpan for the parsed timezone offset.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **              len: the repeated number of the "z"
        **Exceptions: FormatException if errors in parsing.
        ==============================================================================*/

        private static bool ParseTimeZoneOffset(__DTString str, int len, bool isThrowExp, ref TimeSpan result) {
            bool isPositive = true;
            int hourOffset;
            int minuteOffset = 0;

            switch (len) {
                case 1:
                case 2:
                    if (!ParseSign(str, isThrowExp, ref isPositive)) {
                        return (false);
                    }
                    if (!ParseDigits(str, len, isThrowExp, out hourOffset)) {
                        return (false);
                    }
                    break;
                default:
                    if (!ParseSign(str, isThrowExp, ref isPositive)) {
                        return (false);
                    }
                    
                    if (!ParseDigits(str, 2, isThrowExp, out hourOffset)) {
                        return (false);
                    }   
                    // ':' is optional.
                    if (str.Match(":")) {
                        // Found ':'
                        if (!ParseDigits(str, 2, isThrowExp, out minuteOffset)) {
                            return (false);
                        }
                    } else {
                        // Since we can not match ':', put the char back.
                        str.Index--;
                        if (!ParseDigits(str, 2, isThrowExp, out minuteOffset)) {
                            return (false);
                        } 
                    }
                    break;
            }
            result = (new TimeSpan(hourOffset, minuteOffset, 0));
            if (!isPositive) {
                result = result.Negate();
            }
            return (true);
        }

        /*=================================MatchAbbreviatedMonthName==================================
        **Action: Parse the abbreviated month name from string starting at str.Index.
        **Returns: A value from 1 to 12 for the first month to the twelveth month.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if an abbreviated month name can not be found.
        ==============================================================================*/

        private static bool MatchAbbreviatedMonthName(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            int maxMatchStrLen = 0;
            result = -1;
            if (str.GetNext()) {
                //
                // Scan the month names (note that some calendars has 13 months) and find
                // the matching month name which has the max string length.
                // We need to do this because some cultures (e.g. "cs-CZ") which have
                // abbreviated month names with the same prefix.
                //            
                int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12: 13);
                for (int i = 1; i <= monthsInYear; i++) {
                    String searchStr = dtfi.GetAbbreviatedMonthName(i);
                    if (str.MatchSpecifiedWord(searchStr)) {
                        int matchStrLen = searchStr.Length;
                        if (matchStrLen > maxMatchStrLen) {
                            maxMatchStrLen = matchStrLen;
                            result = i;
                        }
                    }
                }
            }
            if (result > 0) {
                str.Index += (maxMatchStrLen - 1);
                return (true);
            }
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));            
        }

        /*=================================MatchMonthName==================================
        **Action: Parse the month name from string starting at str.Index.
        **Returns: A value from 1 to 12 indicating the first month to the twelveth month.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if a month name can not be found.
        ==============================================================================*/

        private static bool MatchMonthName(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            int maxMatchStrLen = 0;
            result = -1;
            if (str.GetNext()) {
                //
                // Scan the month names (note that some calendars has 13 months) and find
                // the matching month name which has the max string length.
                // We need to do this because some cultures (e.g. "vi-VN") which have
                // month names with the same prefix.
                //
                int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12: 13);
                for (int i = 1; i <= monthsInYear; i++) {
                    String searchStr = dtfi.GetMonthName(i);
                    if (str.MatchSpecifiedWord(searchStr)) {
                        int matchStrLen = (searchStr.Length - 1);
                        if (matchStrLen > maxMatchStrLen) {
                            maxMatchStrLen = matchStrLen;
                            result = i;
                        }
                    }
                }
            }

            if (result > 0) {
                str.Index += maxMatchStrLen;
                return (true);
            }
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================MatchAbbreviatedDayName==================================
        **Action: Parse the abbreviated day of week name from string starting at str.Index.
        **Returns: A value from 0 to 6 indicating Sunday to Saturday.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if a abbreviated day of week name can not be found.
        ==============================================================================*/

        private static bool MatchAbbreviatedDayName(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            if (str.GetNext()) {
                for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) {
                    String searchStr = dtfi.GetAbbreviatedDayName(i);
                    if (str.MatchSpecifiedWord(searchStr)) {
                        str.Index += (searchStr.Length - 1);
                        result = (int)i;
                        return (true);
                    }
                }
            }
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================MatchDayName==================================
        **Action: Parse the day of week name from string starting at str.Index.
        **Returns: A value from 0 to 6 indicating Sunday to Saturday.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if a day of week name can not be found.
        ==============================================================================*/

        private static bool MatchDayName(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            // Turkish (tr-TR) got day names with the same prefix.
            int maxMatchStrLen = 0;
            result = -1;
            if (str.GetNext()) {
                for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) {
                    String searchStr = dtfi.GetDayName(i);
                    if (str.MatchSpecifiedWord(searchStr)) {
                        int matchStrLen = (searchStr.Length - 1);
                        if (matchStrLen > maxMatchStrLen) {
                            maxMatchStrLen = matchStrLen;
                            result = (int)i;
                        }
                    }                    
                }
            }
            if (result >= 0) {
                str.Index += maxMatchStrLen;
                return (true);
            }            
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================MatchEraName==================================
        **Action: Parse era name from string starting at str.Index.
        **Returns: An era value. 
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if an era name can not be found.
        ==============================================================================*/

        private static bool MatchEraName(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            if (str.GetNext()) {
                int[] eras = dtfi.Calendar.Eras;

                if (eras != null) {
                    for (int i = 0; i <= eras.Length; i++) {
                        String searchStr = dtfi.GetEraName(eras[i]);
                        if (str.MatchSpecifiedWord(searchStr)) {
                            str.Index += (searchStr.Length - 1);
                            result = eras[i];
                            return (true);
                        }
                        searchStr = dtfi.GetAbbreviatedEraName(eras[i]);
                        if (str.MatchSpecifiedWord(searchStr)) {
                            str.Index += (searchStr.Length - 1);
                            result = eras[i];
                            return (true);
                        }
                    }
                }
            }
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================MatchTimeMark==================================
        **Action: Parse the time mark (AM/PM) from string starting at str.Index.
        **Returns: TM_AM or TM_PM.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if a time mark can not be found.
        ==============================================================================*/

        private static bool MatchTimeMark(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            result = -1;
            // In some cultures have empty strings in AM/PM mark. E.g. af-ZA (0x0436), the AM mark is "", and PM mark is "nm".
            if (dtfi.AMDesignator.Length == 0) {
                result = TM_AM;
            }
            if (dtfi.PMDesignator.Length == 0) {
                result = TM_PM;
            }
            
            if (str.GetNext()) {
                String searchStr = dtfi.AMDesignator;
                if (searchStr.Length > 0) {
                    if (str.MatchSpecifiedWord(searchStr)) {
                        // Found an AM timemark with length > 0.
                        str.Index += (searchStr.Length - 1);
                        result = TM_AM;
                        return (true);
                    }
                }
                searchStr = dtfi.PMDesignator;
                if (searchStr.Length > 0) {
                    if (str.MatchSpecifiedWord(searchStr)) {
                        // Found a PM timemark with length > 0.
                        str.Index += (searchStr.Length - 1);
                        result = TM_PM;
                        return (true);
                    }
                }
                // If we can not match the time mark strings with length > 0, 
                // just return the 
                return (true);
            } 
            if (result != -1) {
                // If one of the AM/PM marks is empty string, return the result.                
                return (true);
            }            
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================MatchAbbreviatedTimeMark==================================
        **Action: Parse the abbreviated time mark (AM/PM) from string starting at str.Index.
        **Returns: TM_AM or TM_PM.
        **Arguments:    str: a __DTString.  The parsing will start from the
        **              next character after str.Index.
        **Exceptions: FormatException if a abbreviated time mark can not be found.
        ==============================================================================*/

        private static bool MatchAbbreviatedTimeMark(__DTString str, DateTimeFormatInfo dtfi, bool isThrowExp, ref int result) {
            // NOTENOTE                     : the assumption here is that abbreviated time mark is the first
            // character of the AM/PM designator.  If this invariant changes, we have to
            // change the code below.
            if (str.GetNext())
            {
                if (str.GetChar() == dtfi.AMDesignator[0]) {
                    result = TM_AM;
                    return (true);
                }
                if (str.GetChar() == dtfi.PMDesignator[0]) {                
                    result = TM_PM;
                    return (true);
                }
            }
            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
        }

        /*=================================CheckNewValue==================================
        **Action: Check if currentValue is initialized.  If not, return the newValue.
        **        If yes, check if the current value is equal to newValue.  Throw ArgumentException
        **        if they are not equal.  This is used to check the case like "d" and "dd" are both
        **        used to format a string.
        **Returns: the correct value for currentValue.
        **Arguments:
        **Exceptions:
        ==============================================================================*/

        private static bool CheckNewValue(ref int currentValue, int newValue, char patternChar, bool isThrowExp) {
            if (currentValue == -1) {
                currentValue = newValue;
                return (true);
            } else {
                if (newValue != currentValue) {
                    BCLDebug.Trace("NLS", "DateTimeParse.CheckNewValue() : ", patternChar, " is repeated");
                    if (isThrowExp) {
                        throw new ArgumentException(
                            String.Format(Environment.GetResourceString("Format_RepeatDateTimePattern"), patternChar), "format");
                    }
                    return (false);
                }
            }
            return (true);
        }

        private static void CheckDefaultDateTime(DateTimeResult result, ref Calendar cal, DateTimeStyles styles) {
            
            if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) {
                /*
                The following table describes the behaviors of getting the default value
                when a certain year/month/day values are missing.

                An "X" means that the value exists.  And "--" means that value is missing.

                Year    Month   Day =>  ResultYear  ResultMonth     ResultDay       Note

                X       X       X       Parsed year Parsed month    Parsed day
                X       X       --      Parsed Year Parsed month    First day       If we have year and month, assume the first day of that month.
                X       --      X       Parsed year First month     Parsed day      If the month is missing, assume first month of that year.
                X       --      --      Parsed year First month     First day       If we have only the year, assume the first day of that year.

                --      X       X       CurrentYear Parsed month    Parsed day      If the year is missing, assume the current year.
                --      X       --      CurrentYear Parsed month    First day       If we have only a month value, assume the current year and current day.
                --      --      X       CurrentYear First month     Parsed day      If we have only a day value, assume current year and first month.
                --      --      --      CurrentYear Current month   Current day     So this means that if the date string only contains time, you will get current date.
                    
                */

                DateTime now = DateTime.Now;
                if (result.Month == -1 && result.Day == -1) {                    
                    if (result.Year == -1) {
                        if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0) {
                            // If there is no year/month/day values, and NoCurrentDateDefault flag is used,
                            // set the year/month/day value to the beginning year/month/day of DateTime().
                            // Note we should be using Gregorian for the year/month/day.
                            cal = GregorianCalendar.GetDefaultInstance();
                            result.Year = result.Month = result.Day = 1;
                        } else {
                            // Year/Month/Day are all missing.  
                            result.Year = cal.GetYear(now);                    
                            result.Month = cal.GetMonth(now);
                            result.Day = cal.GetDayOfMonth(now);
                        }
                    } else {
                        // Month/Day are both missing.
                        result.Month = 1;
                        result.Day = 1;
                    }                    
                } else {
                    if (result.Year == -1) {
                        result.Year = cal.GetYear(now);
                    }
                    if (result.Month == -1) {
                        result.Month = 1;
                    }
                    if (result.Day == -1) {
                        result.Day = 1;
                    }
                }                
            }
            // Set Hour/Minute/Second to zero if these value are not in str.
            if (result.Hour   == -1) result.Hour = 0;
            if (result.Minute == -1) result.Minute = 0;
            if (result.Second == -1) result.Second = 0;
            if (result.era == -1) result.era = Calendar.CurrentEra;
        }

        // Expand a pre-defined format string (like "D" for long date) to the real format that
        // we are going to use in the date time parsing.
        // This method also set the dtfi according/parseInfo to some special pre-defined
        // formats.
        //
        private static String ExpandPredefinedFormat(String format, ref DateTimeFormatInfo dtfi, ParsingInfo parseInfo) {
            //
            // Check the format to see if we need to override the dtfi to be InvariantInfo,
            // and see if we need to set up the userUniversalTime flag.
            //
            switch (format[0]) {
                case 'r':
                case 'R':       // RFC 1123 Standard.  (in Universal time)
                    parseInfo.calendar = GregorianCalendar.GetDefaultInstance();                    
                    dtfi = DateTimeFormatInfo.InvariantInfo;                    
                    break;
                case 's':       // Sortable format (in local time)                
                    dtfi = DateTimeFormatInfo.InvariantInfo;
                    parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
                    break;
                case 'u':       // Universal time format in sortable format.
                    parseInfo.calendar = GregorianCalendar.GetDefaultInstance();                    
                    dtfi = DateTimeFormatInfo.InvariantInfo;                    
                    break;
                case 'U':       // Universal time format with culture-dependent format.                        
                    parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
                    parseInfo.fUseUniversalTime = true;
                    if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
                        dtfi = (DateTimeFormatInfo)dtfi.Clone();
                        dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
                    }
                    break;
            } 

            //
            // Expand the pre-defined format character to the real format from DateTimeFormatInfo.
            //
            return (DateTimeFormat.GetRealFormat(format, dtfi));            
        }
            
        // Given a specified format character, parse and update the parsing result.
        //
        private static bool ParseByFormat(
            __DTString str, 
            __DTString format, 
            ParsingInfo parseInfo, 
            DateTimeFormatInfo dtfi,
            bool isThrowExp,
            DateTimeResult result) {
            
            int tokenLen = 0;
            int tempYear = 0, tempMonth = 0, tempDay = 0, tempDayOfWeek = 0, tempHour = 0, tempMinute = 0, tempSecond = 0;
            double tempFraction = 0;
            int tempTimeMark = 0;
            
            char ch = format.GetChar();
            
            switch (ch) {
                case 'y':
                    tokenLen = format.GetRepeatCount();
                    if (tokenLen <= 2) {
                        parseInfo.fUseTwoDigitYear = true;
                    }
                    if (!ParseDigits(str, tokenLen, isThrowExp, out tempYear)) {
                        return (false);
                    }                    
                    if (!CheckNewValue(ref result.Year, tempYear, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'M':
                    tokenLen = format.GetRepeatCount();
                    if (tokenLen <= 2) {
                        if (!ParseDigits(str, tokenLen, isThrowExp, out tempMonth)) {
                            return (false);
                        }
                    } else {
                        if (tokenLen == 3) {
                            if (!MatchAbbreviatedMonthName(str, dtfi, isThrowExp, ref tempMonth)) {
                                return (false);
                            }
                        } else {
                            if (!MatchMonthName(str, dtfi, isThrowExp, ref tempMonth)) {
                                return (false);
                            }
                        }
                    }
                    if (!CheckNewValue(ref result.Month, tempMonth, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'd':
                    // Day & Day of week
                    tokenLen = format.GetRepeatCount();
                    if (tokenLen <= 2) {
                        // "d" & "dd"
                        if (!ParseDigits(str, tokenLen, isThrowExp, out tempDay)) {
                            return (false);
                        }
                        if (!CheckNewValue(ref result.Day, tempDay, ch, isThrowExp)) {
                            return (false);
                        }
                    } else {
                        if (tokenLen == 3) {
                            // "ddd"
                            if (!MatchAbbreviatedDayName(str, dtfi, isThrowExp, ref tempDayOfWeek)) {
                                return (false);
                            }
                        } else {
                            // "dddd*"
                            if (!MatchDayName(str, dtfi, isThrowExp, ref tempDayOfWeek)) {
                                return (false);
                            }
                        }
                        if (!CheckNewValue(ref parseInfo.dayOfWeek, tempDayOfWeek, ch, isThrowExp)) {
                            return (false);
                        }
                    }
                    break;
                case 'g':
                    tokenLen = format.GetRepeatCount();
                    // Put the era value in result.era.
                    if (!MatchEraName(str, dtfi, isThrowExp, ref result.era)) {
                        return (false);
                    }
                    break;
                case 'h':
                    parseInfo.fUseHour12 = true;
                    tokenLen = format.GetRepeatCount();
                    if (!ParseDigits(str, (tokenLen < 2? 1 : 2), isThrowExp, out tempHour)) {
                        return (false);
                    }
                    if (!CheckNewValue(ref result.Hour, tempHour, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'H':
                    tokenLen = format.GetRepeatCount();
                    if (!ParseDigits(str, (tokenLen < 2? 1 : 2), isThrowExp, out tempHour)) {
                        return (false);
                    }
                    if (!CheckNewValue(ref result.Hour, tempHour, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'm':
                    tokenLen = format.GetRepeatCount();
                    if (!ParseDigits(str, (tokenLen < 2? 1 : 2), isThrowExp, out tempMinute)) {
                        return (false);
                    }
                    if (!CheckNewValue(ref result.Minute, tempMinute, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 's':
                    tokenLen = format.GetRepeatCount();
                    if (!ParseDigits(str, (tokenLen < 2? 1 : 2), isThrowExp, out tempSecond)) {
                        return (false);
                    }
                    if (!CheckNewValue(ref result.Second, tempSecond, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'f':
                    tokenLen = format.GetRepeatCount();
                    if (tokenLen <= DateTimeFormat.MaxSecondsFractionDigits) {
                        if (!ParseFractionExact(str, tokenLen, isThrowExp, ref tempFraction)) {
                            return (false);
                        }
                        if (result.fraction < 0) {
                            result.fraction = tempFraction;
                        } else {
                            if (tempFraction != result.fraction) {
                                if (isThrowExp) {
                                    throw new ArgumentException(
                                        String.Format(Environment.GetResourceString("Format_RepeatDateTimePattern"), ch), "str");
                                } else {
                                    return (false);
                                }
                            }                                        
                        }
                    } else {
                        return ParseFormatError(isThrowExp, "Format_BadDateTime");
                    }
                    break;
                case 't':
                    // AM/PM designator
                    tokenLen = format.GetRepeatCount();
                    if (tokenLen == 1) {
                        if (!MatchAbbreviatedTimeMark(str, dtfi, isThrowExp, ref tempTimeMark)) {
                            return (false);
                        }
                    } else {                        
                        if (!MatchTimeMark(str, dtfi, isThrowExp, ref tempTimeMark)) {
                            return (false);
                        }
                    }

                    if (!CheckNewValue(ref parseInfo.timeMark, tempTimeMark, ch, isThrowExp)) {
                        return (false);
                    }
                    break;
                case 'z':
                    // timezone offset
                    if (parseInfo.fUseTimeZone) {
                        throw new ArgumentException(Environment.GetResourceString("Argument_TwoTimeZoneSpecifiers"), "str");
                    }
                    parseInfo.fUseTimeZone = true;
                    tokenLen = format.GetRepeatCount();
                    if (!ParseTimeZoneOffset(str, tokenLen, isThrowExp, ref parseInfo.timeZoneOffset)) {
                        return (false);
                    }                    
                    break;
                case 'Z':
                    if (parseInfo.fUseTimeZone) {
                        throw new ArgumentException(Environment.GetResourceString("Argument_TwoTimeZoneSpecifiers"), "str");
                    }
                    parseInfo.fUseTimeZone = true;
                    parseInfo.timeZoneOffset = new TimeSpan(0);

                    str.Index++;
                    if (!GetTimeZoneName(str)) {
                        BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): 'Z' or 'GMT' are expected");
                        return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                    }
                    break;
                case ':':
                    if (!str.Match(dtfi.TimeSeparator)) {
                        // A time separator is expected.
                        BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): ':' is expected");
                        return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                    }
                    break;
                case '/':
                    if (!str.Match(dtfi.DateSeparator)) {
                        // A date separator is expected.
                        BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): date separator is expected");
                        return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                    }
                    break;
                case '/"':
                case '/'':
                    StringBuilder enquotedString = new StringBuilder();
                    try {
                        // Use ParseQuoteString so that we can handle escape characters within the quoted string.
                        tokenLen = DateTimeFormat.ParseQuoteString(format.Value, format.Index, enquotedString); 
                    } catch (Exception) {
                        if (isThrowExp) { 
                            throw new FormatException(String.Format(Environment.GetResourceString("Format_BadQuote"), ch));
                        } else {
                            return (false);
                        }
                    }
                    format.Index += tokenLen - 1;                    
                    
                    // Some cultures uses space in the quoted string.  E.g. Spanish has long date format as:
                    // "dddd, dd' de 'MMMM' de 'yyyy".  When inner spaces flag is set, we should skip whitespaces if there is space
                    // in the quoted string.
                    String quotedStr = enquotedString.ToString();
                    for (int i = 0; i < quotedStr.Length; i++) {
                        if (quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite) {
                            str.SkipWhiteSpaces();
                        } else if (!str.Match(quotedStr[i])) {
                            // Can not find the matching quoted string.
                            BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse():Quote string doesn't match");
                            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                        }
                    }
                    break;
                case '%':
                    // Skip this so we can get to the next pattern character.
                    // Used in case like "%d", "%y"

                    // Make sure the next character is not a '%' again.
                    if (format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%') {
                        BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse():%% is not permitted");
                        return (ParseFormatError(isThrowExp, "Format_BadFormatSpecifier"));
                    }
                    break;
                case '//':
                    // Escape character. For example, "/d".
                    // Get the next character in format, and see if we can
                    // find a match in str.
                    if (format.GetNext()) {
                        if (!str.Match(format.GetChar())) {
                            // Can not find a match for the escaped character.
                            BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): Can not find a match for the escaped character");
                            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                        }
                    } else {
                        BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): // is at the end of the format string");
                        return (ParseFormatError(isThrowExp, "Format_BadFormatSpecifier"));
                    }
                    break;
                default:
                    if (ch == ' ') {
                        if (parseInfo.fAllowInnerWhite) {
                            // Skip whitespaces if AllowInnerWhite.
                            // Do nothing here.
                        } else {
                            if (!str.Match(ch)) {
                                // If the space does not match, and trailing space is allowed, we do
                                // one more step to see if the next format character can lead to
                                // successful parsing.
                                // This is used to deal with special case that a empty string can match
                                // a specific pattern.
                                // The example here is af-ZA, which has a time format like "hh:mm:ss tt".  However,
                                // its AM symbol is "" (empty string).  If fAllowTrailingWhite is used, and time is in 
                                // the AM, we will trim the whitespaces at the end, which will lead to a failure
                                // when we are trying to match the space before "tt".                                
                                if (parseInfo.fAllowTrailingWhite) {
                                    if (format.GetNext()) {
                                        if (ParseByFormat(str, format, parseInfo, dtfi, isThrowExp, result)) {
                                            return (true);
                                        }
                                    }
                                }
                                return (ParseFormatError(isThrowExp, "Format_BadDateTime")); 
                            }
                            // Found a macth.
                        }
                    } else {
                        if (format.MatchSpecifiedWord(GMTName)) {
                            format.Index += (GMTName.Length - 1);
                            // Found GMT string in format.  This means the DateTime string
                            // is in GMT timezone.
                            parseInfo.fUseTimeZone = true;
                            if (!str.Match(GMTName)) {
                                BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): GMT in format, but not in str");
                                return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                            }
                        } else if (!str.Match(ch)) {
                            // ch is expected.
                            BCLDebug.Trace ("NLS", "DateTimeParse.DoStrictParse(): '", ch, "' is expected");
                            return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                        }
                    }
                    break;
            } // switch
            return (true);
        }

        // A very small utility method to either return false or throw format exception according to the flag.
        private static bool ParseFormatError(bool isThrowException, String resourceID)
        {
            if (isThrowException)
            {
                throw new FormatException(Environment.GetResourceString(resourceID));
            }
            return (false);
        }
        
        /*=================================DoStrictParse==================================
        **Action: Do DateTime parsing using the format in formatParam.
        **Returns: The parsed DateTime.
        **Arguments:
        **Exceptions:
        **
        **Notes:
        **  When the following general formats are used, InvariantInfo is used in dtfi:
        **      'r', 'R', 's'.
        **  When the following general formats are used, the time is assumed to be in Universal time.
        **
        **Limitations:
        **  Only GregarianCalendar is supported for now.
        **  Only support GMT timezone.
        ==============================================================================*/

        private static bool DoStrictParse(
            String s, 
            String formatParam, 
            DateTimeStyles styles, 
            DateTimeFormatInfo dtfi, 
            bool isThrowExp,
            out DateTime returnValue) {

            bool bTimeOnly = false;
            returnValue = new DateTime();
            ParsingInfo parseInfo = new ParsingInfo();

            parseInfo.calendar = dtfi.Calendar;
            parseInfo.fAllowInnerWhite = ((styles & DateTimeStyles.AllowInnerWhite) != 0);
            parseInfo.fAllowTrailingWhite = ((styles & DateTimeStyles.AllowTrailingWhite) != 0);

            if (formatParam.Length == 1) {
                formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, parseInfo);
            }

            DateTimeResult result = new DateTimeResult();

            // Reset these values to negative one so that we could throw exception
            // if we have parsed every item twice.
            result.Hour = result.Minute = result.Second = -1;

            __DTString format = new __DTString(formatParam);
            __DTString str = new __DTString(s);

            if (parseInfo.fAllowTrailingWhite) {
                // Trim trailing spaces if AllowTrailingWhite.
                format.TrimTail();
                format.RemoveTrailingInQuoteSpaces();
                str.TrimTail();
            }

            if ((styles & DateTimeStyles.AllowLeadingWhite) != 0) {
                format.SkipWhiteSpaces();
                format.RemoveLeadingInQuoteSpaces();
                str.SkipWhiteSpaces();
            }

            //
            // Scan every character in format and match the pattern in str.
            //
            while (format.GetNext()) {
                // We trim inner spaces here, so that we will not eat trailing spaces when
                // AllowTrailingWhite is not used.
                if (parseInfo.fAllowInnerWhite) {
                    str.SkipWhiteSpaces();
                }
                if (!ParseByFormat(str, format, parseInfo, dtfi, isThrowExp, result) &&
                   !isThrowExp) {
                   return (false);
                }
            }
            if (str.Index < str.Value.Length - 1) {
                // There are still remaining character in str.
                BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): Still characters in str, str.Index = ", str.Index);
                return (ParseFormatError(isThrowExp, "Format_BadDateTime"));                
            }

            if (parseInfo.fUseTwoDigitYear) {
                // A two digit year value is expected. Check if the parsed year value is valid.
                if (result.Year >= 100) {
                    BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): Invalid value for two-digit year");
                    return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                }
                result.Year = parseInfo.calendar.ToFourDigitYear(result.Year);
            }

            if (parseInfo.fUseHour12) {
                if (parseInfo.timeMark == -1) {
                    // hh is used, but no AM/PM designator is specified.
                    // Assume the time is AM.  
                    // Don't throw exceptions in here becasue it is very confusing for people.
                    // I always got confused myself when I use "hh:mm:ss" to parse a time string,
                    // and ParseExact() throws on me (because I didn't use the 24-hour clock 'HH').
                    parseInfo.timeMark = TM_AM;
                    BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): hh is used, but no AM/PM designator is specified.");
                }
                if (result.Hour > 12) {
                    // AM/PM is used, but the value for HH is too big.
                    BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): AM/PM is used, but the value for HH is too big.");
                    return (ParseFormatError(isThrowExp, "Format_BadDateTime"));
                }
                if (parseInfo.timeMark == TM_AM) {
                    if (result.Hour == 12) {
                        result.Hour = 0;
                    }
                } else {
                    result.Hour = (result.Hour == 12) ? 12 : result.Hour + 12;
                }
            }

            // Check if the parased string only contains hour/minute/second values.
            bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
            CheckDefaultDateTime(result, ref parseInfo.calendar, styles);
            try {
                returnValue = parseInfo.calendar.ToDateTime(result.Year, result.Month, result.Day, 
                    result.Hour, result.Minute, result.Second, 0, result.era);
                if (result.fraction > 0) {
                    returnValue = returnValue.AddTicks((long)Math.Round(result.fraction * Calendar.TicksPerSecond));
            }
            } catch (ArgumentOutOfRangeException) {
                return (ParseFormatError(isThrowExp, "Format_DateOutOfRange"));
            } catch (Exception exp) {
                if (isThrowExp) {
                    throw exp;
                } else {
                    return (false);
                }
            }

            //
            // NOTENOTE                     :
            // We have to check day of week before we adjust to the time zone.
            // It is because the value of day of week may change after adjusting
            // to the time zone.
            //
            if (parseInfo.dayOfWeek != -1) {
                //
                // Check if day of week is correct.
                //
                if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(returnValue)) {
                    BCLDebug.Trace("NLS", "DateTimeParse.DoStrictParse(): day of week is not correct");
                    return (ParseFormatError(isThrowExp, "Format_BadDayOfWeek"));
                }
            }
            if (parseInfo.fUseTimeZone) {
                if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
                    returnValue = AdjustTimeZoneToUniversal(returnValue, parseInfo.timeZoneOffset);
                } else {
                    returnValue = AdjustTimeZoneToLocal(returnValue, parseInfo.timeZoneOffset, bTimeOnly);
                }
            } else if (parseInfo.fUseUniversalTime) {
                try {
                    returnValue = returnValue.ToLocalTime();
                } catch (ArgumentOutOfRangeException) {
                    return (ParseFormatError(isThrowExp, "Format_DateOutOfRange"));
                }
            }
            return (true);
        }


         // This method should never be called.  Its sole purpose is to shut up the compiler
        //    because it warns about private fields that are never used.  Most of these fields
        //    are used in unmanaged code.
#if _DEBUG
        internal String[] NeverCallThis()
        {
            BCLDebug.Assert(false,"NeverCallThis");
            String[] i = invariantMonthNames;
            i = invariantAbbrevMonthNames;
            i = invariantDayNames;
            return invariantAbbrevDayNames;
        }
#endif
   }

    //
    // This is a string parsing helper which wraps a String object.
    // It has a Index property which tracks
    // the current parsing pointer of the string.
    //
    [Serializable()]
    internal 
    class __DTString
    {
        //
        // Value propery: stores the real string to be parsed.
        //
        internal String Value;

        //
        // Index property: points to the character that we are currently parsing.
        //
        internal int Index = -1;

        // The length of Value string.
        internal int len = 0;

        private CompareInfo m_info;

        internal __DTString()
        {
            Value = "";
        }

        internal __DTString(String str)
        {
            Value = str;
            len = Value.Length;
            m_info = Thread.CurrentThread.CurrentCulture.CompareInfo;
        }

        internal CompareInfo CompareInfo {
            get {
                return m_info;
            }
        }

        //
        // Advance the Index.  
        // Return true if Index is NOT at the end of the string.
        //
        // Typical usage:
        // while (str.GetNext())
        // {
        //     char ch = str.GetChar()
        // }
        internal bool GetNext() {
            Index++;
            return (Index < len);
        }

        //
        // Return the word starting from the current index.
        // Index will not be updated.
        //
        internal int FindEndOfCurrentWord() {
            int i = Index;
            while (i < len) {
                if (Value[i] == ' ' || Value[i] == ',' || Value[i] == '/'' || Char.IsDigit(Value[i])) {
                    break;
                }
                i++;
            }
            return i;
        }

        internal String PeekCurrentWord() {
            int endIndex = FindEndOfCurrentWord();
            return Value.Substring(Index, (endIndex - Index));
        }

        internal bool MatchSpecifiedWord(String target) {
            return MatchSpecifiedWord(target, target.Length + Index);
        }
        
        internal bool MatchSpecifiedWord(String target, int endIndex) {
            int count = endIndex - Index;

            if (count != target.Length) {
                return false;
            }

            if (Index + count > len) {
                return false;
            }

            return (m_info.Compare(Value, Index, count, target, 0, count, CompareOptions.IgnoreCase)==0);
        }

        internal bool StartsWith(String target, bool checkWordBoundary) {
            if (target.Length > (Value.Length - Index)) {
                return false;
            }

            if (m_info.Compare(Value, Index, target.Length, target, 0, target.Length, CompareOptions.IgnoreCase)!=0) {
                return (false);
            }

            if (checkWordBoundary) {
                int nextCharIndex = Index + target.Length;
                if (nextCharIndex < Value.Length) {
                    if (Char.IsLetter(Value[nextCharIndex])) {
                        return (false);
                    }
                }
            }
            return (true);
        }
        
        //
        // Check to see if the string starting from Index is a prefix of 
        // str. 
        // If a match is found, true value is returned and Index is updated to the next character to be parsed.
        // Otherwise, Index is unchanged.
        //
        internal bool Match(String str) {
            if (++Index >= len) {
                return (false);
            }

            if (str.Length > (Value.Length - Index)) {
                return false;
            }
            
            if (m_info.Compare(Value, Index, str.Length, str, 0, str.Length, CompareOptions.Ordinal)==0) {
                // Update the Index to the end of the matching string.
                // So the following GetNext()/Match() opeartion will get
                // the next character to be parsed.
                Index += (str.Length - 1);
                return (true);
            }
            return (false);
        }

        internal bool Match(char ch) {
            if (++Index >= len) {
                return (false);
            }
            if (Value[Index] == ch) {
                return (true);
            }
            return (false);
        }

        //
        // Trying to match an array of words.
        // Return true when one of the word in the array matching with substring
        // starting from the current index.
        // If the words array is null, also return true, assuming that there is a match.
        //
        internal bool MatchWords(String[] words) {
            if (words == null) {
                return (true);
            }

            if (Index >= len) {
                return (false);
            }
            for (int i = 0; i < words.Length; i++) {
                if (words[i].Length <= (Value.Length - Index)) {
                    if (m_info.Compare(
                        Value, Index, words[i].Length, words[i], 0, words[i].Length, CompareOptions.IgnoreCase)==0) {
                        Index += words[i].Length;
                        return (true);
                    }
                }
            }
            return (false);
        }

        //
        // Get the number of repeat character after the current character.
        // For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index
        // will point to the second ':'.
        //
        internal int GetRepeatCount() {
            char repeatChar = Value[Index];
            int pos = Index + 1;
            while ((pos < len) && (Value[pos] == repeatChar)) {
                pos++;
            }
            int repeatCount = (pos - Index);
            // Update the Index to the end of the repeated characters.
            // So the following GetNext() opeartion will get
            // the next character to be parsed.
            Index = pos - 1;
            return (repeatCount);
        }

        // Return false when end of string is encountered or a non-digit character is found.
        internal bool GetNextDigit() {
            if (++Index >= len) {
                return (false);
            }
            return (DateTimeParse.IsDigit(Value[Index]));
        }

        // Return null when end of string is encountered or a matching quote character is not found.
        // Throws FormatException if the matching quote character can not be found.
        internal String GetQuotedString(char quoteChar) {
            // When we enter this method, Index points to the first quote character.
            int oldPos = ++Index;
            while ((Index < len) && (Value[Index] != quoteChar)) {
                Index++;
            }
            if (Index == len) {
                // If we move past len, it means a matching quote character is not found.
                // 'ABC'    'ABC
                // 01234    0123
                return (null);
            }
            // When we leave this method, Index points to the matching quote character.
            return (Value.Substring(oldPos, Index - oldPos));
        }
        
        //
        // Get the current character.
        //
        internal char GetChar() {
            BCLDebug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
            return (Value[Index]);
        }

        //
        // Convert the current character to a digit, and return it.
        //
        internal int GetDigit() {
            BCLDebug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
            BCLDebug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
            return (Value[Index] - '0');
        }

        //
        // Enjoy eating white spaces.
        //
        // Return false if end of string is encountered.
        //
        internal void SkipWhiteSpaces()
        {        
            // Look ahead to see if the next character
            // is a whitespace.
            while (Index+1 < len)
            {
                char ch = Value[Index+1];
                if (!Char.IsWhiteSpace(ch)) {
                    return;
                }
                Index++;
            }
            return;
        }    

        //
        // Enjoy eating white spaces and commas.
        //
        // Return false if end of string is encountered.
        //
        internal bool SkipWhiteSpaceComma()
        {
            char ch;

            if (Index >= len) {
                return (false);
            }
            
            if (!Char.IsWhiteSpace(ch=Value[Index]) && ch!=',')
            {
                return (true);
            } 
            
            while (++Index < len)
            {
                ch = Value[Index];
                if (!Char.IsWhiteSpace(ch) && ch != ',')
                {
                    return (true);
                }
                // Nothing here.
            }
            return (false);
        }

        internal void TrimTail() {
            int i = len - 1;
            while (i >= 0 && Char.IsWhiteSpace(Value[i])) {
                i--;
            }
            Value = Value.Substring(0, i + 1);
            len = Value.Length;
        }

        // Trim the trailing spaces within a quoted string.
        // Call this after TrimTail() is done.
        internal void RemoveTrailingInQuoteSpaces() {
            int i = len - 1;
            if (i <= 1) {
                return;
            }
            char ch = Value[i];
            // Check if the last character is a quote.
            if (ch == '/'' || ch == '/"') {
                if (Char.IsWhiteSpace(Value[i-1])) {
                    i--;
                    while (i >= 1 && Char.IsWhiteSpace(Value[i-1])) {
                        i--;
                    }
                    Value = Value.Remove(i, Value.Length - 1 - i);
                    len = Value.Length;
                }
            }
        }

        // Trim the leading spaces within a quoted string.
        // Call this after the leading spaces before quoted string are trimmed.
        internal void RemoveLeadingInQuoteSpaces() {
            if (len <= 2) {
                return;
            }
            int i = 0;
            char ch = Value[i];
            // Check if the last character is a quote.
            if (ch == '/'' || ch == '/"') {
                while ((i + 1) < len && Char.IsWhiteSpace(Value[i+1])) {
                    i++;
                }
                if (i != 0) {
                    Value = Value.Remove(1, i);
                    len = Value.Length;
                }
            }
        }
        
    }

    //
    // The buffer to store the parsing token.
    //
    [Serializable()]
    internal 
    class DateTimeToken {
        internal int dtt;    // Store the token
        internal int suffix; // Store the CJK Year/Month/Day suffix (if any)
        internal int num;    // Store the number that we are parsing (if any)
    }

    //
    // The buffer to store temporary parsing information.
    //
    [Serializable()]
    internal 
    class DateTimeRawInfo {
        internal int[] num;
        internal int numCount   = 0;
        internal int month      = -1;
        internal int year       = -1;
        internal int dayOfWeek  = -1;
        internal int era        = -1;
        internal int timeMark   = -1;  // Value could be -1, TM_AM or TM_PM.
        internal double fraction = -1;
        //
        //
        internal bool timeZone = false;


        internal DateTimeRawInfo()
        {
            num = new int[] {-1, -1, -1};
        }
    }

    //
    // This will store the result of the parsing.  And it will be eventually
    // used to construct a DateTime instance.
    //
    [Serializable()]
    internal 
    class DateTimeResult
    {
        internal int Year    = -1;
        internal int Month   = -1;
        internal int Day     = -1;
        //
        // Set time defualt to 00:00:00.
        //
        internal int Hour    = 0;
        internal int Minute  = 0;
        internal int Second = 0;
        internal double fraction = -1;
        
        internal int era = -1;

        internal bool timeZoneUsed = false;
        internal TimeSpan timeZoneOffset;

        internal Calendar calendar;

        internal DateTimeResult()
        {
        }

        internal virtual void SetDate(int year, int month, int day)
        {
            Year = year;
            Month = month;
            Day = day;
        }
    }

    [Serializable]
    internal class ParsingInfo {
        internal Calendar calendar;
        internal int dayOfWeek = -1;
        internal int timeMark = -1;
        internal TimeSpan timeZoneOffset = new TimeSpan();

        internal bool fUseUniversalTime = false;
        internal bool fUseHour12 = false;
        internal bool fUseTwoDigitYear = false;
        internal bool fUseTimeZone = false;
        internal bool fAllowInnerWhite = false;        
        internal bool fAllowTrailingWhite = false;

        internal ParsingInfo() {
        }
    }
}
import struct import os import tkinter as tk from tkinter import ttk, messagebox, simpledialog, filedialog, scrolledtext import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import platform import sys import datetime import math import hashlib import re import binascii class FAT32Parser: def __init__(self, device_path, readonly=True): self.device_path = device_path self.readonly = readonly self.sector_size = 512 self.cluster_size = 0 self.fat_start = 0 self.data_start = 0 self.root_cluster = 0 self.fat = [] self.free_clusters = [] self.total_clusters = 0 try: # 打开设备 mode = 'rb' if readonly else 'r+b' self.fd = open(device_path, mode) except Exception as e: raise ValueError(f"无法打开设备: {e}") try: # 读取引导扇区 self.fd.seek(0) boot_sector = self.fd.read(512) # 检查FAT32签名 if len(boot_sector) < 512 or boot_sector[510] != 0x55 or boot_sector[511] != 0xAA: raise ValueError("无效的引导扇区签名 - 可能不是FAT32格式") # 解析关键参数 self.sectors_per_cluster = boot_sector[13] if self.sectors_per_cluster not in [1, 2, 4, 8, 16, 32, 64, 128]: raise ValueError("无效的每簇扇区数") self.reserved_sectors = struct.unpack('<H', boot_sector[14:16])[0] self.num_fats = boot_sector[16] self.sectors_per_fat = struct.unpack('<I', boot_sector[36:40])[0] self.root_cluster = struct.unpack('<I', boot_sector[44:48])[0] self.total_sectors = struct.unpack('<I', boot_sector[32:36])[0] or struct.unpack('<I', boot_sector[40:44])[0] # 计算关键位置 self.cluster_size = self.sectors_per_cluster * self.sector_size self.fat_start = self.reserved_sectors * self.sector_size self.data_start = self.fat_start + (self.num_fats * self.sectors_per_fat * self.sector_size) # 计算总簇数 self.total_clusters = (self.total_sectors - self.reserved_sectors - self.num_fats * self.sectors_per_fat) // self.sectors_per_cluster # 加载FAT表 self._load_fat_table() # 检查根簇号是否有效 if self.root_cluster < 2 or self.root_cluster >= len(self.fat): raise ValueError(f"无效的根簇号: {self.root_cluster}") # 扫描空闲簇 self._find_free_clusters() # 保存引导扇区信息 self.boot_sector_info = self._parse_boot_sector(boot_sector) except Exception as e: self.fd.close() raise e def _parse_boot_sector(self, boot_sector): """解析引导扇区信息""" info = {} info['OEM Name'] = boot_sector[3:11].decode('ascii', errors='replace').strip() info['Bytes Per Sector'] = struct.unpack('<H', boot_sector[11:13])[0] info['Sectors Per Cluster'] = boot_sector[13] info['Reserved Sectors'] = struct.unpack('<H', boot_sector[14:16])[0] info['Number of FATs'] = boot_sector[16] info['Root Entries'] = struct.unpack('<H', boot_sector[17:19])[0] # FAT16 only info['Total Sectors 16'] = struct.unpack('<H', boot_sector[19:21])[0] # FAT16 only info['Media Descriptor'] = hex(boot_sector[21]) info['Sectors Per FAT 16'] = struct.unpack('<H', boot_sector[22:24])[0] # FAT16 only info['Sectors Per Track'] = struct.unpack('<H', boot_sector[24:26])[0] info['Number of Heads'] = struct.unpack('<H', boot_sector[26:28])[0] info['Hidden Sectors'] = struct.unpack('<I', boot_sector[28:32])[0] info['Total Sectors 32'] = struct.unpack('<I', boot_sector[32:36])[0] # FAT32 specific info['Sectors Per FAT'] = struct.unpack('<I', boot_sector[36:40])[0] info['Flags'] = struct.unpack('<H', boot_sector[40:42])[0] info['FAT Version'] = struct.unpack('<H', boot_sector[42:44])[0] info['Root Directory Cluster'] = struct.unpack('<I', boot_sector[44:48])[0] info['FSInfo Sector'] = struct.unpack('<H', boot_sector[48:50])[0] info['Backup Boot Sector'] = struct.unpack('<H', boot_sector[50:52])[0] info['Volume Label'] = boot_sector[71:82].decode('ascii', errors='replace').strip() info['File System Type'] = boot_sector[82:90].decode('ascii', errors='replace').strip() return info def _load_fat_table(self): """加载FAT表到内存""" self.fd.seek(self.fat_start) fat_size = self.sectors_per_fat * self.sector_size fat_data = self.fd.read(fat_size) if len(fat_data) != fat_size: raise ValueError("读取FAT表失败") # 解析FAT32表项 (每4字节一个簇) self.fat = [] for i in range(0, len(fat_data), 4): # 只取低28位(FAT32实际用28位) entry = struct.unpack('<I', fat_data[i:i+4])[0] & 0x0FFFFFFF self.fat.append(entry) def _find_free_clusters(self): """查找所有空闲簇""" self.free_clusters = [] for cluster_idx in range(2, len(self.fat)): # 簇0和1保留 if self.fat[cluster_idx] == 0: self.free_clusters.append(cluster_idx) def get_cluster_chain(self, start_cluster): """获取文件的簇链""" if start_cluster < 2 or start_cluster >= len(self.fat): return [] # 无效簇号 chain = [] current = start_cluster visited = set() # 追踪簇链直到结束 while current < 0x0FFFFFF8: # 文件结束标记 if current in visited: messagebox.showwarning("警告", f"发现循环簇链!簇 {current} 已被访问过") break # 防止无限循环 if current >= len(self.fat): messagebox.showwarning("警告", f"簇链越界!簇 {current} 超出FAT表范围") break # 越界保护 chain.append(current) visited.add(current) next_cluster = self.fat[current] if next_cluster == 0 or next_cluster >= 0x0FFFFFF8: break current = next_cluster return chain def get_fat_chain(self, start_cluster): """获取文件的FAT链(包含FAT表值)""" chain = self.get_cluster_chain(start_cluster) fat_chain = [] for cluster in chain: if cluster < len(self.fat): fat_chain.append((cluster, self.fat[cluster])) return fat_chain def read_directory(self, cluster): """读取目录内容""" entries = [] chain = self.get_cluster_chain(cluster) if not chain: return entries # 长文件名缓存 lfn_parts = [] for c in chain: # 计算簇对应的扇区 sector_offset = self.data_start + (c - 2) * self.cluster_size if sector_offset < 0 or sector_offset > self.get_disk_size(): break self.fd.seek(sector_offset) data = self.fd.read(self.cluster_size) if len(data) < self.cluster_size: break # 读取不完整 # 解析每个目录项(32字节) for i in range(0, len(data), 32): entry = data[i:i+32] if len(entry) < 32: continue if entry[0] == 0x00: # 空闲 lfn_parts = [] # 重置长文件名缓存 continue if entry[0] == 0xE5: # 删除 lfn_parts = [] # 重置长文件名缓存 continue attr = entry[11] if attr == 0x0F: # 长文件名条目 # 解析长文件名片段 seq = entry[0] name_part = entry[1:11] + entry[14:26] + entry[28:32] # 移除尾部的0x00 name_part = name_part.split(b'\x00')[0] try: name_part = name_part.decode('utf-16le', errors='ignore') except: name_part = '?' lfn_parts.append((seq, name_part)) continue # 短文件名条目 name = entry[0:8].decode('latin-1', errors='ignore').strip() ext = entry[8:11].decode('latin-1', errors='ignore').strip() fullname = name + ('.' + ext if ext else '') # 如果有长文件名,使用它 if lfn_parts: # 排序并组合长文件名片段 lfn_parts.sort(key=lambda x: x[0]) long_name = ''.join(part for _, part in reversed(lfn_parts)) fullname = long_name.strip() lfn_parts = [] # 解析属性 is_dir = bool(attr & 0x10) is_volume = bool(attr & 0x08) is_hidden = bool(attr & 0x02) is_system = bool(attr & 0x04) is_archive = bool(attr & 0x20) # 获取起始簇号 start_cluster_hi = struct.unpack('<H', entry[20:22])[0] start_cluster_lo = struct.unpack('<H', entry[26:28])[0] start_cluster = (start_cluster_hi << 16) | start_cluster_lo # 文件大小 size = struct.unpack('<I', entry[28:32])[0] # 解析时间日期 create_time = struct.unpack('<H', entry[14:16])[0] create_date = struct.unpack('<H', entry[16:18])[0] mod_time = struct.unpack('<H', entry[22:24])[0] mod_date = struct.unpack('<H', entry[24:26])[0] # 跳过卷标 if is_volume: continue # 添加所有条目 entries.append({ 'name': fullname, 'is_dir': is_dir, 'is_hidden': is_hidden, 'is_system': is_system, 'is_archive': is_archive, 'start_cluster': start_cluster, 'size': size, 'create_time': self._parse_dos_datetime(create_date, create_time), 'mod_time': self._parse_dos_datetime(mod_date, mod_time) }) return entries def _parse_dos_datetime(self, date, time): """解析DOS日期时间格式""" try: # 解析日期: 7位年(从1980), 4位月, 5位日 year = ((date & 0xFE00) >> 9) + 1980 month = (date & 0x01E0) >> 5 day = date & 0x001F # 解析时间: 5位时, 6位分, 5位秒(以2秒为单位) hour = (time & 0xF800) >> 11 minute = (time & 0x07E0) >> 5 second = (time & 0x001F) * 2 return f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}" except: return "未知时间" def read_file_content(self, start_cluster, size): """读取文件内容""" content = b'' chain = self.get_cluster_chain(start_cluster) if not chain: return content bytes_remaining = size for cluster in chain: if bytes_remaining <= 0: break # 计算簇位置 sector_offset = self.data_start + (cluster - 2) * self.cluster_size if sector_offset < 0 or sector_offset > self.get_disk_size(): break self.fd.seek(sector_offset) # 读取簇内容 bytes_to_read = min(bytes_remaining, self.cluster_size) try: chunk = self.fd.read(bytes_to_read) if not chunk: break content += chunk bytes_remaining -= len(chunk) except Exception as e: messagebox.showerror("读取错误", f"读取簇 {cluster} 失败: {str(e)}") break return content def get_disk_size(self): """获取磁盘大小""" try: self.fd.seek(0, 2) # 移动到文件末尾 return self.fd.tell() except Exception as e: messagebox.showerror("错误", f"获取磁盘大小失败: {str(e)}") return 0 def create_file(self, parent_cluster, filename, content): """在指定目录创建文件""" if self.readonly: raise PermissionError("只读模式不允许写操作") # 1. 分配簇链 clusters_needed = math.ceil(len(content) / self.cluster_size) if clusters_needed > len(self.free_clusters): raise IOError("磁盘空间不足") allocated_clusters = self.free_clusters[:clusters_needed] self.free_clusters = self.free_clusters[clusters_needed:] # 2. 更新FAT表 for i in range(len(allocated_clusters)): cluster = allocated_clusters[i] if i == len(allocated_clusters) - 1: # 最后一个簇标记为EOF self.fat[cluster] = 0x0FFFFFFF else: # 指向下一个簇 self.fat[cluster] = allocated_clusters[i+1] # 3. 写入FAT表 self._write_fat_table() # 4. 写入文件内容 for i, cluster in enumerate(allocated_clusters): offset = self.data_start + (cluster - 2) * self.cluster_size self.fd.seek(offset) # 写入当前簇的数据 start = i * self.cluster_size end = min((i+1) * self.cluster_size, len(content)) self.fd.write(content[start:end]) # 5. 在父目录创建目录项 self._create_directory_entry(parent_cluster, { 'name': filename, 'is_dir': False, 'start_cluster': allocated_clusters[0], 'size': len(content) }) return allocated_clusters[0] def create_directory(self, parent_cluster, dirname): """在指定目录创建子目录""" if self.readonly: raise PermissionError("只读模式不允许写操作") # 1. 分配一个簇给新目录 if not self.free_clusters: raise IOError("磁盘空间不足") cluster = self.free_clusters[0] self.free_clusters = self.free_clusters[1:] # 2. 更新FAT表 (目录结束) self.fat[cluster] = 0x0FFFFFFF self._write_fat_table() # 3. 初始化目录内容 (创建 ... 条目) self._initialize_directory(cluster, parent_cluster) # 4. 在父目录创建目录项 self._create_directory_entry(parent_cluster, { 'name': dirname, 'is_dir': True, 'start_cluster': cluster, 'size': 0 }) return cluster def _initialize_directory(self, cluster, parent_cluster): """初始化新目录内容""" # 计算簇位置 offset = self.data_start + (cluster - 2) * self.cluster_size # 创建 . 条目 dot_entry = self._create_dir_entry(".", cluster, True) # 创建 .. 条目 dotdot_entry = self._create_dir_entry("..", parent_cluster, True) # 写入目录内容 self.fd.seek(offset) self.fd.write(dot_entry) self.fd.write(dotdot_entry) # 填充剩余空间为0 remaining = self.cluster_size - len(dot_entry) - len(dotdot_entry) self.fd.write(b'\x00' * remaining) def _create_dir_entry(self, name, cluster, is_dir): """创建目录项字节数据""" # 短文件名格式 (8.3) if len(name) > 8 and '.' not in name: base, ext = name[:8], "" else: parts = name.split('.') base = parts[0].upper()[:8] ext = parts[1].upper()[:3] if len(parts) > 1 else "" # 填充空格 base = base.ljust(8, ' ') ext = ext.ljust(3, ' ') # 创建32字节条目 entry = bytearray(32) # 文件名 (8字节) entry[0:8] = base.encode('latin-1') # 扩展名 (3字节) entry[8:11] = ext.encode('latin-1') # 属性 (目录) entry[11] = 0x10 if is_dir else 0x20 # 目录或存档 # 创建时间和日期 (当前时间) now = datetime.datetime.now() create_time = self._to_dos_time(now) create_date = self._to_dos_date(now) entry[14:16] = struct.pack('<H', create_time) entry[16:18] = struct.pack('<H', create_date) # 修改时间和日期 mod_time = create_time mod_date = create_date entry[22:24] = struct.pack('<H', mod_time) entry[24:26] = struct.pack('<H', mod_date) # 起始簇号 entry[20:22] = struct.pack('<H', (cluster >> 16) & 0xFFFF) # 高16位 entry[26:28] = struct.pack('<H', cluster & 0xFFFF) # 低16位 # 文件大小 (目录为0) entry[28:32] = struct.pack('<I', 0) return entry def _to_dos_time(self, dt): """将datetime转换为DOS时间格式""" return ((dt.hour << 11) | (dt.minute << 5) | (dt.second // 2)) def _to_dos_date(self, dt): """将datetime转换为DOS日期格式""" return (((dt.year - 1980) << 9) | (dt.month << 5) | dt.day) def _create_directory_entry(self, parent_cluster, entry_info): """在父目录中添加新的目录项""" # 获取父目录的所有簇 clusters = self.get_cluster_chain(parent_cluster) if not clusters: raise IOError("父目录无效") # 查找空闲目录槽 for cluster in clusters: offset = self.data_start + (cluster - 2) * self.cluster_size self.fd.seek(offset) data = self.fd.read(self.cluster_size) for i in range(0, len(data), 32): pos = offset + i entry = data[i:i+32] # 找到空闲或已删除的条目 if len(entry) < 32 or entry[0] in [0x00, 0xE5]: # 创建新条目 new_entry = self._create_dir_entry( entry_info['name'], entry_info['start_cluster'], entry_info['is_dir'] ) # 设置文件大小 if not entry_info['is_dir']: new_entry[28:32] = struct.pack('<I', entry_info['size']) # 写入新条目 self.fd.seek(pos) self.fd.write(new_entry) return # 如果没有找到空闲槽,分配新簇 if not self.free_clusters: raise IOError("磁盘空间不足") new_cluster = self.free_clusters[0] self.free_clusters = self.free_clusters[1:] # 更新FAT表 self.fat[clusters[-1]] = new_cluster # 当前最后一个簇指向新簇 self.fat[new_cluster] = 0x0FFFFFFF # 新簇标记为EOF self._write_fat_table() # 初始化新簇 self.fd.seek(self.data_start + (new_cluster - 2) * self.cluster_size) self.fd.write(b'\x00' * self.cluster_size) # 写入新条目到新簇的第一个位置 new_entry = self._create_dir_entry( entry_info['name'], entry_info['start_cluster'], entry_info['is_dir'] ) if not entry_info['is_dir']: new_entry[28:32] = struct.pack('<I', entry_info['size']) self.fd.seek(self.data_start + (new_cluster - 2) * self.cluster_size) self.fd.write(new_entry) def _write_fat_table(self): """将FAT表写回磁盘""" # 更新所有FAT副本 for fat_copy in range(self.num_fats): offset = self.fat_start + fat_copy * self.sectors_per_fat * self.sector_size self.fd.seek(offset) # 构建FAT表数据 fat_data = bytearray() for entry in self.fat: # 确保使用32位格式 fat_data += struct.pack('<I', entry) # 写入FAT表 self.fd.write(fat_data) def close(self): """安全关闭文件句柄""" if hasattr(self, 'fd') and self.fd: self.fd.close() class FAT32Explorer: def __init__(self, root, device_path, readonly=True): self.root = root self.root.title(f"FAT32 文件系统分析工具 - {device_path}") self.root.geometry("1400x900") self.root.protocol("WM_DELETE_WINDOW", self.on_close) self.device_path = device_path self.readonly = readonly self.current_cluster = None self.current_path = "/" self.selected_file = None self.file_content_cache = None self.canvas = None self.cluster_canvas = None # 创建GUI布局 self._create_widgets() # 在后台加载文件系统 self.loading = True self.status = tk.StringVar() self.status.set("正在加载文件系统...") self.root.after(100, self._load_filesystem) def _create_widgets(self): # 创建主框架 main_frame = tk.Frame(self.root) main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 顶部工具栏 toolbar = tk.Frame(main_frame) toolbar.pack(fill=tk.X, pady=(0, 10)) mode_text = "只读模式" if self.readonly else "读写模式" mode_color = "green" if self.readonly else "red" tk.Label(toolbar, text=f"模式: {mode_text}", fg=mode_color, font=("Arial", 10, "bold")).pack(side=tk.LEFT, padx=10) # 路径导航 self.path_var = tk.StringVar(value="路径: /") tk.Label(toolbar, textvariable=self.path_var, font=("Arial", 10)).pack(side=tk.LEFT, padx=10) # 操作按钮 btn_frame = tk.Frame(toolbar) btn_frame.pack(side=tk.RIGHT) tk.Button(btn_frame, text="刷新", command=self.refresh).pack(side=tk.LEFT, padx=2) tk.Button(btn_frame, text="物理布局", command=self.show_physical_layout).pack(side=tk.LEFT, padx=2) tk.Button(btn_frame, text="FAT表信息", command=self.show_fat_info).pack(side=tk.LEFT, padx=2) if not self.readonly: tk.Button(btn_frame, text="新建文件", command=self.create_file_dialog).pack(side=tk.LEFT, padx=2) tk.Button(btn_frame, text="新建目录", command=self.create_directory_dialog).pack(side=tk.LEFT, padx=2) tk.Button(btn_frame, text="写入测试文件", command=self.write_test_file).pack(side=tk.LEFT, padx=2) # 主分割窗口 self.paned_window = tk.PanedWindow(main_frame, orient=tk.HORIZONTAL) self.paned_window.pack(fill=tk.BOTH, expand=True) # 左侧面板 (目录树) self.left_frame = tk.LabelFrame(self.paned_window, text="目录结构") self.paned_window.add(self.left_frame, width=300) # 目录树 self.tree = ttk.Treeview(self.left_frame, show='tree', columns=("size")) self.tree.heading("#0", text="名称") self.tree.heading("size", text="大小") self.tree.column("size", width=80, anchor='e') self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) scrollbar = ttk.Scrollbar(self.left_frame, orient=tk.VERTICAL, command=self.tree.yview) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.tree.configure(yscrollcommand=scrollbar.set) self.tree.bind('<<TreeviewSelect>>', self.on_tree_select) # 右侧面板 self.right_frame = tk.PanedWindow(self.paned_window, orient=tk.VERTICAL) self.paned_window.add(self.right_frame) # 上部: 文件列表 file_frame = tk.LabelFrame(self.right_frame, text="当前目录内容") file_frame.pack(fill=tk.BOTH, expand=True) # 文件列表表头 columns = ("name", "size", "type", "cluster", "modified", "attributes") self.file_tree = ttk.Treeview(file_frame, columns=columns, show="headings") # 设置列 self.file_tree.heading("name", text="名称") self.file_tree.heading("size", text="大小") self.file_tree.heading("type", text="类型") self.file_tree.heading("cluster", text="起始簇") self.file_tree.heading("modified", text="修改时间") self.file_tree.heading("attributes", text="属性") self.file_tree.column("name", width=200) self.file_tree.column("size", width=80, anchor='e') self.file_tree.column("type", width=80) self.file_tree.column("cluster", width=80, anchor='e') self.file_tree.column("modified", width=150) self.file_tree.column("attributes", width=80) self.file_tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) self.file_tree.bind('<<TreeviewSelect>>', self.on_file_select) self.file_tree.bind('<Double-1>', self.on_file_double_click) # 文件列表滚动条 file_scrollbar = ttk.Scrollbar(file_frame, orient=tk.VERTICAL, command=self.file_tree.yview) file_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.file_tree.configure(yscrollcommand=file_scrollbar.set) # 添加右键菜单 self.file_menu = tk.Menu(self.root, tearoff=0) self.file_menu.add_command(label="查看内容", command=self.show_file_content) self.file_menu.add_command(label="查看簇链", command=self.show_cluster_chain) self.file_menu.add_command(label="计算哈希", command=self.calculate_hash) self.file_tree.bind("<Button-3>", self.show_context_menu) # 下部: 簇状态可视化 self.cluster_frame = tk.LabelFrame(self.right_frame, text="簇分配图") self.cluster_frame.pack(fill=tk.BOTH, expand=True) # 簇链可视化框架 self.cluster_canvas_frame = tk.Frame(self.cluster_frame) self.cluster_canvas_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 底部: 状态栏 self.status = tk.StringVar() self.status.set("就绪" + (" - 只读模式" if self.readonly else " - 读写模式")) status_bar = tk.Label(self.root, textvariable=self.status, bd=1, relief=tk.SUNKEN, anchor=tk.W) status_bar.pack(side=tk.BOTTOM, fill=tk.X) # 添加文件内容查看器 (弹出窗口) self.content_window = None self.cluster_window = None def _load_filesystem(self): """安全加载文件系统""" try: self.parser = FAT32Parser(self.device_path, self.readonly) self.root_cluster = self.parser.root_cluster # 加载根目录 self._show_root_directory() self.status.set(f"就绪 | 总簇数: {len(self.parser.fat)} | 空闲簇: {len(self.parser.free_clusters)}") self.loading = False # 更新簇分配图 self._update_cluster_map() except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("初始化错误", f"加载文件系统失败: {str(e)}") self.root.after(100, self.root.destroy) def _show_root_directory(self): """显示根目录""" self.tree.delete(*self.tree.get_children()) self.file_tree.delete(*self.file_tree.get_children()) self.current_path = "/" self.path_var.set(f"路径: {self.current_path}") # 添加根节点 root_id = self.tree.insert('', 'end', text="根目录", values=[""], open=True) self.current_cluster = self.root_cluster # 加载根目录内容 self._load_directory(root_id, self.root_cluster) def _load_directory(self, parent_id, cluster): """加载目录内容到树视图和列表""" try: entries = self.parser.read_directory(cluster) self.current_entries = entries # 清空文件列表 self.file_tree.delete(*self.file_tree.get_children()) # 添加到文件列表 for entry in entries: # 跳过特殊目录项 '.' 和 '..' if entry['name'] in ['.', '..']: continue item_type = "目录" if entry['is_dir'] else "文件" size = self.format_size(entry['size']) if not entry['is_dir'] else "" # 构建属性字符串 attributes = [] if entry['is_hidden']: attributes.append("隐藏") if entry['is_system']: attributes.append("系统") if entry['is_archive']: attributes.append("存档") attr_str = ", ".join(attributes) self.file_tree.insert('', 'end', values=( entry['name'], size, item_type, entry['start_cluster'], entry['mod_time'], attr_str )) # 添加到树视图 for entry in entries: # 跳过特殊目录项 '.' 和 '..' if entry['name'] in ['.', '..']: continue if entry['is_dir']: size = self.format_size(entry['size']) node_id = self.tree.insert(parent_id, 'end', text=entry['name'], values=[entry['start_cluster']], tags=('dir',)) # 添加一个虚拟节点以便展开 self.tree.insert(node_id, 'end', text="加载中...", tags=('dummy',)) # 配置标签样式 self.tree.tag_configure('dir', foreground='blue') self.tree.tag_configure('dummy', foreground='gray') self.status.set(f"显示目录: 簇 {cluster} | 条目: {len(entries)}") except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("目录错误", f"读取目录失败: {str(e)}") def _update_cluster_map(self): """更新簇状态可视化""" if not hasattr(self, 'parser'): return # 清除现有图表 if self.canvas: self.canvas.get_tk_widget().destroy() fig, ax = plt.subplots(figsize=(10, 3)) # 简化的簇状态展示 max_clusters = min(1000, len(self.parser.fat)) # 创建状态数组,每个元素对应一个簇的状态 cluster_status = [] # 收集前max_clusters个簇的状态 for cluster_idx in range(max_clusters): # 标记特殊簇 if cluster_idx == 0: cluster_status.append(4) # 特殊簇 elif cluster_idx == 1: cluster_status.append(4) # 特殊簇 elif self.parser.fat[cluster_idx] == 0: cluster_status.append(0) # 空闲 elif self.parser.fat[cluster_idx] >= 0x0FFFFFF8: cluster_status.append(1) # 文件结束 elif self.parser.fat[cluster_idx] == 0x0FFFFFF7: cluster_status.append(3) # 坏簇 else: cluster_status.append(2) # 使用中 # 修复:将一维列表转换为二维数组用于热力图 # 计算合适的行数和列数 num_cols = 50 # 每行50个簇 num_rows = (len(cluster_status) + num_cols - 1) // num_cols # 创建二维数组 heatmap_data = [] for i in range(num_rows): start_idx = i * num_cols end_idx = min((i + 1) * num_cols, len(cluster_status)) row = cluster_status[start_idx:end_idx] # 如果行不满,填充0 if len(row) < num_cols: row += [0] * (num_cols - len(row)) heatmap_data.append(row) # 使用不同颜色 cmap = plt.cm.colors.ListedColormap([ 'green', # 0: 空闲 'red', # 1: 文件结束 'blue', # 2: 使用中 'black', # 3: 坏簇 'gray', # 4: 特殊簇 ]) # 绘制热力图 img = ax.imshow(heatmap_data, cmap=cmap, aspect='auto') # 添加颜色条 cbar = fig.colorbar(img, ax=ax, ticks=[0, 1, 2, 3, 4]) cbar.ax.set_yticklabels(['空闲', '结束簇', '使用中', '坏簇', '特殊簇']) ax.set_title(f'簇分配图 (前{max_clusters}个簇)') ax.set_xlabel('簇号 (每行50个)') ax.set_ylabel('簇组') # 添加网格线 ax.grid(which='major', color='gray', linestyle='-', linewidth=0.5) ax.set_xticks(range(0, num_cols, 5)) ax.set_yticks(range(0, num_rows, 5)) # 嵌入到Canvas canvas = FigureCanvasTkAgg(fig, master=self.cluster_canvas_frame) canvas.draw() canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True) self.canvas = canvas def show_context_menu(self, event): """显示右键菜单""" item = self.file_tree.identify_row(event.y) if item: self.file_tree.selection_set(item) self.file_menu.post(event.x_root, event.y_root) def on_tree_select(self, event): """处理树节点选择事件""" if self.loading: return selected = self.tree.selection() if not selected: return item = self.tree.item(selected[0]) if 'values' in item and item['values']: # 如果是虚拟节点,跳过 if 'dummy' in self.tree.item(selected[0], "tags"): return # 获取簇号(目录节点才有) if 'dir' in self.tree.item(selected[0], "tags"): cluster = self.tree.item(selected[0])['values'][0] if isinstance(cluster, int) or cluster.isdigit(): self.current_cluster = int(cluster) else: # 根目录 self.current_cluster = self.parser.root_cluster # 构建当前路径 path = [] current_item = selected[0] while current_item: item_text = self.tree.item(current_item)['text'] if item_text != "根目录": path.insert(0, item_text) current_item = self.tree.parent(current_item) self.current_path = "/" + "/".join(path) self.path_var.set(f"路径: {self.current_path}") # 如果节点有子节点但只有一个"加载中"节点,则加载实际内容 children = self.tree.get_children(selected[0]) if children and self.tree.item(children[0])['text'] == "加载中...": self.tree.delete(children[0]) self._load_directory(selected[0], self.current_cluster) else: self._load_directory(selected[0], self.current_cluster) def on_file_select(self, event): """处理文件列表选择事件""" if self.loading: return selected = self.file_tree.selection() if not selected: return item = self.file_tree.item(selected[0]) values = item['values'] if values: # 查找对应的条目 for entry in self.current_entries: if entry['name'] == values[0]: self.selected_file = entry break def on_file_double_click(self, event): """双击文件事件""" if self.selected_file and not self.selected_file['is_dir']: self.show_file_content() def show_file_content(self): """显示文件内容""" if not self.selected_file or self.selected_file['is_dir']: return # 创建弹出窗口 if self.content_window and self.content_window.winfo_exists(): self.content_window.destroy() self.content_window = tk.Toplevel(self.root) self.content_window.title(f"文件内容: {self.selected_file['name']}") self.content_window.geometry("800x600") # 添加文本编辑器 text_frame = tk.Frame(self.content_window) text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 添加文本区域 self.content_text = scrolledtext.ScrolledText(text_frame, wrap=tk.WORD) self.content_text.pack(fill=tk.BOTH, expand=True) # 添加按钮 btn_frame = tk.Frame(self.content_window) btn_frame.pack(fill=tk.X, padx=10, pady=(0, 10)) tk.Button(btn_frame, text="加载内容", command=self.load_file_content).pack(side=tk.LEFT, padx=5) if not self.readonly: tk.Button(btn_frame, text="保存修改", command=self.save_file_content).pack(side=tk.LEFT, padx=5) tk.Button(btn_frame, text="关闭", command=self.content_window.destroy).pack(side=tk.RIGHT, padx=5) def load_file_content(self): """加载文件内容到编辑器""" if not self.selected_file: return try: content = self.parser.read_file_content( self.selected_file['start_cluster'], self.selected_file['size'] ) # 尝试解码为文本 try: decoded = content.decode('utf-8', errors='replace') self.content_text.delete(1.0, tk.END) self.content_text.insert(tk.END, decoded) self.file_content_cache = content self.status.set(f"已加载文件: {self.selected_file['name']}") except UnicodeDecodeError: # 如果是二进制文件,显示十六进制预览 hex_preview = ' '.join(f'{b:02x}' for b in content[:128]) if len(content) > 128: hex_preview += " ..." self.content_text.delete(1.0, tk.END) self.content_text.insert(tk.END, f"二进制文件 (十六进制预览):\n{hex_preview}") self.file_content_cache = content self.status.set(f"已加载二进制文件: {self.selected_file['name']}") except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("读取错误", f"读取文件内容失败: {str(e)}") def save_file_content(self): """保存修改后的文件内容""" if self.readonly or not self.selected_file or not self.file_content_cache: return # 获取新内容 new_content = self.content_text.get(1.0, tk.END).encode('utf-8') # 检查内容是否变化 if new_content == self.file_content_cache: messagebox.showinfo("保存", "内容未更改") return # 确认保存 confirm = messagebox.askyesno("确认保存", f"确定要保存对文件 '{self.selected_file['name']}' 的修改吗?\n" "此操作将直接写入U盘!") if not confirm: return try: # 创建新文件 (如果大小变化) if len(new_content) != len(self.file_content_cache): # 创建新文件 new_cluster = self.parser.create_file( self.current_cluster, self.selected_file['name'], new_content ) # 删除旧文件 (标记为删除) # 在实际应用中应该实现文件删除功能 messagebox.showinfo("保存成功", "文件大小已改变,已创建新文件副本") else: # 直接覆盖内容 chain = self.parser.get_cluster_chain(self.selected_file['start_cluster']) bytes_remaining = len(new_content) for i, cluster in enumerate(chain): if bytes_remaining <= 0: break offset = self.parser.data_start + (cluster - 2) * self.parser.cluster_size self.parser.fd.seek(offset) # 写入当前簇的数据 start = i * self.parser.cluster_size end = min((i+1) * self.parser.cluster_size, len(new_content)) self.parser.fd.write(new_content[start:end]) bytes_remaining -= (end - start) self.status.set(f"文件已保存: {self.selected_file['name']}") messagebox.showinfo("保存成功", "文件内容已更新") # 刷新目录 self.refresh() 修正代码
06-23
import struct import os import tkinter as tk from tkinter import ttk, messagebox, simpledialog, filedialog, scrolledtext import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import platform import sys import datetime import math class FAT32Parser: def __init__(self, device_path, readonly=True): self.device_path = device_path self.readonly = readonly self.sector_size = 512 self.cluster_size = 0 self.fat_start = 0 self.data_start = 0 self.root_cluster = 0 self.fat = [] self.free_clusters = [] self.total_clusters = 0 try: # 打开设备 mode = 'rb' if readonly else 'r+b' self.fd = open(device_path, mode) except Exception as e: raise ValueError(f"无法打开设备: {e}") try: # 读取引导扇区 self.fd.seek(0) boot_sector = self.fd.read(512) # 检查FAT32签名 if len(boot_sector) < 512 or boot_sector[510] != 0x55 or boot_sector[511] != 0xAA: raise ValueError("无效的引导扇区签名 - 可能不是FAT32格式") # 解析关键参数 self.sectors_per_cluster = boot_sector[13] if self.sectors_per_cluster not in [1, 2, 4, 8, 16, 32, 64, 128]: raise ValueError("无效的每簇扇区数") self.reserved_sectors = struct.unpack('<H', boot_sector[14:16])[0] self.num_fats = boot_sector[16] self.sectors_per_fat = struct.unpack('<I', boot_sector[36:40])[0] self.root_cluster = struct.unpack('<I', boot_sector[44:48])[0] self.total_sectors = struct.unpack('<I', boot_sector[32:36])[0] or struct.unpack('<I', boot_sector[40:44])[0] # 计算关键位置 self.cluster_size = self.sectors_per_cluster * self.sector_size self.fat_start = self.reserved_sectors * self.sector_size self.data_start = self.fat_start + (self.num_fats * self.sectors_per_fat * self.sector_size) # 计算总簇数 self.total_clusters = (self.total_sectors - self.reserved_sectors - self.num_fats * self.sectors_per_fat) // self.sectors_per_cluster # 加载FAT表 self._load_fat_table() # 检查根簇号是否有效 if self.root_cluster < 2 or self.root_cluster >= len(self.fat): raise ValueError(f"无效的根簇号: {self.root_cluster}") # 扫描空闲簇 self._find_free_clusters() except Exception as e: self.fd.close() raise e def _load_fat_table(self): """加载FAT表到内存""" self.fd.seek(self.fat_start) fat_size = self.sectors_per_fat * self.sector_size fat_data = self.fd.read(fat_size) if len(fat_data) != fat_size: raise ValueError("读取FAT表失败") # 解析FAT32表项 (每4字节一个簇) self.fat = [] for i in range(0, len(fat_data), 4): # 只取低28位(FAT32实际用28位) entry = struct.unpack('<I', fat_data[i:i+4])[0] & 0x0FFFFFFF self.fat.append(entry) def _find_free_clusters(self): """查找所有空闲簇""" self.free_clusters = [] for cluster_idx in range(2, len(self.fat)): # 簇0和1保留 if self.fat[cluster_idx] == 0: self.free_clusters.append(cluster_idx) def get_cluster_chain(self, start_cluster): """获取文件的簇链""" if start_cluster < 2 or start_cluster >= len(self.fat): return [] # 无效簇号 chain = [] current = start_cluster visited = set() # 追踪簇链直到结束 while current < 0x0FFFFFF8: # 文件结束标记 if current in visited: break # 防止无限循环 if current >= len(self.fat): break # 越界保护 chain.append(current) visited.add(current) next_cluster = self.fat[current] if next_cluster == 0 or next_cluster >= 0x0FFFFFF8: break current = next_cluster return chain def read_directory(self, cluster): """读取目录内容""" entries = [] chain = self.get_cluster_chain(cluster) if not chain: return entries # 长文件名缓存 lfn_parts = [] for c in chain: # 计算簇对应的扇区 sector_offset = self.data_start + (c - 2) * self.cluster_size if sector_offset < 0 or sector_offset > self.get_disk_size(): break self.fd.seek(sector_offset) data = self.fd.read(self.cluster_size) if len(data) < self.cluster_size: break # 读取不完整 # 解析每个目录项(32字节) for i in range(0, len(data), 32): entry = data[i:i+32] if len(entry) < 32: continue if entry[0] == 0x00: # 空闲 lfn_parts = [] # 重置长文件名缓存 continue if entry[0] == 0xE5: # 删除 lfn_parts = [] # 重置长文件名缓存 continue attr = entry[11] if attr == 0x0F: # 长文件名条目 # 解析长文件名片段 seq = entry[0] name_part = entry[1:11] + entry[14:26] + entry[28:32] # 移除尾部的0x00 name_part = name_part.split(b'\x00')[0] try: name_part = name_part.decode('utf-16le', errors='ignore') except: name_part = '?' lfn_parts.append((seq, name_part)) continue # 短文件名条目 name = entry[0:8].decode('latin-1', errors='ignore').strip() ext = entry[8:11].decode('latin-1', errors='ignore').strip() fullname = name + ('.' + ext if ext else '') # 如果有长文件名,使用它 if lfn_parts: # 排序并组合长文件名片段 lfn_parts.sort(key=lambda x: x[0]) long_name = ''.join(part for _, part in reversed(lfn_parts)) fullname = long_name.strip() lfn_parts = [] # 解析属性 is_dir = bool(attr & 0x10) is_volume = bool(attr & 0x08) # 获取起始簇号 start_cluster_hi = struct.unpack('<H', entry[20:22])[0] start_cluster_lo = struct.unpack('<H', entry[26:28])[0] start_cluster = (start_cluster_hi << 16) | start_cluster_lo # 文件大小 size = struct.unpack('<I', entry[28:32])[0] # 解析时间日期 create_time = struct.unpack('<H', entry[14:16])[0] create_date = struct.unpack('<H', entry[16:18])[0] mod_time = struct.unpack('<H', entry[22:24])[0] mod_date = struct.unpack('<H', entry[24:26])[0] # 跳过卷标 if is_volume: continue # 跳过特殊目录项 if fullname in ['.', '..']: continue entries.append({ 'name': fullname, 'is_dir': is_dir, 'start_cluster': start_cluster, 'size': size, 'create_time': self._parse_dos_datetime(create_date, create_time), 'mod_time': self._parse_dos_datetime(mod_date, mod_time) }) return entries def _parse_dos_datetime(self, date, time): """解析DOS日期时间格式""" try: # 解析日期: 7位年(从1980), 4位月, 5位日 year = ((date & 0xFE00) >> 9) + 1980 month = (date & 0x01E0) >> 5 day = date & 0x001F # 解析时间: 5位时, 6位分, 5位秒(以2秒为单位) hour = (time & 0xF800) >> 11 minute = (time & 0x07E0) >> 5 second = (time & 0x001F) * 2 return f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}" except: return "未知时间" def read_file_content(self, start_cluster, size): """读取文件内容""" content = b'' chain = self.get_cluster_chain(start_cluster) if not chain: return content bytes_remaining = size for cluster in chain: if bytes_remaining <= 0: break # 计算簇位置 sector_offset = self.data_start + (cluster - 2) * self.cluster_size if sector_offset < 0 or sector_offset > self.get_disk_size(): break self.fd.seek(sector_offset) # 读取簇内容 bytes_to_read = min(bytes_remaining, self.cluster_size) chunk = self.fd.read(bytes_to_read) if not chunk: break content += chunk bytes_remaining -= len(chunk) return content def get_disk_size(self): """获取磁盘大小""" self.fd.seek(0, 2) # 移动到文件末尾 return self.fd.tell() def create_file(self, parent_cluster, filename, content): """在指定目录创建文件""" if self.readonly: raise PermissionError("只读模式不允许写操作") # 1. 分配簇链 clusters_needed = math.ceil(len(content) / self.cluster_size) if clusters_needed > len(self.free_clusters): raise IOError("磁盘空间不足") allocated_clusters = self.free_clusters[:clusters_needed] self.free_clusters = self.free_clusters[clusters_needed:] # 2. 更新FAT表 for i in range(len(allocated_clusters)): cluster = allocated_clusters[i] if i == len(allocated_clusters) - 1: # 最后一个簇标记为EOF self.fat[cluster] = 0x0FFFFFFF else: # 指向下一个簇 self.fat[cluster] = allocated_clusters[i+1] # 3. 写入FAT表 self._write_fat_table() # 4. 写入文件内容 for i, cluster in enumerate(allocated_clusters): offset = self.data_start + (cluster - 2) * self.cluster_size self.fd.seek(offset) # 写入当前簇的数据 start = i * self.cluster_size end = min((i+1) * self.cluster_size, len(content)) self.fd.write(content[start:end]) # 5. 在父目录创建目录项 self._create_directory_entry(parent_cluster, { 'name': filename, 'is_dir': False, 'start_cluster': allocated_clusters[0], 'size': len(content) }) return allocated_clusters[0] def create_directory(self, parent_cluster, dirname): """在指定目录创建子目录""" if self.readonly: raise PermissionError("只读模式不允许写操作") # 1. 分配一个簇给新目录 if not self.free_clusters: raise IOError("磁盘空间不足") cluster = self.free_clusters[0] self.free_clusters = self.free_clusters[1:] # 2. 更新FAT表 (目录结束) self.fat[cluster] = 0x0FFFFFFF self._write_fat_table() # 3. 初始化目录内容 (创建 ... 条目) self._initialize_directory(cluster, parent_cluster) # 4. 在父目录创建目录项 self._create_directory_entry(parent_cluster, { 'name': dirname, 'is_dir': True, 'start_cluster': cluster, 'size': 0 }) return cluster def _initialize_directory(self, cluster, parent_cluster): """初始化新目录内容""" # 计算簇位置 offset = self.data_start + (cluster - 2) * self.cluster_size # 创建 . 条目 dot_entry = self._create_dir_entry(".", cluster, True) # 创建 .. 条目 dotdot_entry = self._create_dir_entry("..", parent_cluster, True) # 写入目录内容 self.fd.seek(offset) self.fd.write(dot_entry) self.fd.write(dotdot_entry) # 填充剩余空间为0 remaining = self.cluster_size - len(dot_entry) - len(dotdot_entry) self.fd.write(b'\x00' * remaining) def _create_dir_entry(self, name, cluster, is_dir): """创建目录项字节数据""" # 短文件名格式 (8.3) if len(name) > 8 and '.' not in name: base, ext = name[:8], "" else: parts = name.split('.') base = parts[0].upper()[:8] ext = parts[1].upper()[:3] if len(parts) > 1 else "" # 填充空格 base = base.ljust(8, ' ') ext = ext.ljust(3, ' ') # 创建32字节条目 entry = bytearray(32) # 文件名 (8字节) entry[0:8] = base.encode('latin-1') # 扩展名 (3字节) entry[8:11] = ext.encode('latin-1') # 属性 (目录) entry[11] = 0x10 if is_dir else 0x20 # 目录或存档 # 创建时间和日期 (当前时间) now = datetime.datetime.now() create_time = self._to_dos_time(now) create_date = self._to_dos_date(now) entry[14:16] = struct.pack('<H', create_time) entry[16:18] = struct.pack('<H', create_date) # 修改时间和日期 mod_time = create_time mod_date = create_date entry[22:24] = struct.pack('<H', mod_time) entry[24:26] = struct.pack('<H', mod_date) # 起始簇号 entry[20:22] = struct.pack('<H', (cluster >> 16) & 0xFFFF) # 高16位 entry[26:28] = struct.pack('<H', cluster & 0xFFFF) # 低16位 # 文件大小 (目录为0) entry[28:32] = struct.pack('<I', 0) return entry def _to_dos_time(self, dt): """将datetime转换为DOS时间格式""" return ((dt.hour << 11) | (dt.minute << 5) | (dt.second // 2)) def _to_dos_date(self, dt): """将datetime转换为DOS日期格式""" return (((dt.year - 1980) << 9) | (dt.month << 5) | dt.day) def _create_directory_entry(self, parent_cluster, entry_info): """在父目录中添加新的目录项""" # 获取父目录的所有簇 clusters = self.get_cluster_chain(parent_cluster) if not clusters: raise IOError("父目录无效") # 查找空闲目录槽 for cluster in clusters: offset = self.data_start + (cluster - 2) * self.cluster_size self.fd.seek(offset) data = self.fd.read(self.cluster_size) for i in range(0, len(data), 32): pos = offset + i entry = data[i:i+32] # 找到空闲或已删除的条目 if len(entry) < 32 or entry[0] in [0x00, 0xE5]: # 创建新条目 new_entry = self._create_dir_entry( entry_info['name'], entry_info['start_cluster'], entry_info['is_dir'] ) # 设置文件大小 if not entry_info['is_dir']: new_entry[28:32] = struct.pack('<I', entry_info['size']) # 写入新条目 self.fd.seek(pos) self.fd.write(new_entry) return # 如果没有找到空闲槽,分配新簇 if not self.free_clusters: raise IOError("磁盘空间不足") new_cluster = self.free_clusters[0] self.free_clusters = self.free_clusters[1:] # 更新FAT表 self.fat[clusters[-1]] = new_cluster # 当前最后一个簇指向新簇 self.fat[new_cluster] = 0x0FFFFFFF # 新簇标记为EOF self._write_fat_table() # 初始化新簇 self.fd.seek(self.data_start + (new_cluster - 2) * self.cluster_size) self.fd.write(b'\x00' * self.cluster_size) # 写入新条目到新簇的第一个位置 new_entry = self._create_dir_entry( entry_info['name'], entry_info['start_cluster'], entry_info['is_dir'] ) if not entry_info['is_dir']: new_entry[28:32] = struct.pack('<I', entry_info['size']) self.fd.seek(self.data_start + (new_cluster - 2) * self.cluster_size) self.fd.write(new_entry) def _write_fat_table(self): """将FAT表写回磁盘""" # 更新所有FAT副本 for fat_copy in range(self.num_fats): offset = self.fat_start + fat_copy * self.sectors_per_fat * self.sector_size self.fd.seek(offset) # 构建FAT表数据 fat_data = bytearray() for entry in self.fat: fat_data += struct.pack('<I', entry) # 写入FAT表 self.fd.write(fat_data) def close(self): """安全关闭文件句柄""" if hasattr(self, 'fd') and self.fd: self.fd.close() class FAT32Explorer: def __init__(self, root, device_path, readonly=True): self.root = root self.root.title(f"FAT32 文件系统工具 - {device_path}") self.root.geometry("1200x800") self.root.protocol("WM_DELETE_WINDOW", self.on_close) self.device_path = device_path self.readonly = readonly self.current_cluster = None self.current_path = "/" self.selected_file = None self.file_content_cache = None # 创建GUI布局 self._create_widgets() # 在后台加载文件系统 self.loading = True self.status.set("正在加载文件系统...") self.root.after(100, self._load_filesystem) def _create_widgets(self): # 创建主框架 main_frame = tk.Frame(self.root) main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 顶部工具栏 toolbar = tk.Frame(main_frame) toolbar.pack(fill=tk.X, pady=(0, 10)) mode_text = "只读模式" if self.readonly else "读写模式" mode_color = "green" if self.readonly else "red" tk.Label(toolbar, text=f"模式: {mode_text}", fg=mode_color, font=("Arial", 10, "bold")).pack(side=tk.LEFT, padx=10) # 路径导航 self.path_var = tk.StringVar(value="路径: /") tk.Label(toolbar, textvariable=self.path_var, font=("Arial", 10)).pack(side=tk.LEFT, padx=10) # 操作按钮 btn_frame = tk.Frame(toolbar) btn_frame.pack(side=tk.RIGHT) tk.Button(btn_frame, text="刷新", command=self.refresh).pack(side=tk.LEFT, padx=2) if not self.readonly: tk.Button(btn_frame, text="新建文件", command=self.create_file_dialog).pack(side=tk.LEFT, padx=2) tk.Button(btn_frame, text="新建目录", command=self.create_directory_dialog).pack(side=tk.LEFT, padx=2) # 主分割窗口 self.paned_window = tk.PanedWindow(main_frame, orient=tk.HORIZONTAL) self.paned_window.pack(fill=tk.BOTH, expand=True) # 左侧面板 (目录树) self.left_frame = tk.LabelFrame(self.paned_window, text="目录结构") self.paned_window.add(self.left_frame, width=300) # 目录树 self.tree = ttk.Treeview(self.left_frame, show='tree') self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) scrollbar = ttk.Scrollbar(self.left_frame, orient=tk.VERTICAL, command=self.tree.yview) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.tree.configure(yscrollcommand=scrollbar.set) self.tree.bind('<<TreeviewSelect>>', self.on_tree_select) # 右侧面板 self.right_frame = tk.PanedWindow(self.paned_window, orient=tk.VERTICAL) self.paned_window.add(self.right_frame) # 上部: 文件列表 file_frame = tk.LabelFrame(self.right_frame, text="当前目录内容") file_frame.pack(fill=tk.BOTH, expand=True) # 文件列表表头 columns = ("name", "size", "type", "cluster", "modified") self.file_tree = ttk.Treeview(file_frame, columns=columns, show="headings") # 设置列 self.file_tree.heading("name", text="名称") self.file_tree.heading("size", text="大小") self.file_tree.heading("type", text="类型") self.file_tree.heading("cluster", text="起始簇") self.file_tree.heading("modified", text="修改时间") self.file_tree.column("name", width=200) self.file_tree.column("size", width=80, anchor='e') self.file_tree.column("type", width=80) self.file_tree.column("cluster", width=80, anchor='e') self.file_tree.column("modified", width=150) self.file_tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) self.file_tree.bind('<<TreeviewSelect>>', self.on_file_select) # 文件列表滚动条 file_scrollbar = ttk.Scrollbar(file_frame, orient=tk.VERTICAL, command=self.file_tree.yview) file_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.file_tree.configure(yscrollcommand=file_scrollbar.set) # 下部: 簇状态可视化 self.cluster_frame = tk.LabelFrame(self.right_frame, text="簇分配图") self.cluster_frame.pack(fill=tk.BOTH, expand=True) self.fig, self.ax = plt.subplots(figsize=(8, 4)) self.canvas = FigureCanvasTkAgg(self.fig, master=self.cluster_frame) self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 底部: 状态栏 self.status = tk.StringVar() self.status.set("就绪" + (" - 只读模式" if self.readonly else " - 读写模式")) status_bar = tk.Label(self.root, textvariable=self.status, bd=1, relief=tk.SUNKEN, anchor=tk.W) status_bar.pack(side=tk.BOTTOM, fill=tk.X) # 添加文件内容查看器 (弹出窗口) self.content_window = None def _load_filesystem(self): """安全加载文件系统""" try: self.parser = FAT32Parser(self.device_path, self.readonly) self.root_cluster = self.parser.root_cluster # 加载根目录 self._show_root_directory() self.status.set(f"就绪 | 总簇数: {len(self.parser.fat)} | 空闲簇: {len(self.parser.free_clusters)}") self.loading = False except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("初始化错误", f"加载文件系统失败: {str(e)}") self.root.after(100, self.root.destroy) def _show_root_directory(self): """显示根目录""" self.tree.delete(*self.tree.get_children()) self.file_tree.delete(*self.file_tree.get_children()) self.current_path = "/" self.path_var.set(f"路径: {self.current_path}") # 添加根节点 root_id = self.tree.insert('', 'end', text="根目录", values=[self.root_cluster], open=True) self.current_cluster = self.root_cluster # 加载根目录内容 self._load_directory(root_id, self.root_cluster) def _load_directory(self, parent_id, cluster): """加载目录内容到树视图和列表""" try: entries = self.parser.read_directory(cluster) self.current_entries = entries # 清空文件列表 self.file_tree.delete(*self.file_tree.get_children()) # 添加到文件列表 for entry in entries: item_type = "目录" if entry['is_dir'] else "文件" size = f"{entry['size']:,}" if not entry['is_dir'] else "" self.file_tree.insert('', 'end', values=( entry['name'], size, item_type, entry['start_cluster'], entry['mod_time'] )) # 添加到树视图 for entry in entries: if entry['is_dir']: node_id = self.tree.insert(parent_id, 'end', text=entry['name'], values=[entry['start_cluster']]) # 添加一个虚拟节点以便展开 self.tree.insert(node_id, 'end', text="加载中...") # 更新簇图 self._update_cluster_map(cluster) self.status.set(f"显示目录: 簇 {cluster} | 条目: {len(entries)}") except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("目录错误", f"读取目录失败: {str(e)}") def _update_cluster_map(self, cluster=None): """更新簇状态可视化""" if not hasattr(self, 'parser'): return self.ax.clear() # 获取簇链(如果是目录) if cluster: chain = self.parser.get_cluster_chain(cluster) else: chain = [] # 简化的簇状态展示(只显示前500个簇) max_clusters = min(500, len(self.parser.fat)) cluster_status = [0] * max_clusters # 标记特殊簇 for i in range(max_clusters): if i == 0: cluster_status[i] = 4 # 特殊簇 elif i == 1: cluster_status[i] = 4 # 特殊簇 elif self.parser.fat[i] == 0: cluster_status[i] = 0 # 空闲 elif self.parser.fat[i] >= 0x0FFFFFF8: cluster_status[i] = 1 # 文件结束 elif self.parser.fat[i] == 0x0FFFFFF7: cluster_status[i] = 3 # 坏簇 else: cluster_status[i] = 2 # 使用中 # 高亮显示当前目录的簇链 for c in chain: if c < max_clusters: cluster_status[c] = 5 # 当前选择 # 使用不同颜色 cmap = plt.cm.colors.ListedColormap([ 'green', # 0: 空闲 'red', # 1: 文件结束 'blue', # 2: 使用中 'black', # 3: 坏簇 'gray', # 4: 特殊簇 'yellow' # 5: 当前选择 ]) # 绘制热力图 img = self.ax.imshow([cluster_status], cmap=cmap, aspect='auto', extent=[0, max_clusters, 0, 1]) # 添加颜色条 cbar = self.fig.colorbar(img, ax=self.ax, ticks=[0.4, 1.2, 2.0, 2.8, 3.6, 4.4]) cbar.ax.set_yticklabels(['空闲', '结束簇', '使用中', '坏簇', '特殊簇', '当前选择']) self.ax.set_title(f'簇分配图 (前{max_clusters}个簇)') self.ax.set_xlabel('簇号') self.ax.set_yticks([]) self.canvas.draw() def on_tree_select(self, event): """处理树节点选择事件""" if self.loading: return selected = self.tree.selection() if not selected: return item = self.tree.item(selected[0]) if 'values' in item and item['values']: cluster = item['values'][0] self.current_cluster = cluster # 构建当前路径 path = [] current_item = selected[0] while current_item: item_text = self.tree.item(current_item)['text'] if item_text != "根目录": path.insert(0, item_text) current_item = self.tree.parent(current_item) self.current_path = "/" + "/".join(path) self.path_var.set(f"路径: {self.current_path}") # 如果节点有子节点但只有一个"加载中"节点,则加载实际内容 children = self.tree.get_children(selected[0]) if children and self.tree.item(children[0])['text'] == "加载中...": self.tree.delete(children[0]) self._load_directory(selected[0], cluster) else: self._load_directory(selected[0], cluster) def on_file_select(self, event): """处理文件列表选择事件""" if self.loading: return selected = self.file_tree.selection() if not selected: return item = self.file_tree.item(selected[0]) values = item['values'] if values: # 查找对应的条目 for entry in self.current_entries: if entry['name'] == values[0]: self.selected_file = entry break if self.selected_file: # 显示文件信息 if not self.selected_file['is_dir']: # 打开文件内容查看器 self.show_file_content() def show_file_content(self): """显示文件内容""" if not self.selected_file or self.selected_file['is_dir']: return # 创建弹出窗口 if self.content_window and self.content_window.winfo_exists(): self.content_window.destroy() self.content_window = tk.Toplevel(self.root) self.content_window.title(f"文件内容: {self.selected_file['name']}") self.content_window.geometry("800x600") # 添加文本编辑器 text_frame = tk.Frame(self.content_window) text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 添加文本区域 self.content_text = scrolledtext.ScrolledText(text_frame, wrap=tk.WORD) self.content_text.pack(fill=tk.BOTH, expand=True) # 添加按钮 btn_frame = tk.Frame(self.content_window) btn_frame.pack(fill=tk.X, padx=10, pady=(0, 10)) tk.Button(btn_frame, text="加载内容", command=self.load_file_content).pack(side=tk.LEFT, padx=5) if not self.readonly: tk.Button(btn_frame, text="保存修改", command=self.save_file_content).pack(side=tk.LEFT, padx=5) tk.Button(btn_frame, text="关闭", command=self.content_window.destroy).pack(side=tk.RIGHT, padx=5) def load_file_content(self): """加载文件内容到编辑器""" if not self.selected_file: return try: content = self.parser.read_file_content( self.selected_file['start_cluster'], self.selected_file['size'] ) # 尝试解码为文本 try: decoded = content.decode('utf-8', errors='replace') self.content_text.delete(1.0, tk.END) self.content_text.insert(tk.END, decoded) self.file_content_cache = content self.status.set(f"已加载文件: {self.selected_file['name']}") except: # 如果是二进制文件,显示十六进制预览 hex_preview = ' '.join(f'{b:02x}' for b in content[:128]) if len(content) > 128: hex_preview += " ..." self.content_text.delete(1.0, tk.END) self.content_text.insert(tk.END, f"二进制文件 (十六进制预览):\n{hex_preview}") self.file_content_cache = content self.status.set(f"已加载二进制文件: {self.selected_file['name']}") except Exception as e: self.status.set(f"错误: {str(e)}") messagebox.showerror("读取错误", f"读取文件内容失败: {str(e)}") def save_file_content(self): """保存修改后的文件内容""" if self.readonly or not self.selected_file or not self.file_content_cache: return # 获取新内容 new_content = self.content_text.get(1.0, tk.END).encode('utf-8') # 检查内容是否变化 if new_content == self.file_content_cache: messagebox.showinfo("保存", "内容未更改") return # 确认保存 confirm = messagebox.askyesno("确认保存", f"确定要保存对文件 '{self.selected_file['name']}' 的修改吗?\n" "此操作将直接写入U盘!") if not confirm: return try: # 创建新文件 (如果大小变化) if len(new_content) != len(self.file_content_cache): # 创建新文件 new_cluster = self.parser.create_file( self.current_cluster, self.selected_file['name'], new_content ) # 删除旧文件 (标记为删除) # 在实际应用中应该实现文件删除功能 messagebox.showinfo("保存成功", "文件大小已改变,已创建新文件副本") else: # 直接覆盖内容 chain = self.parser.get_cluster_chain(self.selected_file['start_cluster']) bytes_remaining = len(new_content) for i, cluster in enumerate(chain): if bytes_remaining <= 0: break offset = self.parser.data_start + (cluster - 2) * self.parser.cluster_size self.parser.fd.seek(offset) # 写入当前簇的数据 start = i * self.parser.cluster_size end = min((i+1) * self.parser.cluster_size, len(new_content)) self.parser.fd.write(new_content[start:end]) bytes_remaining -= (end - start) self.status.set(f"文件已保存: {self.selected_file['name']}") messagebox.showinfo("保存成功", "文件内容已更新") # 刷新目录 self.refresh() except Exception as e: self.status.set(f"保存错误: {str(e)}") messagebox.showerror("保存失败", f"保存文件失败: {str(e)}") def create_file_dialog(self): """创建新文件对话框""" if self.readonly: messagebox.showwarning("只读模式", "只读模式下无法创建文件") return filename = simpledialog.askstring("新建文件", "请输入文件名:") if not filename: return # 创建内容输入窗口 content_window = tk.Toplevel(self.root) content_window.title(f"创建文件: {filename}") content_window.geometry("600x400") # 添加文本编辑器 text_frame = tk.Frame(content_window) text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) content_text = scrolledtext.ScrolledText(text_frame, wrap=tk.WORD) content_text.pack(fill=tk.BOTH, expand=True) content_text.focus_set() # 添加按钮 btn_frame = tk.Frame(content_window) btn_frame.pack(fill=tk.X, padx=10, pady=(0, 10)) def create_file(): content = content_text.get(1.0, tk.END).encode('utf-8') content_window.destroy() try: self.parser.create_file( self.current_cluster, filename, content ) self.status.set(f"文件已创建: {filename}") self.refresh() messagebox.showinfo("成功", f"文件 '{filename}' 已创建") except Exception as e: self.status.set(f"创建错误: {str(e)}") messagebox.showerror("创建失败", f"创建文件失败: {str(e)}") tk.Button(btn_frame, text="创建", command=create_file).pack(side=tk.LEFT, padx=5) tk.Button(btn_frame, text="取消", command=content_window.destroy).pack(side=tk.RIGHT, padx=5) def create_directory_dialog(self): """创建新目录对话框""" if self.readonly: messagebox.showwarning("只读模式", "只读模式下无法创建目录") return dirname = simpledialog.askstring("新建目录", "请输入目录名:") if not dirname: return try: self.parser.create_directory(self.current_cluster, dirname) self.status.set(f"目录已创建: {dirname}") self.refresh() messagebox.showinfo("成功", f"目录 '{dirname}' 已创建") except Exception as e: self.status.set(f"创建错误: {str(e)}") messagebox.showerror("创建失败", f"创建目录失败: {str(e)}") def refresh(self): """刷新当前目录""" if self.loading or not self.current_cluster: return selected = self.tree.selection() if selected: self._load_directory(selected[0], self.current_cluster) def on_close(self): """安全关闭窗口""" if hasattr(self, 'parser'): self.parser.close() self.root.destroy() def get_device_path(): """安全获取设备路径""" root = tk.Tk() root.withdraw() # 显示安全警告 messagebox.showwarning("重要提示", "此工具将直接访问您的U盘设备\n\n" "请确认:\n" "1. 您使用的是测试U盘,而不是系统盘\n" "2. 您已备份重要数据\n" "3. 您了解直接操作磁盘的风险") # 获取操作模式 mode = messagebox.askyesno("选择模式", "请选择操作模式:\n\n是: 读写模式 (允许修改)\n否: 只读模式 (安全分析)") readonly = not mode # 获取设备路径 if platform.system() == 'Windows': # Windows设备路径输入 device_path = simpledialog.askstring("输入U盘路径", "请输入U盘盘符 (例如: F:):\n\n" "Windows路径格式: \\\\.\\[盘符]", initialvalue="\\\\.\\F:") if device_path: # 标准化路径格式 if not device_path.startswith('\\\\'): device_path = '\\\\.\\' + device_path.replace(':', '') return device_path, readonly else: # Linux/Mac设备路径选择 messagebox.showinfo("选择U盘", "请选择您的U盘设备(例如:/dev/sdb1)") device_path = filedialog.askopenfilename( title="选择U盘设备", filetypes=[("磁盘设备", "/dev/sd*"), ("所有文件", "*")] ) return device_path, readonly return None, True if __name__ == '__main__': # 安全获取设备路径和模式 device_path, readonly = get_device_path() if not device_path: sys.exit(0) # 最终安全确认 mode_text = "读写" if not readonly else "只读" confirm = messagebox.askyesno("最终确认", f"即将以{mode_text}模式访问设备:\n{device_path}\n\n" "请确认:\n" "1. 这是正确的U盘设备\n" "2. 您已备份重要数据\n\n" "是否继续?") if not confirm: sys.exit(0) # 创建主窗口 root = tk.Tk() try: app = FAT32Explorer(root, device_path, readonly) root.mainloop() except Exception as e: messagebox.showerror("应用程序错误", f"发生未处理的错误: {str(e)}") sys.exit(1)修改代码使其可以访问目录成功
06-23
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license """ Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc. Usage - sources: $ python detect.py --weights yolov5s.pt --source 0 # webcam img.jpg # image vid.mp4 # video screen # screenshot path/ # directory list.txt # list of images list.streams # list of streams 'path/*.jpg' # glob 'https://youtu.be/LNwODJXcvt4' # YouTube 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream Usage - formats: $ python detect.py --weights yolov5s.pt # PyTorch yolov5s.torchscript # TorchScript yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s_openvino_model # OpenVINO yolov5s.engine # TensorRT yolov5s.mlpackage # CoreML (macOS-only) yolov5s_saved_model # TensorFlow SavedModel yolov5s.pb # TensorFlow GraphDef yolov5s.tflite # TensorFlow Lite yolov5s_edgetpu.tflite # TensorFlow Edge TPU yolov5s_paddle_model # PaddlePaddle """ import argparse import csv import os import platform import sys from pathlib import Path import torch FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative from ultralytics.utils.plotting import Annotator, colors, save_one_box from models.common import DetectMultiBackend from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams from utils.general import ( LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh, ) from utils.torch_utils import select_device, smart_inference_mode # 新增:计算IOU函数 def calculate_iou(box1, box2): """计算两个边界框的IOU""" x1, y1, x2, y2 = box1 x1g, y1g, x2g, y2g = box2 # 计算交集区域 xA = max(x1, x1g) yA = max(y1, y1g) xB = min(x2, x2g) yB = min(y2, y2g) # 计算交集面积 inter_area = max(0, xB - xA + 1) * max(0, yB - yA + 1) # 计算并集面积 box1_area = (x2 - x1 + 1) * (y2 - y1 + 1) box2_area = (x2g - x1g + 1) * (y2g - y1g + 1) union_area = float(box1_area + box2_area - inter_area) # 计算IOU iou = inter_area / union_area return iou # 新增:计算准确率函数 def calculate_accuracy(gt_labels, pred_detections, iou_threshold=0.5): """计算目标检测的准确率""" correct_predictions = 0 total_gt_objects = 0 total_pred_objects = 0 for img_name in gt_labels: if img_name not in pred_detections: continue gt_boxes = gt_labels[img_name] pred_boxes = pred_detections[img_name] total_gt_objects += len(gt_boxes) total_pred_objects += len(pred_boxes) # 标记已匹配的真实标签 gt_matched = [False] * len(gt_boxes) for pred_box in pred_boxes: pred_class, pred_bbox, pred_conf = pred_box best_iou = 0 best_gt_idx = -1 # 寻找最佳匹配的真实标签 for i, gt_box in enumerate(gt_boxes): gt_class, gt_bbox = gt_box if gt_matched[i]: continue iou = calculate_iou(pred_bbox, gt_bbox) if iou > best_iou and pred_class == gt_class: best_iou = iou best_gt_idx = i # 如果IOU超过阈值且类别正确,则计为正确预测 if best_gt_idx != -1 and best_iou >= iou_threshold: correct_predictions += 1 gt_matched[best_gt_idx] = True # 避免除零错误 if total_gt_objects == 0: return 0.0 # 计算准确率 return correct_predictions / total_gt_objects @smart_inference_mode() def run( weights=ROOT / "yolov5s.pt", # model path or triton URL source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam) data=ROOT / "data/coco128.yaml", # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_format=0, # save boxes coordinates in YOLO format or Pascal-VOC format (0 for YOLO and 1 for Pascal-VOC) save_csv=False, # save results in CSV format save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / "runs/detect", # save results to project/name name="exp", # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride gt_dir="", # 新增:真实标签目录 eval_interval=10, # 新增:评估间隔帧数 ): """ Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc. Args: weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'. source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam index. Default is 'data/images'. data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'. imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640). conf_thres (float): Confidence threshold for detections. Default is 0.25. iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45. max_det (int): Maximum number of detections per image. Default is 1000. device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the best available device. view_img (bool): If True, display inference results using OpenCV. Default is False. save_txt (bool): If True, save results in a text file. Default is False. save_format (int): Whether to save boxes coordinates in YOLO format or Pascal-VOC format. Default is 0. save_csv (bool): If True, save results in a CSV file. Default is False. save_conf (bool): If True, include confidence scores in the saved results. Default is False. save_crop (bool): If True, save cropped prediction boxes. Default is False. nosave (bool): If True, do not save inference images or videos. Default is False. classes (list[int]): List of classes to filter detections by. Default is None. agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False. augment (bool): If True, use augmented inference. Default is False. visualize (bool): If True, visualize feature maps. Default is False. update (bool): If True, update all models' weights. Default is False. project (str | Path): Directory to save results. Default is 'runs/detect'. name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'. exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is False. line_thickness (int): Thickness of bounding box lines in pixels. Default is 3. hide_labels (bool): If True, do not display labels on bounding boxes. Default is False. hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False. half (bool): If True, use FP16 half-precision inference. Default is False. dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False. vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1. gt_dir (str): 新增:真实标签目录路径 eval_interval (int): 新增:每隔多少帧计算一次准确率 Returns: None """ source = str(source) save_img = not nosave and not source.endswith(".txt") # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://")) webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file) screenshot = source.lower().startswith("screen") if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True) dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) bs = len(dataset) elif screenshot: dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt) else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) vid_path, vid_writer = [None] * bs, [None] * bs # 新增:加载真实标签数据 gt_labels = {} if gt_dir: gt_dir = Path(gt_dir) for txt_file in gt_dir.glob("*.txt"): img_name = txt_file.stem gt_labels[img_name] = [] with open(txt_file, "r") as f: for line in f: parts = line.strip().split() if len(parts) >= 5: cls = int(parts[0]) # 将YOLO格式转换为xyxy格式 x, y, w, h = map(float, parts[1:5]) # 假设真实标签对应的图像尺寸与输入图像一致 x1 = (x - w/2) * imgsz[1] y1 = (y - h/2) * imgsz[0] x2 = (x + w/2) * imgsz[1] y2 = (y + h/2) * imgsz[0] gt_labels[img_name].append((cls, (x1, y1, x2, y2))) # 新增:收集预测结果 pred_detections = {} frame_count = 0 accuracy = 0.0 # 初始化准确率 # Run inference model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device)) for path, im, im0s, vid_cap, s in dataset: with dt[0]: im = torch.from_numpy(im).to(model.device) im = im.half() if model.fp16 else im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim if model.xml and im.shape[0] > 1: ims = torch.chunk(im, im.shape[0], 0) # Inference with dt[1]: visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False if model.xml and im.shape[0] > 1: pred = None for image in ims: if pred is None: pred = model(image, augment=augment, visualize=visualize).unsqueeze(0) else: pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0) pred = [pred, None] else: pred = model(im, augment=augment, visualize=visualize) # NMS with dt[2]: pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) # Second-stage classifier (optional) # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) # Define the path for the CSV file csv_path = save_dir / "predictions.csv" # Create or append to the CSV file def write_to_csv(image_name, prediction, confidence): """Writes prediction data for an image to a CSV file, appending if the file exists.""" data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence} file_exists = os.path.isfile(csv_path) with open(csv_path, mode="a", newline="") as f: writer = csv.DictWriter(f, fieldnames=data.keys()) if not file_exists: writer.writeheader() writer.writerow(data) # Process predictions for i, det in enumerate(pred): # per image seen += 1 if webcam: # batch_size >= 1 p, im0, frame = path[i], im0s[i].copy(), dataset.count s += f"{i}: " else: p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0) p = Path(p) # to Path save_path = str(save_dir / p.name) # im.jpg txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt s += "{:g}x{:g} ".format(*im.shape[2:]) # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh imc = im0.copy() if save_crop else im0 # for save_crop annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string # Write results for *xyxy, conf, cls in reversed(det): c = int(cls) # integer class label = names[c] if hide_conf else f"{names[c]}" confidence = float(conf) confidence_str = f"{confidence:.2f}" if save_csv: write_to_csv(p.name, label, confidence_str) if save_txt: # Write to file if save_format == 0: coords = ( (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() ) # normalized xywh else: coords = (torch.tensor(xyxy).view(1, 4) / gn).view(-1).tolist() # xyxy line = (cls, *coords, conf) if save_conf else (cls, *coords) # label format with open(f"{txt_path}.txt", "a") as f: f.write(("%g " * len(line)).rstrip() % line + "\n") if save_img or save_crop or view_img: # Add bbox to image c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}") annotator.box_label(xyxy, label, color=colors(c, True)) if save_crop: save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True) # 新增:收集预测结果 img_name = p.stem pred_detections[img_name] = [] if len(det): for *xyxy, conf, cls in det: c = int(cls) x1, y1, x2, y2 = map(int, xyxy) pred_detections[img_name].append((c, (x1, y1, x2, y2), float(conf))) # 新增:定期计算准确率并显示 frame_count += 1 if gt_dir and frame_count % eval_interval == 0: accuracy = calculate_accuracy(gt_labels, pred_detections) if save_img or view_img: accuracy_text = f"Accuracy: {accuracy:.2f}" annotator.text((10, 30), accuracy_text, txt_color=(255, 255, 255)) im0 = annotator.result() # Stream results im0 = annotator.result() if view_img: if platform.system() == "Linux" and p not in windows: windows.append(p) cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux) cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0]) cv2.imshow(str(p), im0) cv2.waitKey(1) # 1 millisecond # Save results (image with detections) if save_img: if dataset.mode == "image": cv2.imwrite(save_path, im0) else: # 'video' or 'stream' if vid_path[i] != save_path: # new video vid_path[i] = save_path if isinstance(vid_writer[i], cv2.VideoWriter): vid_writer[i].release() # release previous video writer if vid_cap: # video fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) else: # stream fps, w, h = 30, im0.shape[1], im0.shape[0] save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) vid_writer[i].write(im0) # Print time (inference-only) LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1e3:.1f}ms") # 新增:在终端输出最终准确率 if gt_dir: accuracy = calculate_accuracy(gt_labels, pred_detections) LOGGER.info(f"Overall Accuracy: {accuracy:.4f}") # Print results t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t) if save_txt or save_img: s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else "" LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") if update: strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning) def parse_opt(): """ Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations. Args: --weights (str | list[str], optional): Model path or triton URL. Defaults to ROOT / 'yolov5s.pt'. --source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'. --data (str, optional): Dataset YAML path. Provides dataset configuration information. --imgsz (list[int], optional): Inference size (height, width). Defaults to [640]. --conf-thres (float, optional): Confidence threshold. Defaults to 0.25. --iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45. --max-det (int, optional): Maximum number of detections per image. Defaults to 1000. --device (str, optional): CUDA device, i.e. 0 or 0,1,2,3 or cpu. Defaults to "". --view-img (bool, optional): Flag to display results. Default is False. --save-txt (bool, optional): Flag to save results to *.txt files. Default is False. --save-format (int, optional): Whether to save boxes coordinates in YOLO format or Pascal-VOC format. Default is 0. --save-csv (bool, optional): Flag to save results in CSV format. Default is False. --save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Default is False. --save-crop (bool, optional): Flag to save cropped prediction boxes. Default is False. --nosave (bool, optional): Flag to prevent saving images/videos. Default is False. --classes (list[int], optional): List of classes to filter results by. Default is None. --agnostic-nms (bool, optional): Flag for class-agnostic NMS. Default is False. --augment (bool, optional): Flag for augmented inference. Default is False. --visualize (bool, optional): Flag for visualizing features. Default is False. --update (bool, optional): Flag to update all models in the model directory. Default is False. --project (str, optional): Directory to save results. Default is ROOT / 'runs/detect'. --name (str, optional): Sub-directory name for saving results within --project. Default is 'exp'. --exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Default is False. --line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Default is 3. --hide-labels (bool, optional): Flag to hide labels in the output. Default is False. --hide-conf (bool, optional): Flag to hide confidences in the output. Default is False. --half (bool, optional): Flag to use FP16 half-precision inference. Default is False. --dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Default is False. --vid-stride (int, optional): Video frame-rate stride. Default is 1. --gt-dir (str, optional): 新增:真实标签目录路径 --eval-interval (int, optional): 新增:每隔多少帧计算一次准确率 Returns: argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object. """ parser = argparse.ArgumentParser() parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL") parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)") parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path") parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w") parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold") parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold") parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image") parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu") parser.add_argument("--view-img", action="store_true", help="show results") parser.add_argument("--save-txt", action="store_true", help="save results to *.txt") parser.add_argument( "--save-format", type=int, default=0, help="whether to save boxes coordinates in YOLO format or Pascal-VOC format when save-txt is True, 0 for YOLO and 1 for Pascal-VOC", ) parser.add_argument("--save-csv", action="store_true", help="save results in CSV format") parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels") parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes") parser.add_argument("--nosave", action="store_true", help="do not save images/videos") parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3") parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS") parser.add_argument("--augment", action="store_true", help="augmented inference") parser.add_argument("--visualize", action="store_true", help="visualize features") parser.add_argument("--update", action="store_true", help="update all models") parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name") parser.add_argument("--name", default="exp", help="save results to project/name") parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment") parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)") parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels") parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences") parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference") parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference") parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride") # 新增参数 parser.add_argument("--gt-dir", type=str, default="", help="ground truth labels directory") parser.add_argument("--eval-interval", type=int, default=10, help="evaluate accuracy every N frames") opt = parser.parse_args() opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand print_args(vars(opt)) return opt def main(opt): """ Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running. Args: opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. Returns: None """ check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop")) run(**vars(opt)) if __name__ == "__main__": opt = parse_opt() main(opt)代码如上。yolov5在detect.py得到有类别和置信度标注的视频和图片,请问我如何操作,才能在有类别和置信度标注的视频和图片的基础上,在视频或图片中显示识别准确率Accuracy。请给出修改后的完整代码(尽量少修改,不要改变代码的其他地方),要求直接在vscode点击运行即可生成显示识别准确率Accuracy的视频或图片
07-07
import argparse import os import platform import sys from pathlib import Path import torch FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative from models.common import DetectMultiBackend from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh) from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device, smart_inference_mode @smart_inference_mode() def run( weights=ROOT / 'runs/train/exp2/weights/best.pt', # model path or triton URL source=ROOT / 'datasets/binren', # file/dir/URL/glob/screen/0(webcam) data=ROOT / 'data/coco128.yaml', # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) screenshot = source.lower().startswith('screen') if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True) dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) bs = len(dataset) elif screenshot: dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt) else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) vid_path, vid_writer = [None] * bs, [None] * bs # Run inference model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) for path, im, im0s, vid_cap, s in dataset: with dt[0]: im = torch.from_numpy(im).to(model.device) im = im.half() if model.fp16 else im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim # Inference with dt[1]: visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False pred = model(im, augment=augment, visualize=visualize) # NMS with dt[2]: pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) # Second-stage classifier (optional) # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) # Process predictions for i, det in enumerate(pred): # per image seen += 1 if webcam: # batch_size >= 1 p, im0, frame = path[i], im0s[i].copy(), dataset.count s += f'{i}: ' else: p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) p = Path(p) # to Path save_path = str(save_dir / p.name) # im.jpg txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt s += '%gx%g ' % im.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh imc = im0.copy() if save_crop else im0 # for save_crop annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string # Write results for *xyxy, conf, cls in reversed(det): if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(f'{txt_path}.txt', 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') if save_img or save_crop or view_img: # Add bbox to image c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') annotator.box_label(xyxy, label, color=colors(c, True)) if save_crop: save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) # Stream results im0 = annotator.result() if view_img: if platform.system() == 'Linux' and p not in windows: windows.append(p) cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux) cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0]) cv2.imshow(str(p), im0) cv2.waitKey(1) # 1 millisecond # Save results (image with detections) if save_img: if dataset.mode == 'image': cv2.imwrite(save_path, im0) else: # 'video' or 'stream' if vid_path[i] != save_path: # new video vid_path[i] = save_path if isinstance(vid_writer[i], cv2.VideoWriter): vid_writer[i].release() # release previous video writer if vid_cap: # video fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) else: # stream fps, w, h = 30, im0.shape[1], im0.shape[0] save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) vid_writer[i].write(im0) # Print time (inference-only) LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms") # Print results t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t) if save_txt or save_img: s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") if update: strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning) def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train/exp2/weights/best.pt', help='model path or triton URL') parser.add_argument('--source', type=str, default=ROOT / 'datasets/binren', help='file/dir/URL/glob/screen/0(webcam)') parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path') parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--view-img', action='store_true', help='show results') parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') parser.add_argument('--nosave', action='store_true', help='do not save images/videos') parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3') parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') parser.add_argument('--augment', action='store_true', help='augmented inference') parser.add_argument('--visualize', action='store_true', help='visualize features') parser.add_argument('--update', action='store_true', help='update all models') parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name') parser.add_argument('--name', default='exp', help='save results to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride') opt = parser.parse_args() opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand print_args(vars(opt)) return opt def main(opt): check_requirements(exclude=('tensorboard', 'thop')) run(**vars(opt)) if __name__ == "__main__": opt = parse_opt() main(opt)我想将终端里面的输出结果改成中文的
06-26
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值