This file is indexed.

/usr/share/perl5/PilotMgr/PilotSync.pm is in pilot-manager 1.107.0pre108-5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
##
# Generic pilot sychronizing routine.
# Alan Harder <Alan.Harder@Sun.Com>
# Version 0.96, 19990115
#
# Assumptions-
# 1. File side records have some sort of unique Id.
# 2. Pilot records don't need any translation (may add hooks for this later).
# 3. Records can contain scalars, hash refs and array refs, to any depth.
#    AppInfo record can contain _only_ scalars and arrays of scalars.
#
# Required parameters
#	Dlp	  = The $dlp parameter passed into the conduitSync method.
#
#	DbInfo    = Hash ref containing info about the pilot database.  Must
#		    have the following fields: name, creator, type, flags,
#		    version.  Ex: 'MemoDB, 'memo', 'DATA', 0, 0
#
#	ReqFields = Array ref listing the key fields in the records.
#		    These are the fields that will be compared to determine
#		    if two records are the same.
#
#	InfoFields= Array ref listing the key fields in the appinfo
#		    structure.  These fields will be compared and updated
#		    between the pilot and file sides.
#
#	IdField   = Name of the field used to store unique Id in file records.
#
#	MasterFile= Full path filename of conduit db file
#
#	Datafile  = Full path filename of datafile
#
#	NameHook  = Used for PilotMgr log output describing actions.
#		    This method takes a record hash as parameter and
#		    returns a "pretty name" string for the output.
#
#	ReadHook  = Code ref for method to read data from the file side.
#		    Subroutine should take data filename as a parameter and
#		    return a hash ref in the following format:
#			'__RECORDS' => Array ref containing all records
#				       Order will be maintained in case it is
#				       important to your app.
#
#			'__APPINFO' => Array ref containing appinfo data.
#				       (can be undef if no appinfo exists)
#
#			<REC_ID> => <index>   Mappings of your IdField values
#					      to the index that record can be
#					      found at in the __RECORDS list.
#
#	WriteHook = Code ref for method to write data back to file side.
#		    Subroutine parameters are data filename and Hash ref
#		    containing records (hash returned from ReadHook).
#
#	IdHook    = Code ref to generate a new unique record id for the file
#		    side.  Entire hash from ReadHook is passed in as param.
#
#	TranslateHook= (optional)
#		    A translate hook is require for conduits not using one
#		    of the five builtin databases (MemoDB, DatebookDB,
#		    ToDoDB, AddressDB, ExpenseDB).  Records will be returned
#		    from the pilot in 'raw' format.  This hook is used to
#		    read the raw data and fill in the hash with the relevant
#		    fields.  The parameters to this hook are the hash
#		    containing the raw data (key=='raw') and 0 for
#		    raw->fields, 1 for fields->raw.
#
#	AppInfoHook= (optional)Code ref to subroutine which translates to
#		    and from a 'raw' appinfo from pilot and the expanded
#		    format.  Parameters are appinfo hash and 0 for
#		    raw->expanded, 1 for expanded->raw.
#
#	CancelFlag= (optional)Scalar ref for cancel flag.  If value gets
#		    set to a non-empty string before actual sychronization
#		    begins then whole operation gets cancelled.  During
#		    the sync a cancel will abort all file changes, but
#		    pilot changes up to that point have already been written.
#		    Upon a cancel the new value of the cancel flag gets
#		    printed to the pilotmgr log (should inform user of cancel).
#
package PilotSync;

use Data::Dumper;
use Carp;
use strict;

my $VERSION = '0.96 BETA2';
my ($master_db, $file_db, $pilot_db);
my ($gIdField, $gIdHook, $gReqFields, $gTranslateHook, $gNameHook);
my ($FILECHANGE, $PILOTCHANGE, $FILEDELETE, $PILOTDELETE) = (1,4,2,8);
my (@gNotSynced);

