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
package Torello.HTML;

import java.util.*;

import java.util.function.ObjIntConsumer;

// This is only needed for the Java Doc {@link ...} taglets.
import Torello.HTML.NodeSearch.TagNodePeekL1Inclusive;

import Torello.Java.LV;
import Torello.Java.StringParse;
import Torello.Java.Additional.Ret2;

/**
 * Methods for quickly & efficiently replacing the nodes on a Web-Page.
 * 
 * <BR /><BR /><EMBED CLASS='external-html' DATA-FILE-ID=RN>
 */
@Torello.JavaDoc.StaticFunctional
public class ReplaceNodes
{
    private ReplaceNodes() { }

    /**
     * <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_DESC>
     * 
     * @param page <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_PAGE>
     * @param updatedReplaceables <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_UPDATEREPL>
     * @param updateReplaceablesAfterBuild <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_URAB>
     * 
     * @return <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_RET>
     * 
     * @throws ReplaceableOutOfBoundsException  If any of the {@link Replaceable} instances returned
     * by the {@code 'updatedReplaceables'} iterator-parameter have <B><I>original location</I></B>
     * {@code Vector}-indices that are not within the bounds of the HTML page-{@code Vector}
     * (parameter {@code 'page'}).
     * 
     * @throws ReplaceablesOverlappingException If any of the {@link Replaceable} instances returned
     * by the {@code 'updatedReplaceables'} iterator-parameter have <B><I>original location</I></B>
     * {@code Vector}-indices that overlap.
     * 
     * @throws ReplaceablesUnsortedException If any of the {@link Replaceable} instances returned
     * by the {@code 'updatedReplaceables'} iterator-parameter have <B><I>original-starting 
     * locations</I></B> that are non-consecutive (out of order!)
     * 
     * <!-- In the JD Comments 'external-html/' directory, this is filed under 'r0/' -->
     */
    public static
        Ret2<Vector<HTMLNode>, Vector<Replaceable>>
        r(
            Vector<HTMLNode> page, Iterable<? extends Replaceable> updatedReplaceables,
            boolean updateReplaceablesAfterBuild
        )
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // First check for the case that 'updatedReplaceables' is empty
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        final int SIZE = page.size();

        // This entire loop is merely done for nothing more than error/exception checking.
        // It is mandatory that the SubSections which are passed are all 'in-order', that
        // none of them overlap, and that they all fit inside the 'page' vector parameter.

        Iterator<? extends Replaceable> iter = updatedReplaceables.iterator();

