File: datlocalcorrect.pas

package info (click to toggle)
udm 1.0.0.352-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 28,076 kB
  • sloc: pascal: 72,496; ansic: 6,892; awk: 880; makefile: 768; sh: 493; perl: 34; python: 22; tcl: 18
file content (433 lines) | stat: -rw-r--r-- 12,321 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
unit datlocalcorrect;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
  StdCtrls, ExtCtrls, Buttons, ComCtrls, Spin
  , upascaltz //Required for timezone corrections
  ;

type

  { Tdatlocalcorrectform }

  Tdatlocalcorrectform = class(TForm)
    DirectorySelectButton: TButton;
    CorrectButton: TBitBtn;
    FileSelectButton: TButton;
    CustomGroupBox: TGroupBox;
    CustomOffsetEdit: TFloatSpinEdit;
    CustomOffsetLabel: TLabel;
    InputDirectoryDisplay: TEdit;
    InputFileDisplay: TEdit;
    Label11: TLabel;
    Label6: TLabel;
    OutputDir: TLabeledEdit;
    Memo1: TMemo;
    SelectDirectoryDialog1: TSelectDirectoryDialog;
    TZMethodRadioGroup: TRadioGroup;
    StandardGroupBox: TGroupBox;
    SettingsGroupBox: TGroupBox;
    InGroupBox: TGroupBox;
    OpenDialog1: TOpenDialog;
    OutGroupBox: TGroupBox;
    OutputFile: TLabeledEdit;
    StatusBar1: TStatusBar;
    TZLocationBox: TComboBox;
    TZRegionBox: TComboBox;
    procedure CorrectButtonClick(Sender: TObject);
    procedure DirectorySelectButtonClick(Sender: TObject);
    procedure FileSelectButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure TZMethodRadioGroupClick(Sender: TObject);
    procedure TZLocationBoxChange(Sender: TObject);
    procedure TZRegionBoxChange(Sender: TObject);
  private
    procedure ReadINI();
    procedure FillTimezones();
    procedure CorrectFile(InfileString, OutFileString: string);
  public

  end;

var
  datlocalcorrectform: Tdatlocalcorrectform;
  InFileName: string;
  OutFileName: string;
  InDirName: string;
  OutDirName: string;
  Timediff: int64;
  LocalRecINIsection: string;
  AZones: TStringList;
  ptz: TPascalTZ;
  subfix: ansistring; //Used for time zone conversions
  LocalRecTZRegion, LocalRecTZLocation: string; //Only used for local timeone correction

  { Indicates that programmatic changes are taking place to the Time Zone }
  TZChanging: boolean = False;

  TimezoneMethod: integer;
  FileMode: boolean = False; {False = single file. True = directory}
  HoursDiff: double = 0.0;

implementation

uses
  appsettings //Required to read application settings (like locations).
  , dateutils //Required to convert logged UTC string to TDateTime
  , strutils //Required for checking lines in conversion file.
  , LazFileUtils //required for ExtractFileNameOnly
  , dlheader //For Timezone conversions.
  ;

{ Tdattimecorrectform }

{ Populate form from INI file }
procedure Tdatlocalcorrectform.ReadINI();
var
  pieces: TStringList;

begin

  pieces := TStringList.Create;
  pieces.Delimiter := ',';
  pieces.StrictDelimiter := False; //Parse spaces also

  LocalRecINIsection := 'LocalReconstruct:';

  { Pull Timezone information from INI file if it exists.}
  LocalRecTZRegion := vConfigurations.ReadString(LocalRecINIsection, 'Local region');
  TZRegionBox.Text := LocalRecTZRegion;
  FillTimezones();

  { Read the previously recorded entries. }
  LocalRecTZLocation := vConfigurations.ReadString(LocalRecINIsection, 'Local time zone');
  TZLocationBox.Text := LocalRecTZLocation;

  if Assigned(pieces) then FreeAndNil(pieces);

end;

//Select file for correction
procedure Tdatlocalcorrectform.FileSelectButtonClick(Sender: TObject);
begin

  { Set mode and clear displays}
  FileMode := False; {Single file selection}
  InputFileDisplay.Text := '';
  InputDirectoryDisplay.Text := '';
  InputFileDisplay.Visible := True;
  InputDirectoryDisplay.Visible := False;
  OutputFile.Visible := True;
  OutputDir.Visible := False;

  { Clear status bar }
  StatusBar1.Panels.Items[0].Text := '';
  Application.ProcessMessages;

  OpenDialog1.Filter := 'data log files|*.dat|All files|*.*';
  OpenDialog1.InitialDir := appsettings.LogsDirectory;

  { Get Input filename from user }
  if (OpenDialog1.Execute) then
  begin
    InFileName := OpenDialog1.FileName;
    InputFileDisplay.Text := InFileName;

    { Create output file name }
    OutFileName := ExtractFilePath(InFileName) + LazFileUtils.ExtractFileNameOnly(InFileName) + '_LocalCorr' + ExtractFileExt(InFileName);
    OutputFile.Text := OutFileName;
  end;