sub doSync
{
    my ($dlp, $dbinfo, $reqFields, $infoFields, $idField,
	$masterFile, $dataFile, $nameHook, $readHook, $writeHook, $idHook,
	$translateHook, $appinfoHook, $cancelFlag) = @_;

    $gIdField = $idField;
    $gIdHook = $idHook;
    $gReqFields = $reqFields;
    $gTranslateHook = $translateHook;
    $gNameHook = $nameHook;
    @gNotSynced = ();

    # Open or create database
    #
    my ($pilot_dbhandle, $appinfo);
    $pilot_dbhandle = &openDB($dlp, $dbinfo);

    unless (defined $pilot_dbhandle)
    {
	PilotMgr::msg("Unable to open '$dbinfo->{name}'.  Aborting!");
	return;
    }

    # Set display on pilot
    #
    $dlp->getStatus();					PilotMgr::update();

    # Read inputs
    #
    $dlp->tickle;
    $dlp->watchdog(20);

    $master_db = &readMaster($masterFile);		PilotMgr::update();
    $file_db = &$readHook($dataFile);			PilotMgr::update();

    $dlp->watchdog(0);
    $dlp->tickle;

    $pilot_db = %$master_db
		    ? &readPilotChanges($dlp, $pilot_dbhandle, $translateHook)
		    : &readPilotAll($dlp, $pilot_dbhandle, $translateHook);

    # Check if the sync has been cancelled
    #
    PilotMgr::update();
    if (defined $cancelFlag and $$cancelFlag)
    {
	$pilot_dbhandle->close();
	PilotMgr::msg($$cancelFlag);
	PilotMgr::msg('No changes written to pilot or desktop.');
	croak('cancel');
    }

    # Do sync
    #
    &syncAppInfo($pilot_dbhandle, $infoFields, $appinfoHook);
    &doFastSync($dlp, $pilot_dbhandle, $cancelFlag);

    if (defined $cancelFlag and $$cancelFlag)
    {
	$pilot_dbhandle->close();
	PilotMgr::msg($$cancelFlag);
	PilotMgr::msg('Cancel during sync!  All file modifications listed ' .
	    'above will NOT be saved, but pilot changes above have already ' .
	    'been written.');
	croak('cancel');
    }

    # Write dbs
    #
    $dlp->tickle;
    $dlp->watchdog(20);

    &writeMaster($masterFile, $master_db);
    &$writeHook($dataFile, $file_db);

    $dlp->watchdog(0);
    $dlp->tickle;

    # Clear flags
    #
    $pilot_dbhandle->purge();
    $pilot_dbhandle->resetFlags();

    # If there were any unmergeable changes, mark pilot records still dirty
    #
    foreach (@gNotSynced)
    {
	my $rec = $pilot_dbhandle->getRecordByID($_);
	$rec->{'modified'} = 1;
	$pilot_dbhandle->setRecord($rec);
    }

    # Close db
    #
    $pilot_dbhandle->close();
}

sub openDB
{
    my ($dlp, $dbinfo) = @_;
    my ($dbname, $dbh) = ($dbinfo->{'name'});

    eval
    {
	$dbh = $dlp->open($dbname);
    };
    if ($@ =~ /read-only value/)
    {
	PilotMgr::msg("Pilot database '$dbname' does not exist.\n" .
		      "Creating it...");

	$dbh = $dlp->create($dbname, $dbinfo->{'creator'},
			    $dbinfo->{'type'}, $dbinfo->{'flags'},
			    $dbinfo->{'version'});
    }
    elsif ($@)
    {
	croak($@);
    }

    return $dbh;
}

sub readMaster
{
    my ($fname) = @_;
    return {} unless (-r "$fname");

    use vars qw($masterdb);
    do "$fname";
    return $masterdb;
}

sub writeMaster
{
    my ($fname, $masterdb) = @_;

    $Data::Dumper::Purity = 1;
    $Data::Dumper::Deepcopy = 1;
    $Data::Dumper::Indent = 0;

    unless (open(FD, ">$fname"))
    {
	PilotMgr::msg("Unable to write to $fname.  Help!");
	return;
    }

    print FD Data::Dumper->Dumpxs([$masterdb], ['masterdb']), "1;\n";
    close(FD);
}

sub readPilotChanges
{
    my ($dlp, $dbh, $translateHook) = @_;
    my ($db, $i, $msg, $rec) = ({}, 1, "Reading Pilot Changes");

    PilotMgr::status($msg, 0);
    while (1)
    {
	$rec = $dbh->getNextModRecord();
	last unless (defined($rec));

	&$translateHook($rec) if (defined $translateHook);

	$db->{$rec->{'id'}} = $rec;

	PilotMgr::status($msg, $i++);
	$i = 96 if ($i > 100);
    }
    PilotMgr::status($msg, 100);

    return $db;
}