        // If there are no Replaceables in the Iterable, return the original page.
        if (! iter.hasNext())
        {
            if (! updateReplaceablesAfterBuild) return new Ret2<>(page, null);

            Vector<Replaceable> ret = new Vector<>();
            for (Replaceable r : updatedReplaceables) ret.add(r);
            return new Ret2<>(page, ret);
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Initialize the Loop variables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        Replaceable replaceable         = iter.next();
        Replaceable previousReplaceable = null;

        // These are used, specifically, for the error-checking part of the loop
        int start1  = replaceable.originalLocationStart();
        int end1    = replaceable.originalLocationEnd() - 1;  // Value is Exclusive
        int start2  = -1;
        int end2    = -1;

        // This is used for the exception messages only.  It is incremented on the last line of the
        // loop body.

        int i=0;

        // These are used, specifically, for the part that computes the size the final vector
        int size = 0;   // Total (Future) Size of the Return / Output Vector
        int last = 0;   // Temp Variable, it is easier to have a separate one for this

        while (iter.hasNext())
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Compute what the size of the returned HTML-Vector is going to be.
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            //
            // This is done by looking at the locations of all the replacements, and the number of
            // nodes between each replacement.
            //
            // For the part of this loop that is computing the size of the final vector, there
            // start2 and end2 pointers should just be ignored.  The start1, end1 pointer pair
            // are sufficient, as during each iteration, start2 and end2 are assigned to start1 and
            // end1 in the very next step anyways.
    
            size += (start1 - last);            // Size of the previous "in-between chunk"
            size += replaceable.currentSize();  // Size of the next SubSection
            last = end1;                        // advance the 'last' pointer

        
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Advance the Validity-Checking Pointer Pairs
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            // Advance pointer-pair #1 (but DONT'T do this one the VERY FIRST ITERATION)
            if (i > 0)
            {
                start1  = start2;
                end1    = end2;
            }

            // Advance Pointer Pair #2
            previousReplaceable = replaceable;
            replaceable         = iter.next();
            start2              = replaceable.originalLocationStart();
            end2                = replaceable.originalLocationEnd() - 1;


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // NOW... THE VALIDITY-CHECKING IF-STATEMENTS
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            /*
            System.out.println(
                "previousReplaceable: " + previousReplaceable +
                ", replaceable: " + replaceable + '\n' +
                "start1: " + start1 + ", end1: " + end1 + ", start2: " + start2 + ", end2: " + end2
            );
            */

            if (start2 < start1)

                throw new ReplaceablesUnsortedException(
                    "'updatedReplaceables' contains at least one Replaceable Element-Pair " +
                    "which is not sorted from first to last:\n" +
                    "The " + (i+1) + StringParse.ordinalIndicator(i+1) + " Replaceable returned " +
                    "by 'updatedReplaceables' starts at page-index " + start1 + '\n' +
                    "The " + (i+2) + StringParse.ordinalIndicator(i+2) + " Replaceable returned " +
                    "by 'updatedReplaceables' starts at page-index " + start2,
                    previousReplaceable, replaceable
                );

            if (    (start2 == start1)  // New section starts at same place as the previous section
                ||  (start2 <= end1)    // New section begins before the previous section ended
    
                // !!! Whenever a user has created a zero-length-replaceable (zero original length)
                // then the "end" of that replaceable will be "start-1".  Sounds a little silly,
                // right?  Well inserting a zero-length replaceable happens a lot in JavaDoc
                // Upgrader.  The two cases of the if-statement are both important.  Remember, the
                // iterator must be returning sorted elements, or else the previous if statement
                // would have already failed.
                )

                throw new ReplaceablesOverlappingException(
                    "'updatedReplaceables' contains at least one Replaceable Element-Pair " +
                    "that overlap each-other:\n" +
                    "The " + (i+1) + StringParse.ordinalIndicator(i+1) + " Replaceable returned " +
                    "by 'updatedReplaceables' has original-location " +
                    "[" + start1 + ", " + end1 + "]\n" +
                    "The " + (i+2) + StringParse.ordinalIndicator(i+2) + " Replaceable returned " +
                    "by 'updatedReplaceables' has original-location " +
                    "[" + start2 + ", " + end2 + ']',
                    previousReplaceable, replaceable
                );

            if (end1 > SIZE)

                throw new ReplaceableOutOfBoundsException(
                    "There was a Replaceable Element whose original-location was not within the " +
                    "bounds of page:\n" +
                    "The " + (i+1) + StringParse.ordinalIndicator(i+1) + " Replaceable returned " +
                    "by 'updatedReplaceables' has original-location " +
                    "[" + start1 + ", " + end1 + "]\n" +
                    "While page.size() is: " + SIZE,
                    replaceable
                );

            i++;
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // POST-LOOP FINISHING TOUCHES
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // "Ending Read" Check.  The very last location is not checked, because the loop breaks
        // before it gets to check pointer-pair-2 (on the last iteration)
        //
        // NOTE: The patholigical-cae where there is **ONLY ONE** SubSection in the updatedReplaceables
        //       input Collection.  If pointer-pair-2 is -1, there is no need to check it... :)
        //       If (pointer-pair-2 == -1), the loop body was never entered

        if (end2 != -1) if (end2 >= SIZE)

            throw new ReplaceableOutOfBoundsException(
                "There was a Replaceable Element whose original-location was not within the " +
                "bounds of page:\n" +
                "The " + (i+2) + StringParse.ordinalIndicator(i+2) + " Replaceable returned by " +
                "'updatedReplaceables' has original-location [" + start2 + ", " + end2 + "]\n" +
                "While page.size() is: " + SIZE,
                replaceable
            );

        // the very-last replaceable was not added to the size.
        size += (start1 - last);            // Size of the previous "in-between chunk"
        size += replaceable.currentSize();  // Size of the next SubSection
        last = end1;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build the Return Vector - NOTE - We just computed its final size!
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // ALSO: If the user has requested the DP's be udated, also build the "newSubSections" Vec
        //
        // The purpose of the above computation was for instantiating a properly-sized vector
        // at construction time.  This will save quite a bit of time that would be wasted on
        // vector resizing.

        Vector<HTMLNode> ret = new Vector<>(size);

        // By user request, only!  This really isn't *THAT* important.  All that the
        // 'newSubSections' Vector will have shall be the exact same-subsections that are passed
        // as a parameter to this method through the 'updatedReplaceables' parameter - *EXCEPT* that
        // their SubSection.location fields will be updated to hold the *ACTUAL* / *NEW* locations

        Vector<Replaceable> newReplaceables =
            updateReplaceablesAfterBuild ? new Vector<>() : null;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // MAIN-LOOP: Iterate each of the Replaceables that was passed as input to this method.
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // Add their contents to Output-Vector, and make sure to add all "in-between" nodes too!

        // The index-pointer to the **ORIGINAL-VECTOR** (a.k.a. the input vector)
        int pagePos=0;

        // This loop does the replacement.  It is quick and easy if you understand what replacing
        // a list of subsections involves.

        for (Replaceable r : updatedReplaceables)
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
            // Add all of the MOST-RECENT "In-Between Nodes"  (These are all nodes before next SS)
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            //
            // AFTERWARDS: Add all nodes in the next Sub-Section 

            // Retrieve all of the 'in-between' nodes
            while (pagePos < r.originalLocationStart()) ret.add(page.elementAt(pagePos++));

            // Add this Replaceable to the returned output list!
            r.addAllInto(ret);

            // Skip over the old nodes.
            pagePos = r.originalLocationEnd(); // don't add one, value is exclusive


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
            // User may request that the Sub-Section 'Locations' be updated, rather than discarded
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 

            // This is done for convenience so that the user knows where the sections are all
            // located in the new build.
            //
            // NOTE: All this is doing is changing the 'location' field of the old subsection
            //       which has changed to contain the new 'location'

            if (updateReplaceablesAfterBuild)
            {
                int ePos = ret.size();
                int sPos = ePos - r.currentSize() + 1;

                newReplaceables.add(r.moveAndUpdate(sPos));
            }
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // IMPORTANT: Add the last / final Elements that occur *AFTER* the *LAST* Sub-Section
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // This part should also be called "The Tail" of the Page.  (Put the Page-Tail back)

        while (pagePos < page.size()) ret.add(page.elementAt(pagePos++));


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // AGAIN: User may request that Sub-Section 'Locations' be updated, rather than discarded
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return updateReplaceablesAfterBuild
            ? new Ret2<>(ret, newReplaceables)
            : new Ret2<>(ret, null);
    }