end;

procedure Tdatlocalcorrectform.DirectorySelectButtonClick(Sender: TObject);
begin

  { Set mode and clear displays}
  FileMode := True;
  InputFileDisplay.Text := '';
  InputDirectoryDisplay.Text := '';
  InputFileDisplay.Visible := False;
  InputDirectoryDisplay.Visible := True;
  OutputFile.Visible := False;
  OutputDir.Visible := True;

  { Clear status bar }
  StatusBar1.Panels.Items[0].Text := '';
  Application.ProcessMessages;

  SelectDirectoryDialog1.InitialDir := appsettings.LogsDirectory;

  { Get Input directory from user }
  if (SelectDirectoryDialog1.Execute) then
  begin
    InDirName := SelectDirectoryDialog1.FileName;
    InputDirectoryDisplay.Text := InDirName + DirectorySeparator + '*.dat';

    { Show desired output directory }
    OutDirName := InDirName + DirectorySeparator + 'LocalCorr';
    OutputDir.Text := OutDirName + DirectorySeparator + '*_LocalCorr.dat';
  end;

end;

procedure Tdatlocalcorrectform.FormCreate(Sender: TObject);
begin
  { Clear status bar }
  StatusBar1.Panels.Items[0].Text := '';
  Application.ProcessMessages;

  { get previous timezone settings }
  { Initialize required variables. }
  AZones := TStringList.Create;
  ptz := TPascalTZ.Create();

  ReadINI();

  StandardGroupBox.Enabled := True;
  CustomGroupBox.Enabled := False;
  CustomOffsetEdit.Value := HoursDiff;

end;

procedure Tdatlocalcorrectform.FormDestroy(Sender: TObject);
begin
  if Assigned(AZones) then FreeAndNil(AZones);
  if Assigned(ptz) then FreeAndNil(ptz);
end;

procedure Tdatlocalcorrectform.TZMethodRadioGroupClick(Sender: TObject);
begin

  TimezoneMethod := TZMethodRadioGroup.ItemIndex;
  case TimezoneMethod of
    0: begin
      StandardGroupBox.Enabled := True;
      CustomGroupBox.Enabled := False;
    end;
    1: begin
      StandardGroupBox.Enabled := False;
      CustomGroupBox.Enabled := True;
    end;
  end;
end;

procedure Tdatlocalcorrectform.TZLocationBoxChange(Sender: TObject);
begin
  if not TZChanging then
  begin
    TZChanging := True;
    { Save the TZ selection. }
    LocalRecTZLocation := TZLocationBox.Text;
    Application.ProcessMessages;
    vConfigurations.WriteString(LocalRecINIsection, 'Local time zone',
      LocalRecTZLocation);
    TZChanging := False;
  end;
end;

procedure Tdatlocalcorrectform.TZRegionBoxChange(Sender: TObject);
begin
  if not TZChanging then
  begin
    TZChanging := True;

    { Get and save region }
    LocalRecTZRegion := TZRegionBox.Text;
    Application.ProcessMessages; //Wait for GUI to put screen text into variable.
    vConfigurations.WriteString(LocalRecINIsection, 'Local region', LocalRecTZRegion);
    //Save TZ Region

    { Fill up timezone location names }
    FillTimezones();

    { Clear out selected time zone location because time zone region was just changed. }
    LocalRecTZLocation := '';
    TZLocationBox.Text := LocalRecTZLocation;
    vConfigurations.WriteString(LocalRecINIsection, 'Local time zone',
      LocalRecTZLocation);

    TZChanging := False;
  end;

end;

{ Correct one file }
procedure Tdatlocalcorrectform.CorrectFile(InfileString, OutfileString: string);
var
  InFile, OutFile: TextFile;
  Str: string;
  pieces: TStringList;

  index: integer;

  UTCRecord: TDateTime;
  LocalRecord: TDateTime;
  ComposeString: string;

  WriteAllowable: boolean = True; //Allow output file to be written or not.