sub readPilotAll
{
    my ($dlp, $dbh, $translateHook) = @_;
    my ($db, $i, $msg, $rec, $max) = ({}, 0, "Reading All Pilot Records");

    PilotMgr::status($msg, 0);
    $max = $dbh->getRecords();
    while (1)
    {
	$rec = $dbh->getRecord($i++);
	last unless (defined $rec);

	&$translateHook($rec) if (defined $translateHook);
	$db->{$rec->{'id'}} = $rec;

	PilotMgr::status($msg, int(100 * $i / $max));
    }
    PilotMgr::status($msg, 100);

    return $db;
}

################################

sub doFastSync
{
    my ($dlp, $dbh, $cancel) = @_;
    my ($frec, $mrec, $prec, $id, $i, $tcl);

    # Check file records first
    #
    $tcl = time;
    for ($i=$[; $i < @{$file_db->{'__RECORDS'}}; $i++)
    {
	$frec = $file_db->{'__RECORDS'}->[$i];

	# Find matching records in master and pilot, if any
	#
	$id = $master_db->{$gIdField . '_' . $frec->{$gIdField}};
	$mrec = defined $id ? $master_db->{$id} : undef;
	$prec = defined $id ? $pilot_db->{$id} : undef;

	unless (defined $mrec)
	{
	    # Try to match to existing pilot record
	    #
	    $prec = &findPilotMatch($frec);
	    $id = $prec->{'id'} if (defined $prec);
	}

	# Sync record - method returns any change in size to
	# $file_db->{records} array so we can keep this loop straight..
	#
	$i += &syncRecord($mrec, $frec, $prec, $dlp, $dbh);

	delete $pilot_db->{$id} if (defined $prec);
	$id = $master_db->{$gIdField . '_' . $frec->{$gIdField}};
	$master_db->{$id}->{'__GOT_SYNCED'} = 1 if (defined $id);

	if (time - $tcl >= 20)
	{
	    $dlp->tickle;
	    $tcl = time;
	}

	PilotMgr::update();
	return if (defined $cancel and $$cancel);
    }

    # find deleted file records
    #
    $frec = undef;
    foreach $mrec (values %$master_db)
    {
	next unless (ref $mrec eq 'HASH');

	if (defined $mrec->{'__GOT_SYNCED'})
	{
	    delete $mrec->{'__GOT_SYNCED'};
	    next;
	}

	$id = $master_db->{$gIdField . '_' . $mrec->{$gIdField}};
	$prec = defined $id ? $pilot_db->{$id} : undef;

	&syncRecord($mrec, $frec, $prec, $dlp, $dbh, $FILEDELETE);

	PilotMgr::update();
	return if (defined $cancel and $$cancel);
    }

    # remaining pilot changes
    $tcl = time;
    foreach $prec (values %$pilot_db)
    {
	# Find matching records in master and file, if any
	#
	$mrec = $master_db->{$prec->{'id'}};
	$frec = defined($mrec) ?
	    $file_db->{'__RECORDS'}->[$file_db->{$mrec->{$gIdField}}] : undef;

	&syncRecord($mrec, $frec, $prec, $dlp, $dbh);

	if (time - $tcl >= 20)
	{
	    $dlp->tickle;
	    $tcl = time;
	}

	PilotMgr::update();
	return if (defined $cancel and $$cancel);
    }
}

sub syncRecord
{
    my ($mrec, $frec, $prec, $dlp, $dbh, $rule) = @_;
    $rule = 0 unless (defined $rule);

    $rule |= $FILECHANGE
	if (defined $frec and (!defined $mrec || &recsDiffer($frec, $mrec)));

    $rule |= $prec->{'deleted'} ? $PILOTDELETE : $PILOTCHANGE
	if (defined $prec);

    ##
    # Apply rule...
    #
    # Rules:
    #   0: Pilot=unchanged    File=unchanged    * No action
    #   1: Pilot=unchanged    File=changed/new  * Update Pilot
    #   2: Pilot=unchanged    File=deleted      * Delete Pilot
    #   4: Pilot=changed/new  File=unchanged    * Update File
    #   8: Pilot=deleted      File=unchanged    * Delete File
    #  10: Pilot=deleted      File=deleted      * Just remove master rec
    #
    #   5: Pilot=changed/new  File=changed/new  * Merge changes, Update Both
    #   6: Pilot=changed/new  File=deleted      * Restore File ?
    #   9: Pilot=deleted      File=changed/new  * Restore Pilot ?
    #
    my ($file_sizechange, $id) = (0);
    return 0 if ($rule == 0);

    if ($rule == 10)
    {
	delete $master_db->{$prec->{'id'}};
	delete $master_db->{$gIdField . '_' . $mrec->{$gIdField}};
    }

    if ($rule == 5)
    {
	unless (&recsDiffer($frec, $prec))
	{
	    # both changed, but they're still the same- just update master
	    unless (defined $mrec)
	    {
		$master_db->{$prec->{'id'}} = $frec;
		$master_db->{$gIdField . '_' . $frec->{$gIdField}} =
		    $prec->{'id'};
		PilotMgr::msg("Matching '" . &$gNameHook($prec) . "' " .
			      "(pilot $prec->{id}, file $frec->{$gIdField})");
	    }
	    else
	    {
		&copyRec($frec, $mrec);
	    }
	    return 0;
	}

	# Attempt to automatically merge data
	#
	my ($mergeOk, $fchange, $pchange) = &mergeRec($mrec, $frec, $prec);
	my ($pname, $fname) = (&$gNameHook($prec), &$gNameHook($frec));
	$pname .= " / $fname" if ($pname ne $fname);

	if ($mergeOk)
	{
	    PilotMgr::msg(
		"Pilot/File changes successfully merged for: $pname");
	}
	else
	{
	    push(@gNotSynced, $prec->{'id'});
	    PilotMgr::msg("Both Pilot and File records changed for: $pname\n" .
			  "** Unable to merge all changes!\n** Please edit " .
			  'records to make them the same.');
	}

	if ($pchange)
	{
	    &$gTranslateHook($prec, 1) if (defined $gTranslateHook);
	    $dbh->setRecord($prec);
	    PilotMgr::msg('Update Pilot: ' . &$gNameHook($prec));
	}
	if ($fchange)
	{
	    PilotMgr::msg('Update File: ' . &$gNameHook($frec));
	}
    }

    if ($rule == 1 or $rule == 9)
    {
	# Update Pilot
	#
	$prec = &copyRec($frec, (defined($prec) ? $prec : $dbh->newRecord()));
	$prec->{'id'} = $master_db->{$gIdField . '_' . $frec->{$gIdField}};
	$prec->{'id'} ||= 0;
	$prec->{'secret'} ||= '';
	$prec->{'category'} ||= 0;

	# going to restore a deleted pilot rec with file changes:
	$prec->{'deleted'} = 0 if ($rule ==9);

	&$gTranslateHook($prec, 1) if (defined $gTranslateHook);

	$id = $dbh->setRecord($prec);
	PilotMgr::msg('Update Pilot: ' . &$gNameHook($frec));

	$master_db->{$id} = $frec;
	$master_db->{$gIdField . '_' . $frec->{$gIdField}} = $id
	    unless (defined $mrec);
    }

    if ($rule == 4 and defined $frec and !&recsDiffer($frec, $prec))
    {
	# Pilot reports record modified, but it's really still the same..
	# (this can happen after using Installer to restore a db)
	#
	$rule = -1;
    }

    if ($rule == 4 or $rule == 6)
    {
	# Update File
	#
	unless (defined $frec)
	{
	    $frec = {};
	    $frec->{$gIdField} = &$gIdHook($file_db);
	    push(@{$file_db->{'__RECORDS'}}, $frec);
	    $file_db->{$frec->{$gIdField}} = $#{$file_db->{'__RECORDS'}};
	    $file_sizechange = 1;
	}

	&copyRec($prec, $frec);
	PilotMgr::msg('Update File: ' . &$gNameHook($prec));

	$master_db->{$prec->{'id'}} = $frec;
	$master_db->{$gIdField . '_' . $frec->{$gIdField}} = $prec->{'id'}
	    unless (defined $mrec);
    }

    if ($rule == 2)
    {
	# Delete Pilot
	#
	$id = $master_db->{$gIdField . '_' . $mrec->{$gIdField}};

	$dbh->deleteRecord($id);
	PilotMgr::msg('Delete Pilot: ' . &$gNameHook($mrec));

	delete $master_db->{$id};
	delete $master_db->{$gIdField . '_' . $mrec->{$gIdField}};
    }

    if ($rule == 8 and defined $mrec)
    {
	# Delete File
	#
	$id = $file_db->{$mrec->{$gIdField}};
	splice(@{$file_db->{'__RECORDS'}}, $id, 1);
	delete $file_db->{$mrec->{$gIdField}};
	$file_sizechange = -1;
	PilotMgr::msg('Delete File: ' . &$gNameHook($mrec));

	for (; $id < @{$file_db->{'__RECORDS'}}; $id++)
	{
	    $file_db->{ $file_db->{'__RECORDS'}->[$id]->{$gIdField} }--;
	}

	delete $master_db->{$gIdField . '_' . $mrec->{$gIdField}};
	delete $master_db->{$prec->{'id'}};
    }

    return $file_sizechange;
}

sub copyRec
{
    my ($src, $dst) = @_;
    my ($fld, $val);

    foreach $fld (@$gReqFields)
    {
	$val = $src->{$fld};
	if (ref $val eq 'HASH')		{ $dst->{$fld} = &copyHash($val);   }
	elsif (ref $val eq 'ARRAY')	{ $dst->{$fld} = &copyArray($val);  }
	else				{ $dst->{$fld} = $val;		    }
    }
    return $dst;
}

sub copyHash
{
    my ($src) = @_;
    my ($h, $fld, $val) = ({});

    foreach $fld (keys %$src)
    {
	$val = $src->{$fld};
	if (ref $val eq 'HASH')		{ $h->{$fld} = &copyHash($val);    }
	elsif (ref $val eq 'ARRAY')	{ $h->{$fld} = &copyArray($val);   }
	else				{ $h->{$fld} = $val;		   }
    }
    return $h;
}

sub copyArray
{
    my ($src) = @_;
    my ($a, $val) = ([]);

    foreach $val (@$src)
    {
	if (ref $val eq 'HASH')		{ push(@$a, &copyHash($val));	}
	elsif (ref $val eq 'ARRAY')	{ push(@$a, &copyArray($val));	}
	else				{ push(@$a, $val);		}
    }
    return $a;
}

sub recsDiffer
{
    my ($rec1, $rec2) = @_;
    my ($fld);

    foreach $fld (@$gReqFields)
    {
	return 1 if (defined $rec1->{$fld} ^ defined $rec2->{$fld});
	next unless (defined $rec1->{$fld});
	return 1 if (ref $rec1->{$fld} ne ref $rec2->{$fld}		   or
		     ref $rec1->{$fld} eq 'HASH'  &&
				&hashDiffer($rec1->{$fld}, $rec2->{$fld})  or
		     ref $rec1->{$fld} eq 'ARRAY'  &&
				&arrayDiffer($rec1->{$fld}, $rec2->{$fld}) or
		     !ref $rec1->{$fld}  &&
				$rec1->{$fld} ne $rec2->{$fld}		   );
    }
    return 0;
}

sub hashDiffer
{
    my ($h1, $h2) = @_;
    my ($fld);

    foreach $fld (keys %$h1)
    {
	return 1 if (!exists $h1->{$fld}  or
		     defined $h1->{$fld} ^ defined $h2->{$fld});
	next unless (defined $h1->{$fld});
	return 1 if (ref $h1->{$fld} ne ref $h2->{$fld}			   or
		     ref $h1->{$fld} eq 'HASH'  &&
			&hashDiffer($h1->{$fld}, $h2->{$fld})		   or
		     ref $h1->{$fld} eq 'ARRAY'  &&
			&arrayDiffer($h1->{$fld}, $h2->{$fld})		   or
		     !ref $h1->{$fld}  &&  $h1->{$fld} ne $h2->{$fld}	   );
    }
    return 0;
}

sub arrayDiffer
{
    my ($a1, $a2) = @_;
    my ($i);

    return 1 if ($#$a1 ne $#$a2);
    for ($i=0; $i < @$a1; $i++)
    {
	return 1 if (defined $a1->[$i] ^ defined $a2->[$i]);
	next unless (defined $a1->[$i]);
	return 1 if (ref $a1->[$i] ne ref $a2->[$i]			or
		     ref $a1->[$i] eq 'HASH'  &&
			&hashDiffer($a1->[$i], $a2->[$i])		or
		     ref $a1->[$i] eq 'ARRAY'  &&
			&arrayDiffer($a1->[$i], $a2->[$i])		or
		     !ref $a1->[$i]  &&  $a1->[$i] ne $a2->[$i]		);
    }
    return 0;
}

sub findPilotMatch
{
    my ($frec) = @_;
    my ($prec);

    foreach $prec (values %$pilot_db)
    {
	return $prec unless (&recsDiffer($frec, $prec));
    }
    return undef;
}

sub mergeRec
{
    my ($mrec, $frec, $prec) = @_;
    return &mergeHash($mrec, $frec, $prec, @$gReqFields);
}

sub mergeHash
{
    my ($m, $f, $p, @fields) = @_;
    my ($fld, $mval, $fval, $pval);
    my ($ok, $fchng, $pchng) = (1, 0, 0);

    @fields = keys %$m unless (@fields);
    foreach $fld (@fields)
    {
	$mval = $m->{$fld};
	$fval = $f->{$fld};
	$pval = $p->{$fld};
	if (ref $mval eq 'HASH')
	{
	    $f->{$fld} = $fval = {} unless (defined $fval);
	    $p->{$fld} = $pval = {} unless (defined $pval);
	    @_ = &mergeHash($mval, $fval, $pval);
	    $ok &= $_[0];
	    $fchng |= $_[1];
	    $pchng |= $_[2];
	}
	elsif (ref $mval eq 'ARRAY')
	{
	    $f->{$fld} = $fval = [] unless (defined $fval);
	    $p->{$fld} = $pval = [] unless (defined $pval);
	    @_ = &mergeArray($mval, $fval, $pval);
	    $ok &= $_[0];
	    $fchng |= $_[1];
	    $pchng |= $_[2];
	}
	else
	{
	    if ($mval eq $fval and $fval ne $pval)
	    {
		$f->{$fld} = $m->{$fld} = $pval;
		$fchng = 1;
	    }
	    elsif ($mval eq $pval and $pval ne $fval)
	    {
		$p->{$fld} = $m->{$fld} = $fval;
		$pchng = 1;
	    }
	    elsif ($fval ne $pval)
	    {
		$ok = 0;
	    }
	    elsif ($fval ne $mval)
	    {
		$m->{$fld} = $fval;
	    }
	}
    }
    return ($ok, $fchng, $pchng);
}

sub mergeArray
{
    my ($m, $f, $p) = @_;
    my ($i, $mval, $fval, $pval);
    my ($ok, $fchng, $pchng) = (1, 0, 0);

    for ($i=$[; $i < @$m; $i++)
    {
	$mval = $m->[$i];
	$fval = $f->[$i];
	$pval = $p->[$i];
	if (ref $mval eq 'HASH')
	{
	    $f->[$i] = $fval = {} unless (defined $fval);
	    $p->[$i] = $pval = {} unless (defined $pval);
	    @_ = &mergeHash($mval, $fval, $pval);
	    $ok &= $_[0];
	    $fchng |= $_[1];
	    $pchng |= $_[2];
	}
	elsif (ref $mval eq 'ARRAY')
	{
	    $f->[$i] = $fval = [] unless (defined $fval);
	    $p->[$i] = $pval = [] unless (defined $pval);
	    @_ = &mergeArray($mval, $fval, $pval);
	    $ok &= $_[0];
	    $fchng |= $_[1];
	    $pchng |= $_[2];
	}
	else
	{
	    if ($mval eq $fval and $fval ne $pval)
	    {
		$f->[$i] = $m->[$i] = $pval;
		$fchng = 1;
	    }
	    elsif ($mval eq $pval and $pval ne $fval)
	    {
		$p->[$i] = $m->[$i] = $fval;
		$pchng = 1;
	    }
	    elsif ($fval ne $pval)
	    {
		$ok = 0;
	    }
	    elsif ($fval ne $mval)
	    {
		$m->[$i] = $fval;
	    }
	}
    }
    return ($ok, $fchng, $pchng);
}

sub syncAppInfo
{
    my ($dbh, $InfoFields, $translateHook) = @_;
    my ($writePi, $pappi, $fappi, $mappi, $fld) = (0);

    $pappi = $dbh->getAppBlock();
    $fappi = $file_db->{'__APPINFO'};

    return unless (defined $pappi or defined $fappi);

    &$translateHook($pappi, 0) if (defined $translateHook and defined $pappi);

    $mappi = $master_db->{'__APPINFO'};
    $master_db->{'__APPINFO'} = $mappi = {} unless (defined $mappi);
    $mappi->{'__GOT_SYNCED'} = 1;

    $file_db->{'__APPINFO'} = $fappi = {} unless (defined $fappi);
    unless (defined $pappi)
    {
	$pappi = bless {}, 'PDA::Pilot::AppBlock';
	$writePi=1;
    }

    foreach $fld (@$InfoFields)
    {
	if (ref $pappi->{$fld} eq 'ARRAY' or ref $fappi->{$fld} eq 'ARRAY')
	{
	    # for array values
	    #
	    my ($size, $i);
	    $size = @{$fappi->{$fld}} if defined($fappi->{$fld});
	    $size = @{$pappi->{$fld}} if defined($pappi->{$fld});

	    $pappi->{$fld} = [] unless (defined $pappi->{$fld});
	    $fappi->{$fld} = [] unless (defined $fappi->{$fld});
	    $mappi->{$fld} = [] unless (defined $mappi->{$fld});

	    for ($i=0; $i < $size; $i++)
	    {
		$writePi |= &aiCheck($pappi, $fappi, $mappi, $fld, $i);
	    }
	}
	else
	{
	    # for scalar values
	    #
	    $writePi |= &aiCheck($pappi, $fappi, $mappi, $fld);
	}
    }

    if ($writePi)
    {
	&$translateHook($pappi, 1) if (defined $translateHook);
	PilotMgr::msg("Updating Pilot AppInfo..");
	$dbh->setAppBlock($pappi);
    }
}

sub aiCheck
{
    my ($pappi, $fappi, $mappi, $fld, $i) = @_;
    my ($pichange, $pval, $fval, $mval) = (0);

    $pval = $pappi->{$fld};
    $fval = $fappi->{$fld};
    $mval = $mappi->{$fld};
    if (defined $i)
    {
	$pval = $pval->[$i];
	$fval = $fval->[$i];
	$mval = $mval->[$i];
    }

    # Pilot   Master  File
    # undef   any     undef	-> huh?
    # def \\  any  // def	-> copy to master (pilot==file)
    # undef   any     def	-> use file
    # def     any     undef	-> use pilot
    # def  == def     def	-> use file
    # def     def ==  def	-> use pilot
    # def  != any !=  def	-> merge? do nothing for now

    return unless (defined $pval or defined $fval);

    if (defined $pval and defined $fval and $pval eq $fval)
    {
	if (defined $i) { $mappi->{$fld}->[$i] = $fval; }
	else		{ $mappi->{$fld} = $fval;	}
    }
    elsif (&empty($fval) or (defined $mval and $fval eq $mval))
    {
	if (defined $i) { $mappi->{$fld}->[$i] = $fappi->{$fld}->[$i] = $pval;}
	else		{ $mappi->{$fld} = $fappi->{$fld} = $pval;	      }
    }
    elsif (&empty($pval) or (defined $mval and $pval eq $mval))
    {
	if (defined $i) { $mappi->{$fld}->[$i] = $pappi->{$fld}->[$i] = $fval;}
	else		{ $mappi->{$fld} = $pappi->{$fld} = $fval;	      }
	$pichange = 1;
    }
    else
    {
	PilotMgr::msg("AppInfo field $fld" .
	    ((defined $i) ? "[$i]" : '') .
	    " changed on both pilot and file!\n" .
	    "Not updating either side.. please change them to be the same.\n" .
	    "(pilot=$pval, file=$fval)");
    }

    return $pichange;
}

sub empty
{
    return (!defined $_[0] or !length($_[0]));
}

1;