    /**
     * Allows a user to quickly alter each <B STYLE='color: red;'>row</B> in an HTML
     * <B STYLE='color: red;'>table</B>, iteratively, in a manner that offers a tremendous
     * efficiency-improvement over the HTML {@code Iterator's} in the Node Seach Package.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=RN_R02_R03_FAST DATA-ITEM='table-row'>
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * <LI> {@code 'page'} is not null.
     *      </LI>
     * <LI> {@code 'table'} is non-null, and has {@link DotPair#start} and {@link DotPair#end}
     *      indices with integer-values smaller than the size of {@code 'page'}
     *      </LI>
     * <LI> {@code 'table'} has indices which point to {@code TagNode's} in {@code 'page'} that
     *      are opening {@code <TABLE>} and closing {@code </TABLE>} tags.
     *      </LI>
     * </UL>
     * 
     * @param page Any HTML Page or sub-page that has a table.
     * 
     * @param table A pointer to the table start and end index bounds.
     * 
     * @param tableRowModifier <EMBED CLASS='external-html' DATA-TYPE=Table DATA-ENTITY=Row 
     *      DATA-FILE-ID=RN_R02_R03_ROW_MOD>
     * 
     * @return <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_RET>
     * <!-- Bororwed from R01 RET -->
     * 
     * @see TagNodePeekL1Inclusive
     * @see ReplaceNodes#r(Vector, Iterable, boolean)
     * @see DotPair#exceptionCheck(Vector, String[])
     * @see SubSection
     * <!-- In the JD Comments 'external-html/' directory, this is filed under 'r02r03/' -->
     */
    public static Vector<HTMLNode> tableTR(
            Vector<HTMLNode> page, DotPair table,
            ObjIntConsumer<Vector<HTMLNode>> tableRowModifier
        )
    {
        // Ensure that page.elementAt(table.start) contains a "<TABLE>" element, and that
        // page.elementAt(table.end) contains a "</TABLE>" element.
        //
        // If some other type of TagNode, or a non-TagNode is present, this method throws one of
        // several exceptions to inform the user about the error.

        table.exceptionCheck(page, "table");

        // Retrieve all "<TR> ... </TR>" elements.  The "L1Inclusive" stipulates that any potential
        // inner-table rows (if there are any inner-tables), should be ignored.

        Vector<SubSection> rows = TagNodePeekL1Inclusive.all(page, table.start, table.end, "tr");

        // All this does is invoke the user-provided function-pointer on each table-row
        for (int i=0; i < rows.size(); i++) tableRowModifier.accept(rows.elementAt(i).html, i);

        // Update all Table-Rows.  Remove the old Rows, and insert the new ones.  This replace
        // operation does this much more efficiently than most replacement-code.

        return ReplaceNodes.r(page, rows, false).a;
    }