begin

  StatusBar1.Panels.Items[0].Text := 'Correcting input file: ' + InfileString;
  Application.ProcessMessages;

  pieces := TStringList.Create;

  AssignFile(InFile, InFileString);
  AssignFile(OutFile, OutfileString);


  { Start reading file. }
  if FileExists(OutfileString) then
  begin
    if (MessageDlg('Overwrite existing file?', 'Do you want to overwrite the existing file ' + OutfileString +
      ' ?', mtConfirmation, [mbOK, mbCancel], 0) = mrOk) then
      WriteAllowable := True
    else
      WriteAllowable := False;
  end;
  if WriteAllowable then
  begin
    {$I+}
    try
      Reset(InFile);

      Rewrite(OutFile); {Open file for writing}

      StatusBar1.Panels.Items[0].Text := 'Reading Input file';
      Application.ProcessMessages;

      repeat
        { Read one line at a time from the file. }
        Readln(InFile, Str);

        //StatusBar1.Panels.Items[0].Text := 'Processing : ' + Str;
        //Application.ProcessMessages;

        { Ignore most comment lines which have # as first character. }
        if (AnsiStartsStr('#', Str)) then
        begin
          { Touch up time zone location line }
          if AnsiStartsStr('# Local timezone:', Str) then
          begin
            case TimezoneMethod of
              0: WriteLn(OutFile, format('# Local timezone: %s', [LocalRecTZLocation]));
              1: WriteLn(OutFile, Str);
            end;
          end
          else
            { Write untouched header line }
            WriteLn(OutFile, Str);
        end
        else
        begin
          { Separate the fields of the record. }
          pieces.Delimiter := ';';
          pieces.DelimitedText := Str;

          { Parse the UTC timestamp}
          UTCRecord := ScanDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', pieces.Strings[0]);

          case TimezoneMethod of
            0: begin { Standard correction method uses selected region and timezone. }
              LocalRecord := ptz.GMTToLocalTime(UTCRecord, LocalRecTZLocation, subfix);
            end;
            1: begin { Custom correction method uses offset hours value. }
              LocalRecord := UTCRecord + (HoursDiff / 24.0);
            end;
          end;

          { Compose the string for timestamp replacement. }
          ComposeString := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz;', UTCRecord) + FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', LocalRecord);

          { Compose remainderof string }
          for index := 2 to pieces.Count - 1 do
          begin
            ComposeString := ComposeString + ';' + pieces.Strings[index];
          end;

          WriteLn(OutFile, ComposeString);

        end;
      until (EOF(InFile));
      { EOF(End Of File) The the program will keep reading new lines until there is none. }
      CloseFile(InFile);
      StatusBar1.Panels.Items[0].Text := 'Finished';
      Application.ProcessMessages;

    except
      on E: EInOutError do
      begin
        MessageDlg('Error', 'File handling error occurred. Details: ' + E.ClassName + '/' + E.Message, mtError, [mbOK], 0);
      end;
    end;
    Flush(OutFile);
    CloseFile(OutFile);

  end; { End of WriteAllowable check. }

end;

{ Correct file(s) }
procedure Tdatlocalcorrectform.CorrectButtonClick(Sender: TObject);
var
  sr: TSearchRec;
begin
  { Clear status bar. }
  StatusBar1.Panels.Items[0].Text := 'Processing file(s).';
  Application.ProcessMessages;

  HoursDiff:=CustomOffsetEdit.Value;

  if not FileMode then
  begin
    { Just correct one file. }
    CorrectFile(InFileName, OutFileName);

  end
  else
  begin {All files in a directory.}

    { Make directory to store files. }
    if (not (DirectoryExists(OutDirName))) then
      MkDir(OutDirName);

    { Work on all files in the directory. }
    if FindFirstUTF8(InDirName + DirectorySeparator + '*.dat', faAnyFile, sr) = 0 then
      repeat
        CorrectFile(InDirName + DirectorySeparator + sr.Name, OutDirName + DirectorySeparator +
          LazFileUtils.ExtractFileNameOnly(sr.Name) + '_LocalCorr.dat');
      until FindNextUTF8(sr) <> 0;
    FindCloseUTF8(sr);
  end;

end;

{ Fill timezone location dropdown entries. }
procedure Tdatlocalcorrectform.FillTimezones();
begin
  if (FileExists(appsettings.TZDirectory + LocalRecTZRegion) and (length(LocalRecTZRegion) > 0)) then
  begin
    ptz.Destroy;
    ptz := TPascalTZ.Create();
    try
      ptz.ParseDatabaseFromFile(appsettings.TZDirectory + LocalRecTZRegion);
    except
      ShowMessage(Format('Failed getting zones from %s', [LocalRecTZRegion]));
    end;
    ptz.GetTimeZoneNames(AZones, True);
    { Only geo name = true, does not show short names. }
    TZLocationBox.Items.Clear;
    TZLocationBox.Items.AddStrings(AZones);
  end;
end;

initialization
  {$I datlocalcorrect.lrs}

end.