{$I-}

Unit
  tMsgLib;

Interface

Uses
{$IFNDEF WIN32}
  DOS,
{$ELSE}
  OpCrt,
  SysUtils,
  Classes,
{$ENDIF}
  Objects,
  tGlob,
  tMisc;

Function SaveCollection (FileName: PathStr; Var C: PBigCollection;
         Tag, Version: String): Boolean;

Function ReadCollection (FileName: PathStr; Var C: PBigCollection;
         Tag, Version: String; NotSorted: Boolean): Boolean;

Implementation

Var
  F : File;
  S : String;

Function SaveCollection;
Var
  i : LongInt;

Begin
  Version := ExtractWord (2, Version, [' ']);
  If (Pos ('-', Copy (Version, RPos ('/', Version, Length (Version)), 255)) = 0) And
     (RPos ('/', Version, Length (Version)) <> 0)
  Then Version := Copy (Version, 1, RPos ('/', Version, Length (Version))-1);

  Assign (F, FileName); ReSet (F, 1);
  SaveCollection := False;

  Case IOResult Of
    0 : Begin
          Seek (F, FileSize (F));
        End;
    2 : Begin
          ReWrite (F, 1);
          BlockWrite (F, Version, Length (Version)+1);
        End;
  Else
    Exit;
  End;

  BlockWrite (F, Tag, Length (Tag)+1);

  For i := 0 To C^. Count-1 Do
  Begin
    If C^. At (i) <> Nil Then S := PString (C^. At (i))^ Else S := '';
    BlockWrite (F, S, Length (S)+1);
  End;

  S := #255;
  BlockWrite (F, S, 2);

  Close (F);

  If IOResult <> 0 Then;
  SaveCollection := True;

End;

Function ReadCollection;

  Function ReadString: String;
  Var
    S : String;
    B : Byte;

  Begin
    BlockRead (F, B, 1);
    S[0] := Char (B);
    BlockRead (F, S[1], B);
    ReadString := S;
  End;
(*
{$IFDEF MSDOS}
  Var
    S : String;
    B : Byte;

  Begin
    BlockRead (F, B, 1);
    S[0] := Char (B);
    BlockRead (F, S[1], B);
    ReadString := S;
  End;
{$ELSE}
  Var
    S : String;
    B : Byte;
    C : Array [1..255] Of Char;

  Begin
    BlockRead (F, B, 1);
    BlockRead (F, C, B);
    S := Replicate (' ', B);
    Move (C [1], S [1], B);
    ReadString := S;
  End;
{$ENDIF}
*)
Begin
  ReadCollection := False;
  Assign (F, FileName); ReSet (F, 1);

  If IOResult <> 0 Then Exit;

  { Читаем версию }
  Version := ExtractWord (2, Version, [' ']);
  If (Pos ('-', Copy (Version, RPos ('/', Version, Length (Version)), 255)) = 0) And
     (RPos ('/', Version, Length (Version)) <> 0)
  Then Version := Copy (Version, 1, RPos ('/', Version, Length (Version))-1);

  If ReadString <> Version Then
  Begin
    Close (F);
    Exit;
  End;

  { Ищем Tag }
  While Not EoF (F) Do
  Begin
    If ReadString = Tag Then
    Begin
      C^. FreeAll;
      C^. DeleteAll;

      While Not EoF (F) Do
      Begin
        S := ReadString;
        If S <> #255 Then
        Begin
          If NotSorted Then C^. Insert (NewStr (S)) Else C^. InsLine (S);
        End Else
          Break;
      End;

      ReadCollection := True;
      Close (F);
      Exit;
    End;

    While ReadString <> #255 Do;
  End;

  Close (F);
End;

End.