    /**
     * Allows a user to quickly alter each <B STYLE='color: red;'>item</B> in an HTML
     * <B STYLE='color: red;'>list</B> ({@code <OL>, <UL>} or {@code <MENU>}), iteratively, in a
     * manner that offers a tremendous efficiency-improvement over the HTML {@code Iterator's} in
     * the Node Seach Package.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=RN_R02_R03_FAST DATA-ITEM='list-item'>
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * <LI> {@code 'page'} is not null.
     *      </LI>
     * <LI> {@code 'list'} is non-null, and has {@link DotPair#start} and {@link DotPair#end}
     *      indices with integer-values smaller than the size of {@code 'page'}
     *      </LI>
     * <LI> {@code 'list'} has indices which point to {@code TagNode's} in {@code 'page'} that
     *      are opening-and-closing {@code <UL>, <OL>} or {@code <MENU>} tags.
     *      </LI>
     * </UL>
     * 
     * @param page Any HTML Page or sub-page that has an {@code <OL>, <UL>} or {@code <MENU>}.
     * 
     * @param list A pointer to the list start and end index bounds.
     * 
     * @param listItemModifier <EMBED CLASS='external-html' DATA-TYPE=List DATA-ENTITY=Item 
     *      DATA-FILE-ID=RN_R02_R03_ROW_MOD>
     * 
     * @return <EMBED CLASS='external-html' DATA-FILE-ID=RN_R01_RET> <!-- Bororwed from R01 RET -->
     * 
     * @see TagNodePeekL1Inclusive
     * @see ReplaceNodes#r(Vector, Iterable, boolean)
     * @see DotPair#exceptionCheck(Vector, String[])
     * @see SubSection
     * <!-- In the JD Comments 'external-html/' directory, this is filed under 'r02r03/' -->
     */
    public static Vector<HTMLNode> listLI(
            Vector<HTMLNode> page, DotPair list,
            ObjIntConsumer<Vector<HTMLNode>> listItemModifier
        )
    {
        // Ensure that page.elementAt(list.start) contains an "<OL>", "<UL>", or "<MENU>" element,
        // and that page.elementAt(list.end) contains an "</OL>", "</UL>" or "</MENU>" element.
        //
        // If some other type of TagNode, or a non-TagNode is present, this method throws one of
        // several exceptions to inform the user about the error.

        list.exceptionCheck(page, "ol", "ul", "menu");

        // Retrieve all "<LI> ... </LI>" elements.  The "L1Inclusive" stipulates that any potential
        // inner-list items (if there are any inner-lists), should be ignored.

        Vector<SubSection> items = TagNodePeekL1Inclusive.all(page, list.start, list.end, "li");

        // All this does is invoke the user-provided function-pointer on each list-item
        for (int i=0; i < items.size(); i++) listItemModifier.accept(items.elementAt(i).html, i);

        // Update all items.  Remove the old-Items, and insert the new ones.  This replace
        // operation does this much more efficiently than most replacement-code.

        return ReplaceNodes.r(page, items, false).a;
    }

    /**
     * Iterates the integer-pointer values in {@code int[] posArr}, and replaces the nodes inside
     * {@code 'html'} that have been identified by the {@code 'posArr'} list with a new node
     * supplied by the {@code interface ReplaceFunction}.  It should be obvious, that lambda
     * expressions may be used here.
     * 
     * <BR /><BR /><B CLASS=JDDescLabel>Returning 'null':</B>
     * 
     * <BR />If the Lambda-Target / Functional-Interface {@link ReplaceFunction} (whose method
     * is named {@link ReplaceFunction#getReplacement(HTMLNode, int, int)}
     * <B><I STYLE='color: red;'>actually returns <CODE>'null'</CODE></I></B>,
     * then null will indeed by inserted into the corresponding {@code Vector} position.
     * 
     * @param html Any HTML page or section that has been loaded already.
     * 
     * @param posArr This is usually generated by one of the node-search {@code 'Find.all(...)'}
     * methods.  Each and every one of the {@code 'Find.all(...)'} methods in the search package
     * will return an array of integers.  These integers represent positions/locations in the
     * passed HTML page {@code Vector}.
     * 
     * @param rf This is just a class that implements the {@code interface ReplaceFunction}.  The
     * interface has a single-method that will receive the position in the {@code Vector}, along
     * with the {@code HTMLNode} found at that location.  It is expected to produce a new version
     * of the {@code HTMLNode}.  This new node will be substituted into the page or sup-page.
     * 
     * <BR /><BR />This function-pointer may return null, and when it does, <I>the node located at
     * the current loop-iteration's {@code Vector}-index will not be replaced</I>.
     * 
     * @return The number of nodes that were succesfully replaced.  This number will be equal to
     * {@code posArr.length} minus the number of times {@code rf} returned null;
     * 
     * @throws ArrayIndexOutOfBoundsException <B><SPAN STYLE="color: red;">IMPORTANT
     * NOTE:</B></SPAN> Usually, a position-{@code array} is generated by one of the search-methods
     * in the NodeSearch package.  If, however, the {@code Vector} has since changed and
     * {@code posArr} contains stale-data, or if for other reasons there are invalid index-pointers
     * in {@code posArr}, then an {@code ArrayIndexOutOfBoundsException} will, naturally, be thrown
     * by java's {@code Vector.setElementAt(...)} method.
     * 
     * @see ReplaceFunction
     */
    public static int r(Vector<HTMLNode> html, int[] posArr, ReplaceFunction rf)
    {
        int counter=0, numReplaced=0;
        HTMLNode n;

        for (int pos : posArr)

            // pos is the vector-position, counter is the "iteration-count"
            if ((n = rf.getReplacement(html.elementAt(pos), pos, counter++)) != null)
            {
                html.setElementAt(n, pos);
                numReplaced++;
            }

        return numReplaced;
    }

    /**
     * This will replace <I>each and every node indicated by {@code 'posArr'}</I> with the
     * exact same replacement node {@code 'n'}.
     *
     * @param html Any HTML page or section that has been loaded already.
     * 
     * @param posArr This is usually generated by one of the node-search {@code 'Find.all(...)'}
     * methods.  Each and every one of the {@code 'Find.all(...)'} methods in the search package
     * will return an array of integers.  These integers represent positions/locations in the
     * passed HTML page {@code Vector}.
     *
     * @param n This may be any non-null {@code HTMLNode}.  This node shall be inserted (and will
     * replace) each node indicated by the parameter {@code 'posArr'}.
     * 
     * @throws ArrayIndexOutOfBoundsException <B><SPAN STYLE="color: red;">IMPORTANT
     * NOTE:</B></SPAN> Usually, a position-{@code array} is generated by one of the search-methods
     * in the NodeSearch package.  If, however, the {@code Vector} has since changed and
     * {@code posArr} contains stale-data, or if for other reasons there are invalid index-pointers
     * in {@code posArr}, then an {@code ArrayIndexOutOfBoundsException} will, naturally, be thrown
     * by java's {@code Vector.setElementAt(...)} method.
     */
    public static void r(Vector<HTMLNode> html, int[] posArr, HTMLNode n)
    { 
        int len= html.size();

        for (int i=0; i < len; i++) html.setElementAt(n, i);
    }

    /**
     * Convenience Method.
     * <BR />Invokes: {@link #r(Vector, int, int, ReplaceFunction)}
     * <BR />Passes: Entire Range of {@code html} into {@code sPos & ePos}
     */
    public static int r(Vector<HTMLNode> html, ReplaceFunction rf)
    { return r(html, 0, -1, rf); }

    /**
     * Convenience Method.
     * <BR />Invokes: {@link #r(Vector, int, int, ReplaceFunction)}
     * <BR />Passes: {@link DotPair#start} &amp; {@link DotPair#end} into {@code sPos & ePos}
     */
    public static int r(Vector<HTMLNode> html, DotPair dp, ReplaceFunction rf)
    { return r(html, dp.start, dp.end + 1, rf); }

    /**
     * Iterates <I>the entire html-page, checking every node</I>, replacing them by the
     * values returned by {@code 'rf'} (the replace function).  The {@link ReplaceFunction}
     * (parameter {@code 'rf'}) is expected to return values that either:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * <LI>provide a replacement {@code HTMLNode} for the indicated position</LI>
     * <LI>return null as a value - in which case, <I>no substitution will occur</I></LI>
     * </UL>
     *
     * <BR /><BR /><B CLASS=JDDescLabel>Returning 'null':</B>
     * 
     * <BR />If the Lambda-Target / Functional-Interface {@link ReplaceFunction} (whose method
     * is named {@link ReplaceFunction#getReplacement(HTMLNode, int, int)}
     * <B><I STYLE='color: red;'>returns <CODE>'null'</CODE></I></B>,
     * then in this particular method (differing from a previous method in this class), the
     * returned 'null' will be ignored, and no substitution will be performed.
     * 
     * @param html Any HTML page or section that has been loaded already.
     * 
     * @param sPos <EMBED CLASS='external-html' DATA-FILE-ID=SPOSVEC>
     * @param ePos <EMBED CLASS='external-html' DATA-FILE-ID=EPOSVEC>
     * 
     * @param rf This is just a class that implements the {@code interface ReplaceFunction}.  The
     * interface has a single-method (@code getReplacement(...)} that will receive the position in
     * the {@code Vector}, along with the {@code HTMLNode} found at that location.  It is expected
     * to return a new version of the {@code HTMLNode}.
     * 
     * <BR /><BR />This function-pointer may return null, and when it does, <I>the node located at
     * the current loop-iteration's {@code Vector}-index will not be replaced</I>.
     * 
     * @return The number of nodes that were succesfully replaced.  This number will be equal to
     * {@code html.size()} minus the number of times {@code rf} returned null;
     * 
     * @throws IndexOutOfBoundsException <EMBED CLASS='external-html' DATA-FILE-ID=VIOOBEX>
     * 
     * @see ReplaceFunction
     * @see HTMLNode
     */
    public static int r(Vector<HTMLNode> html, int sPos, int ePos, ReplaceFunction rf)
    {
        LV  l           = new LV(html, sPos, ePos);
        int numReplaced = 0;

        for (int i=l.start; i < l.end; i++)
        {
            // Here the vector-position and iteration-number are the same
            HTMLNode n = rf.getReplacement(html.elementAt(i), i, i);

            if (n != null)
            {
                html.setElementAt(n, i);
                numReplaced++;
            }
        }

        return numReplaced;
    }

    /**
     * Iterates the integer-pointer values listed by {@code 'posArr'}, and replaces every position
     * in {@code 'html'} with an {@code HTMLNode} from the nodes provided by the {@code 'newNodes'}
     * parameter.
     * 
     * @param html Any HTML page or section that has been loaded already.
     * 
     * @param posArr This is usually generated by one of the node-search {@code 'Find.all(...)'} 
     * methods.  Each and every one of the {@code 'Find.all(...)'} methods in the search package 
     * will return an {@code int[] array}.  These integers represent positions/locations in the
     * passed HTML page {@code Vector.}
     * 
     * @param newNodes This list of new nodes must have a length identical to the
     * {@code int[] posArr} (pointer-Array) length.
     * 
     * @throws ArrayIndexOutOfBoundsException This exception will throw if any of the elements of
     * {@code 'posArr'} point to a position in the {@code Vector<HTMLNode> v} parameter that are
     * out of bounds for that {@code Vector}.
     * 
     * @throws IllegalArgumentException if the length of the position array (pointer-array) is not
     * identical to the length of the new-nodes {@code Vector.}
     */
    public static void r(Vector<HTMLNode> html, int[] posArr, Vector<HTMLNode> newNodes)
    {
        if (posArr.length != newNodes.size()) throw new ArrayIndexOutOfBoundsException(
            "The pointer array 'posArr', and the replacement-node array 'newNodes' do not have " +
            "equal lengths!\n" +
            "posArr.length=" + posArr.length + ", newNodes.size()=" + newNodes.size()
        );

        int newNodesPos = 0;

        for (int pos : posArr) html.setElementAt(newNodes.elementAt(newNodesPos++), pos);
    }

    /**
     * Convenience Method.
     * <BR />Invokes: {@link #r(Vector, int, int, Vector)}
     * <BR />Assumes: {@code rangeWithUpdates.html} is located in {@code html} at
     * {@code rangeWithUpdates.location}
     * <BR />And: That {@code rangeWithUpdates.html} has been changed, and needs updating.
     */
    public static int r(Vector<HTMLNode> html, SubSection rangeWithUpdates)
    {
        return r(
            html, rangeWithUpdates.location.start, rangeWithUpdates.location.end,
            rangeWithUpdates.html
        );
    }

    /**
     * Convenience Method.
     * <BR />Invokes: {@link #r(Vector, int, int, Vector)}
     */
    public static int r(Vector<HTMLNode> html, DotPair range, Vector<HTMLNode> newNodes)
    { return r(html, range.start, range.end + 1, newNodes); }

    /**
     * Replaces the nodes currently within the vectorized HTML parameter {@code 'html'}, in the
     * sub-range provided by the {@code 'sPos'} and {@code 'ePos'} parameters - <I>using the new
     * nodes provided by {@code Vector}-Parameter {@code 'newNodes'}.</I>  This is, essentially,
     * a sub-range array-replacement operation.
     * 
     * <BR /><BR />Unless exactly the same number of nodes that are in the {@code 'replaceRange'}
     * are also in {@code 'newNodes'}, this method shall have to shorten or lengthen the size of
     * the HTML {@code Vector}.
     * 
     * @param html This may be any HTML page or sub-page
     * @param sPos <EMBED CLASS='external-html' DATA-FILE-ID=SPOSVEC>
     * @param ePos <EMBED CLASS='external-html' DATA-FILE-ID=EPOSVEC>
     * @param newNodes These are the new {@code HTMLNode's} that are to replace the old ones.
     * @return The change in the size (size-delta) of the input {@code html} parameter.
     * @throws IndexOutOfBoundsException <EMBED CLASS='external-html' DATA-FILE-ID=VIOOBEX>
     */
    public static int r(Vector<HTMLNode> html, int sPos, int ePos, Vector<HTMLNode> newNodes)
    {
        // The loop variable is needed because its constructor does all of the error checking.
        // The constructor also checks for the negative-ePos, and changes it if it is negative
        //
        // The original version of this method has been deprected, and left as a private method to
        // this class.  It was before noticing the "mirrored" stipulations about Vector-operation
        // "subList"  View the source-code to see the original replace-range method.

        LV l = new LV(html, sPos, ePos);

        List<HTMLNode> list = html.subList(l.start, l.end);

        // The Sun-Oracle Docs say that changes to the list returned by sub-list are mirrored into
        // changes in the original vector.  This is how sub-range operations are done.

        list.clear();
        list.addAll(newNodes);

        return newNodes.size() - (ePos - sPos); // ==> (newSize - originalSize)
    }

    // This was how to do this, until noticing in the Java-Docs that "subList" is "linked"
    // to the original list!
    private static void rOLD(Vector<HTMLNode> html, int sPos, int ePos, Vector<HTMLNode> newNodes)
    {
        LV l = new LV(html, sPos, ePos);

        // Replacement while-loop.  This will replace all nodes that can be replaced in the
        // "replace range" - without growing or shrinking the size of the underlying vector.
        //
        // AFTERWARDS   If there are still more nodes to insert, they will be inserted by
        //              growing the vector.
        //
        // AND ALSO     If there were fewer nodes to insert than the number that need to be
        //              removed the Vector will be shortened.

        int i = 0;
        int j = sPos;

        while ((j < l.end) && (i < newNodes.size()))
        {
            html.setElementAt(newNodes.elementAt(i), j);

            i++; j++;
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // CASE 1: The number of nodes to remove is precisely equal to the number being inserted.
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        if (l.size() == newNodes.size()) return;

    
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // CASE 2: The number of nodes being removed is greater than the number being inserted
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // Use Util.removeRange(...) to remove the remaining nodes that weren't replaced.
        // More nodes need to be removed than the number of nodes that have already been inserted
        // (in the previous loop).  In this case the original HTML Vector will SHRINK in SIZE.

        if (j < l.end) { Util.Remove.range(html, j, l.end);  return; }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // CASE 3: There are more nodes being added than the number of nodes being removed.
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // Use Vector.addAll(...) to add the rest which haven't been inserted yet.
        // The HTML Vector is going to grow.  There were fewer nodes removed than the number of
        // nodes that need to be inserted.
        //
        // NOTE: An "intermediate temp Vector" is used since the "Node Shift" is likely done more
        //       efficiently by 'Vector.addAll', than by calling 'Vector.add' multiple times.

        Vector<HTMLNode> temp = new Vector<>(newNodes.size() - i);

        while (i < newNodes.size()) temp.add(newNodes.elementAt(i++));

        html.addAll(l.end, temp);
    }

    /**
     * Convenience Method.
     * Invokes: {@link #r(Vector, int, int, HTMLNode)}
     */
    public static int r(Vector<HTMLNode> html, DotPair range, HTMLNode newNode)
    { return r(html, range.start, range.end + 1, newNode); }

    /**
     * Replaces the nodes currently within the vectorized HTML parameter {@code 'html'}, in the
     * sub-range provided by the {@code 'sPos'} and {@code 'ePos'} parameters, <I>with a single
     * new node provided by {@code 'newNode'}.</I>  Essentially, this is a <B>Range Removal</B>
     * Operation, because a complete sublist is removed, and only a single-node replaces it.
     * 
     * <BR /><BR />Unless the replacement-range (defined by {@code 'sPos'} and {@code 'ePos'}) has
     * a size equal to {@code '1'}, this operation will (obviously) shorten the size of the input
     * HTML {@code Vector} by {@code size - 1} nodes.
     * 
     * @param html This may be any HTML page or sub-page
     * 
     * @param sPos <EMBED CLASS='external-html' DATA-FILE-ID=SPOSVEC>
     * @param ePos <EMBED CLASS='external-html' DATA-FILE-ID=EPOSVEC>
     * 
     * @param newNode This is the new {@code HTMLNode} that is to replace the (entire) list
     * specified by parameters {@code 'sPos'} and {@code 'ePos'}.
     * 
     * @return The change in the size (size-delta) of the input {@code html} parameter.
     * The number returned will always equal {@code 1 - (ePos - sPos)}.  This means the return
     * value for this method will always be negative (i.e. the {@code Vector} shrunk) - unless
     * {@code sPos} and {@code ePos} had specified a range that was equal to 1.
     * 
     * @throws IndexOutOfBoundsException <EMBED CLASS='external-html' DATA-FILE-ID=VIOOBEX>
     */
    public static int r(Vector<HTMLNode> html, int sPos, int ePos, HTMLNode newNode)
    {
        // This method doesn't have any "for-loops", but the LV class does all the much needed
        // exception checks, and conversion computations. (ePos < 0  ==>  epos = html.size())

        LV l = new LV(html, sPos, ePos);

        html.setElementAt(newNode, l.start);

        if (l.size() > 1)

            // Util.removeRange(html, l.start + 1, l.end);  // OLD-WAY
            html.subList(l.start + 1, l.end).clear();       // NEW & IMPROVED WAY

        return 1 - (ePos - sPos); // ==> (newSize - originalSize)
    }

    /**
     * Replaces the instance of {@code HTMLNode} located at {@code Vector}-index {@code 'pos'}
     * with the contents of {@code Vector} parameter {@code 'newNodes'}.  This removes just
     * a single instance of {@code HTMLNode}, and replaces it with a list of nodes.
     * <BR /><BR />Note that this method will, indeed, lengthen the size of the input HTML
     * {@code Vector} (unless the {@code 'newNodes' Vector} being inserted has only 1 or 0
     * elements).
     *
     * @param html This may be any HTML page or sub-page.
     *
     * @param replacePos The position of the {@code HTMLNode} to be removed and replaced with the
     * list of nodes.
     * 
     * @param newNodes These are the new {@code HTMLNode's} that are to replace the old instance
     * of {@code HTMLNode} at position {@code 'pos'}.
     * 
     * @return The change in the size (size-delta) of the input {@code html} parameter.
     * The number returned will always equal {@code newNodes.size() - 1}
     * 
     * @throws ArrayIndexOutOfBoundsException This exception will throw if the specified 
     * {@code 'pos'} parameter is not within the bounds of the {@code Vector}.
     */
    public static int r(Vector<HTMLNode> html, int replacePos, Vector<HTMLNode> newNodes)
    {
        if (replacePos < 0) throw new ArrayIndexOutOfBoundsException(
            "The position passed to this method [" + replacePos + "] is negative."
        );

        if (replacePos >= newNodes.size()) throw new ArrayIndexOutOfBoundsException(
            "The position passed to this method [" + replacePos + "] is greater than or equal " +
            " to the size of the input HTML Vector parameter, 'html' [" + html.size() + "]"
        );

        html.removeElementAt(replacePos);
        html.addAll(replacePos, newNodes);

        return newNodes.size() - 1; // ==> (newSize - originalSize)
    }
}