Source

lp_solve / shared / commonlib.c

Full commit
  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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

#include <sys/types.h>

#if defined INTEGERTIME || defined CLOCKTIME || defined PosixTime
# include <time.h>
#elif defined EnhTime
# include <windows.h>
#else
# include <sys/timeb.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#ifdef WIN32
# include <io.h>       /* Used in file search functions */
#endif
#include <ctype.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include "commonlib.h"

#ifdef FORTIFY
# include "lp_fortify.h"
#endif

#if defined FPUexception
/* FPU exception masks */
unsigned int clearFPU()
{
  return( _clearfp() );
}
unsigned int resetFPU(unsigned int mask)
{
  _clearfp();
  mask = _controlfp( mask, 0xfffff);
  return( mask );
}
unsigned int catchFPU(unsigned int mask)
{
  /* Always call _clearfp before enabling/unmasking a FPU exception */
  unsigned int u = _clearfp();

  /* Set the new mask by not-and'ing it with the previous settings */
  u = _controlfp(0, 0);
  mask = u & ~mask;
  mask = _controlfp(mask, _MCW_EM);

  /* Return the previous mask */
  return( u );
}
#endif

/* Math operator equivalence function */
int intpow(int base, int exponent)
{
  int result = 1;
  while(exponent > 0) {
    result *= base;
    exponent--;
  }
  while(exponent < 0) {
    result /= base;
    exponent++;
  }
  return( result );
}
int mod(int n, int d)
{
  return(n % d);
}

/* Some string functions */
void strtoup(char *s)
{
  if(s != NULL)
  while (*s) {
    *s = toupper(*s);
    s++;
  }
}
void strtolo(char *s)
{
  if(s != NULL)
  while (*s) {
    *s = tolower(*s);
    s++;
  }
}
void strcpyup(char *t, char *s)
{
  if((s != NULL) && (t != NULL)) {
    while (*s) {
      *t = toupper(*s);
      t++;
      s++;
    }
    *t = '\0';
  }
}
void strcpylo(char *t, char *s)
{
  if((s != NULL) && (t != NULL)) {
    while (*s) {
      *t = tolower(*s);
      t++;
      s++;
    }
    *t = '\0';
  }
}

/* Unix library naming utility function */
MYBOOL so_stdname(char *stdname, char *descname, int buflen)
{
  char *ptr;

  if((descname == NULL) || (stdname == NULL) || (((int) strlen(descname)) >= buflen - 6))
    return( FALSE );

  strcpy(stdname, descname);
  if((ptr = strrchr(descname, '/')) == NULL)
    ptr = descname;
  else
    ptr++;
  stdname[(int) (ptr - descname)] = 0;
  if(strncmp(ptr, "lib", 3))
    strcat(stdname, "lib");
  strcat(stdname, ptr);
  if(strcmp(stdname + strlen(stdname) - 3, ".so"))
    strcat(stdname, ".so");
  return( TRUE );
}

/* Return the greatest common divisor of a and b, or -1 if it is
   not defined. Return through the pointer arguments the integers
   such that gcd(a,b) = c*a + b*d. */
int gcd(LLONG a, LLONG b, int *c, int *d)
{
  LLONG q,r,t;
  int   cret,dret,C,D,rval, sgn_a = 1,sgn_b = 1, swap = 0;

  if((a == 0) || (b == 0))
    return( -1 );

  /* Use local multiplier instances, if necessary */
  if(c == NULL)
    c = &cret;
  if(d == NULL)
    d = &dret;

  /* Normalize so that 0 < a <= b */
  if(a < 0){
    a = -a;
    sgn_a = -1;
  }
  if(b < 0){
    b = -b;
    sgn_b = -1;
  }
  if(b < a){
    t = b;
    b = a;
    a = t;
    swap = 1;
  }

  /* Now a <= b and both >= 1. */
  q = b/a;
  r = b - a*q;
  if(r == 0) {
    if(swap){
      *d = 1;
      *c = 0;
    }
    else {
      *c = 1;
      *d = 0;
    }
    *c = sgn_a*(*c);
    *d = sgn_b*(*d);
    return( (int) a );
  }

  rval = gcd(a,r,&C,&D);
  if(swap){
    *d = (int) (C-D*q);
    *c = D;
  }
  else {
    *d = D;
    *c = (int) (C-D*q);
  }
  *c = sgn_a*(*c);
  *d = sgn_b*(*d);
  return( rval );
}

/* Array search functions */
int findIndex(int target, int *attributes, int count, int offset)
{
  int focusPos, beginPos, endPos;
  int focusAttrib, beginAttrib, endAttrib;

 /* Set starting and ending index offsets */
  beginPos = offset;
  endPos = beginPos + count - 1;
  if(endPos < beginPos)
    return(-1);

 /* Do binary search logic based on a sorted (decending) attribute vector */
  focusPos = (beginPos + endPos) / 2;
  beginAttrib = attributes[beginPos];
  focusAttrib = attributes[focusPos];
  endAttrib   = attributes[endPos];

  while(endPos - beginPos > LINEARSEARCH) {
    if(beginAttrib == target) {
      focusAttrib = beginAttrib;
      endPos = beginPos;
    }
    else if(endAttrib == target) {
      focusAttrib = endAttrib;
      beginPos = endPos;
    }
    else if(focusAttrib < target) {
      beginPos = focusPos + 1;
      beginAttrib = attributes[beginPos];
      focusPos = (beginPos + endPos) / 2;
      focusAttrib = attributes[focusPos];
    }
    else if(focusAttrib > target) {
      endPos = focusPos - 1;
      endAttrib = attributes[endPos];
      focusPos = (beginPos + endPos) / 2;
      focusAttrib = attributes[focusPos];
    }
    else {
      beginPos = focusPos;
      endPos = focusPos;
    }
  }

 /* Do linear (unsorted) search logic */
  if(endPos - beginPos <= LINEARSEARCH) {

    /* CPU intensive loop; provide alternative evaluation models */
#if defined DOFASTMATH
    /* Do fast pointer arithmetic */
    int *attptr = attributes + beginPos;
    while((beginPos < endPos) && ((*attptr) < target)) {
      beginPos++;
      attptr++;
    }
    focusAttrib = (*attptr);
#else
    /* Do traditional indexed access */
    focusAttrib = attributes[beginPos];
    while((beginPos < endPos) && (focusAttrib < target)) {
      beginPos++;
      focusAttrib = attributes[beginPos];
    }
#endif
  }

 /* Return the index if a match was found, or signal failure with a -1        */
  if(focusAttrib == target)             /* Found; return retrieval index      */
    return(beginPos);
  else if(focusAttrib > target)         /* Not found; last item               */
    return(-beginPos);
  else if(beginPos > offset+count-1)
    return(-(endPos+1));                /* Not found; end of list             */
  else
    return(-(beginPos+1));              /* Not found; intermediate point      */

}
int findIndexEx(void *target, void *attributes, int count, int offset, int recsize, findCompare_func findCompare, MYBOOL ascending)
{
  int  focusPos, beginPos, endPos, compare, order;
  void *focusAttrib, *beginAttrib, *endAttrib;

 /* Set starting and ending index offsets */
  beginPos = offset;
  endPos = beginPos + count - 1;
  if(endPos < beginPos)
    return(-1);
  order = (ascending ? -1 : 1);

 /* Do binary search logic based on a sorted attribute vector */
  focusPos = (beginPos + endPos) / 2;
  beginAttrib = CMP_ATTRIBUTES(beginPos);
  focusAttrib = CMP_ATTRIBUTES(focusPos);
  endAttrib   = CMP_ATTRIBUTES(endPos);

  compare = 0;
  while(endPos - beginPos > LINEARSEARCH) {
    if(findCompare(target, beginAttrib) == 0) {
      focusAttrib = beginAttrib;
      endPos = beginPos;
    }
    else if(findCompare(target, endAttrib) == 0) {
      focusAttrib = endAttrib;
      beginPos = endPos;
    }
    else {
      compare = findCompare(target, focusAttrib)*order;
      if(compare < 0) {
        beginPos = focusPos + 1;
        beginAttrib = CMP_ATTRIBUTES(beginPos);
        focusPos = (beginPos + endPos) / 2;
        focusAttrib = CMP_ATTRIBUTES(focusPos);
      }
      else if(compare > 0) {
        endPos = focusPos - 1;
        endAttrib = CMP_ATTRIBUTES(endPos);
        focusPos = (beginPos + endPos) / 2;
        focusAttrib = CMP_ATTRIBUTES(focusPos);
      }
      else {
        beginPos = focusPos;
        endPos = focusPos;
      }
    }
  }

 /* Do linear (unsorted) search logic */
  if(endPos - beginPos <= LINEARSEARCH) {

    /* Do traditional indexed access */
    focusAttrib = CMP_ATTRIBUTES(beginPos);
    if(beginPos == endPos)
      compare = findCompare(target, focusAttrib)*order;
    else
    while((beginPos < endPos) &&
          ((compare = findCompare(target, focusAttrib)*order) < 0)) {
      beginPos++;
      focusAttrib = CMP_ATTRIBUTES(beginPos);
    }
  }

 /* Return the index if a match was found, or signal failure with a -1        */
  if(compare == 0)                      /* Found; return retrieval index      */
    return(beginPos);
  else if(compare > 0)                  /* Not found; last item               */
    return(-beginPos);
  else if(beginPos > offset+count-1)
    return(-(endPos+1));                /* Not found; end of list             */
  else
    return(-(beginPos+1));              /* Not found; intermediate point      */

}

/* Simple sorting and searching comparison "operators" */
int CMP_CALLMODEL compareCHAR(const void *current, const void *candidate)
{
  return( CMP_COMPARE( *(char *) current, *(char *) candidate ) );
}
int CMP_CALLMODEL compareINT(const void *current, const void *candidate)
{
  return( CMP_COMPARE( *(int *) current, *(int *) candidate ) );
}
int CMP_CALLMODEL compareREAL(const void *current, const void *candidate)
{
  return( CMP_COMPARE( *(REAL *) current, *(REAL *) candidate ) );
}

/* Heap sort function (procedurally based on the Numerical Recipes version,
   but expanded and generalized to hande any object with the use of
   qsort-style comparison operator).  An expanded version is also implemented,
   where interchanges are reflected in a caller-initialized integer "tags" list. */
void hpsort(void *attributes, int count, int offset, int recsize, MYBOOL descending, findCompare_func findCompare)
{
  register int  i, j, k, ir, order;
  register char *hold, *base;
  char          *save;

  if(count < 2)
    return;
  offset -= 1;
  attributes = CMP_ATTRIBUTES(offset);
  base = CMP_ATTRIBUTES(1);
  save = (char *) malloc(recsize);
  if(descending)
    order = -1;
  else
    order = 1;

  k = (count >> 1) + 1;
  ir = count;

  for(;;) {
    if(k > 1) {
      MEMCOPY(save, CMP_ATTRIBUTES(--k), recsize);
    }
    else {
      hold = CMP_ATTRIBUTES(ir);
      MEMCOPY(save, hold, recsize);
      MEMCOPY(hold, base, recsize);
      if(--ir == 1) {
        MEMCOPY(base, save, recsize);
        break;
      }
    }

    i = k;
    j = k << 1;
    while(j <= ir) {
      hold = CMP_ATTRIBUTES(j);
      if( (j < ir) && (findCompare(hold, CMP_ATTRIBUTES(j+1))*order < 0) ) {
        hold += recsize;
        j++;
      }
      if(findCompare(save, hold)*order < 0) {
        MEMCOPY(CMP_ATTRIBUTES(i), hold, recsize);
        i = j;
        j <<= 1;
	    }
      else
        break;
    }
    MEMCOPY(CMP_ATTRIBUTES(i), save, recsize);
  }

  FREE(save);
}
void hpsortex(void *attributes, int count, int offset, int recsize, MYBOOL descending, findCompare_func findCompare, int *tags)
{
  if(count < 2)
    return;
  if(tags == NULL) {
    hpsort(attributes, count, offset, recsize, descending, findCompare);
    return;
  }
  else {
    register int  i, j, k, ir, order;
    register char *hold, *base;
    char          *save;
    int           savetag;

    offset -= 1;
    attributes = CMP_ATTRIBUTES(offset);
    tags += offset;
    base = CMP_ATTRIBUTES(1);
    save = (char *) malloc(recsize);
    if(descending)
      order = -1;
    else
      order = 1;

    k = (count >> 1) + 1;
    ir = count;

    for(;;) {
      if(k > 1) {
        MEMCOPY(save, CMP_ATTRIBUTES(--k), recsize);
        savetag = tags[k];
      }
      else {
        hold = CMP_ATTRIBUTES(ir);
        MEMCOPY(save, hold, recsize);
        MEMCOPY(hold, base, recsize);
        savetag = tags[ir];
        tags[ir] = tags[1];
        if(--ir == 1) {
          MEMCOPY(base, save, recsize);
          tags[1] = savetag;
          break;
        }
      }

      i = k;
      j = k << 1;
      while(j <= ir) {
        hold = CMP_ATTRIBUTES(j);
        if( (j < ir) && (findCompare(hold, CMP_ATTRIBUTES(j+1))*order < 0) ) {
          hold += recsize;
          j++;
        }
        if(findCompare(save, hold)*order < 0) {
          MEMCOPY(CMP_ATTRIBUTES(i), hold, recsize);
          tags[i] = tags[j];
          i = j;
          j <<= 1;
  	    }
        else
          break;
      }
      MEMCOPY(CMP_ATTRIBUTES(i), save, recsize);
      tags[i] = savetag;
    }

    FREE(save);
  }
}

/* This is a "specialized generic" version of C.A.R Hoare's Quick Sort algorithm.
   It will handle arrays that are already sorted, and arrays with duplicate keys.
   There are two versions here; one extended conventional with optional tag data
   for each sortable value, and a version for the QSORTrec format.  The QSORTrec
   format i.a. includes the ability for to do linked list sorting. If the passed
   comparison operator is NULL, the comparison is assumed to be for integers. */
#define QS_IS_switch LINEARSEARCH    /* Threshold for switching to insertion sort */

void qsortex_swap(void *attributes, int l, int r, int recsize,
                         void *tags, int tagsize, char *save, char *savetag)
{
   MEMCOPY(save, CMP_ATTRIBUTES(l), recsize);
   MEMCOPY(CMP_ATTRIBUTES(l), CMP_ATTRIBUTES(r), recsize);
   MEMCOPY(CMP_ATTRIBUTES(r), save, recsize);
   if(tags != NULL) {
     MEMCOPY(savetag, CMP_TAGS(l), tagsize);
     MEMCOPY(CMP_TAGS(l), CMP_TAGS(r), tagsize);
     MEMCOPY(CMP_TAGS(r), savetag, tagsize);
   }
}

int qsortex_sort(void *attributes, int l, int r, int recsize, int sortorder, findCompare_func findCompare,
                        void *tags, int tagsize, char *save, char *savetag)
{
  register int i, j, nmove = 0;
  char     *v;

  /* Perform the a fast QuickSort */
  if((r-l) > QS_IS_switch) {
    i = (r+l)/2;

    /* Tri-Median Method */
    if(sortorder*findCompare(CMP_ATTRIBUTES(l), CMP_ATTRIBUTES(i)) > 0)
      { nmove++; qsortex_swap(attributes, l,i, recsize, tags, tagsize, save, savetag); }
    if(sortorder*findCompare(CMP_ATTRIBUTES(l), CMP_ATTRIBUTES(r)) > 0)
      { nmove++; qsortex_swap(attributes, l,r, recsize, tags, tagsize, save, savetag); }
    if(sortorder*findCompare(CMP_ATTRIBUTES(i), CMP_ATTRIBUTES(r)) > 0)
      { nmove++; qsortex_swap(attributes, i,r, recsize, tags, tagsize, save, savetag); }

    j = r-1;
    qsortex_swap(attributes, i,j, recsize, tags, tagsize, save, savetag);
    i = l;
    v = CMP_ATTRIBUTES(j);
    for(;;) {
      while(sortorder*findCompare(CMP_ATTRIBUTES(++i), v) < 0);
      while(sortorder*findCompare(CMP_ATTRIBUTES(--j), v) > 0);
      if(j < i) break;
      nmove++; qsortex_swap(attributes, i,j, recsize, tags, tagsize, save, savetag);
    }
    nmove++; qsortex_swap(attributes, i,r-1, recsize, tags, tagsize, save, savetag);
    nmove += qsortex_sort(attributes, l,j,   recsize, sortorder, findCompare, tags, tagsize, save, savetag);
    nmove += qsortex_sort(attributes, i+1,r, recsize, sortorder, findCompare, tags, tagsize, save, savetag);
  }
  return( nmove );
}

int qsortex_finish(void *attributes, int lo0, int hi0, int recsize, int sortorder, findCompare_func findCompare,
                          void *tags, int tagsize, char *save, char *savetag)
{
  int i, j, nmove = 0;

  /* This is actually InsertionSort, which is faster for local sorts */
  for(i = lo0+1; i <= hi0; i++) {

    /* Save bottom-most item */
    MEMCOPY(save, CMP_ATTRIBUTES(i), recsize);
    if(tags != NULL)
      MEMCOPY(savetag, CMP_TAGS(i), tagsize);

    /* Shift down! */
    j = i;
    while ((j > lo0) && (sortorder*findCompare(CMP_ATTRIBUTES(j-1), save) > 0)) {
      MEMCOPY(CMP_ATTRIBUTES(j), CMP_ATTRIBUTES(j-1), recsize);
      if(tags != NULL)
        MEMCOPY(CMP_TAGS(j), CMP_TAGS(j-1), tagsize);
      j--;
      nmove++;
    }

    /* Store bottom-most item at the top */
    MEMCOPY(CMP_ATTRIBUTES(j), save, recsize);
    if(tags != NULL)
      MEMCOPY(CMP_TAGS(j), savetag, tagsize);
  }
  return( nmove );
}

int qsortex(void *attributes, int count, int offset, int recsize, MYBOOL descending, findCompare_func findCompare, void *tags, int tagsize)
{
  int  iswaps = 0, sortorder = (descending ? -1 : 1);
  char *save = NULL, *savetag = NULL;

  /* Check and initialize to zero-based arrays */
  if(count <= 1)
    goto Finish;
  attributes = (void *) CMP_ATTRIBUTES(offset);
  save = (char *) malloc(recsize);
  if((tagsize <= 0) && (tags != NULL))
    tags = NULL;
  else if(tags != NULL) {
    tags = (void *) CMP_TAGS(offset);
    savetag = (char *) malloc(tagsize);
  }
  count--;

  /* Perform sort */
  iswaps = qsortex_sort(attributes, 0, count, recsize, sortorder, findCompare, tags, tagsize, save, savetag);
#if QS_IS_switch > 0
  iswaps += qsortex_finish(attributes, 0, count, recsize, sortorder, findCompare, tags, tagsize, save, savetag);
#endif

Finish:
  FREE(save);
  FREE(savetag);
  return( iswaps );
}

#undef QS_IS_switch

/* This is a "specialized generic" version of C.A.R Hoare's Quick Sort algorithm.
   It will handle arrays that are already sorted, and arrays with duplicate keys.
   The implementation here requires the user to pass a comparison operator and
   assumes that the array passed has the QSORTrec format, which i.a. includes
   the ability for to do linked list sorting. If the passed comparison operator
   is NULL, the comparison is assumed to be for integers. */
#define QS_IS_switch 4    /* Threshold for switching to insertion sort */

void QS_swap(UNIONTYPE QSORTrec a[], int i, int j)
{
  UNIONTYPE QSORTrec T = a[i];
  a[i] = a[j];
  a[j] = T;
}
int QS_addfirst(UNIONTYPE QSORTrec a[], void *mydata)
{
  a[0].pvoid2.ptr = mydata;
  return( 0 );
}
int QS_append(UNIONTYPE QSORTrec a[], int ipos, void *mydata)
{
  if(ipos <= 0)
    ipos = QS_addfirst(a, mydata);
  else
    a[ipos].pvoid2.ptr = mydata;
  return( ipos );
}
void QS_replace(UNIONTYPE QSORTrec a[], int ipos, void *mydata)
{
  a[ipos].pvoid2.ptr = mydata;
}
void QS_insert(UNIONTYPE QSORTrec a[], int ipos, void *mydata, int epos)
{
  for(; epos > ipos; epos--)
    a[epos] = a[epos-1];
  a[ipos].pvoid2.ptr = mydata;
}
void QS_delete(UNIONTYPE QSORTrec a[], int ipos, int epos)
{
  for(; epos > ipos; epos--)
    a[epos] = a[epos-1];
}
int QS_sort(UNIONTYPE QSORTrec a[], int l, int r, findCompare_func findCompare)
{
  register int i, j, nmove = 0;
  UNIONTYPE QSORTrec v;

  /* Perform the a fast QuickSort */
  if((r-l) > QS_IS_switch) {
    i = (r+l)/2;

    /* Tri-Median Method */
    if(findCompare((char *) &a[l], (char *) &a[i]) > 0)
      { nmove++; QS_swap(a,l,i); }
    if(findCompare((char *) &a[l], (char *) &a[r]) > 0)
      { nmove++; QS_swap(a,l,r); }
    if(findCompare((char *) &a[i], (char *) &a[r]) > 0)
      { nmove++; QS_swap(a,i,r); }

    j = r-1;
    QS_swap(a,i,j);
    i = l;
    v = a[j];
    for(;;) {
      while(findCompare((char *) &a[++i], (char *) &v) < 0);
      while(findCompare((char *) &a[--j], (char *) &v) > 0);
      if(j < i) break;
      nmove++; QS_swap (a,i,j);
    }
    nmove++; QS_swap(a,i,r-1);
    nmove += QS_sort(a,l,j,findCompare);
    nmove += QS_sort(a,i+1,r,findCompare);
  }
  return( nmove );
}
int QS_finish(UNIONTYPE QSORTrec a[], int lo0, int hi0, findCompare_func findCompare)
{
  int      i, j, nmove = 0;
  UNIONTYPE QSORTrec v;

  /* This is actually InsertionSort, which is faster for local sorts */
  for(i = lo0+1; i <= hi0; i++) {

    /* Save bottom-most item */
    v = a[i];

    /* Shift down! */
    j = i;
    while ((j > lo0) && (findCompare((char *) &a[j-1], (char *) &v) > 0)) {
      a[j] = a[j-1];
      j--;
      nmove++;
    }

    /* Store bottom-most item at the top */
    a[j] = v;
  }
  return( nmove );
}
MYBOOL QS_execute(UNIONTYPE QSORTrec a[], int count, findCompare_func findCompare, int *nswaps)
{
  int iswaps = 0;

  /* Check and initialize */
  if(count <= 1)
    goto Finish;
  count--;

  /* Perform sort */
  iswaps = QS_sort(a, 0, count, findCompare);
#if QS_IS_switch > 0
  iswaps += QS_finish(a, 0, count, findCompare);
#endif

Finish:
  if(nswaps != NULL)
    *nswaps = iswaps;
  return( TRUE );
}



/* Simple specialized bubble/insertion sort functions */
int sortByREAL(int *item, REAL *weight, int size, int offset, MYBOOL unique)
{
  int i, ii, saveI;
  REAL saveW;

  for(i = 1; i < size; i++) {
    ii = i+offset-1;
    while ((ii >= offset) && (weight[ii] >= weight[ii+1])) {
      if(weight[ii] == weight[ii+1]) {
        if(unique)
          return(item[ii]);
      }
      else {
        saveI = item[ii];
        saveW = weight[ii];
        item[ii] = item[ii+1];
        weight[ii] = weight[ii+1];
        item[ii+1] = saveI;
        weight[ii+1] = saveW;
      }
      ii--;
    }
  }
  return(0);
}
int sortByINT(int *item, int *weight, int size, int offset, MYBOOL unique)
{
  int i, ii, saveI;
  int saveW;

  for(i = 1; i < size; i++) {
    ii = i+offset-1;
    while ((ii >= offset) && (weight[ii] >= weight[ii+1])) {
      if(weight[ii] == weight[ii+1]) {
        if(unique)
          return(item[ii]);
      }
      else {
        saveI = item[ii];
        saveW = weight[ii];
        item[ii] = item[ii+1];
        weight[ii] = weight[ii+1];
        item[ii+1] = saveI;
        weight[ii+1] = saveW;
      }
      ii--;
    }
  }
  return(0);
}
REAL sortREALByINT(REAL *item, int *weight, int size, int offset, MYBOOL unique)
{
  int  i, ii, saveW;
  REAL saveI;

  for(i = 1; i < size; i++) {
    ii = i+offset-1;
    while ((ii >= offset) && (weight[ii] >= weight[ii+1])) {
      if(weight[ii] == weight[ii+1]) {
        if(unique)
          return(item[ii]);
      }
      else {
        saveI = item[ii];
        saveW = weight[ii];
        item[ii] = item[ii+1];
        weight[ii] = weight[ii+1];
        item[ii+1] = saveI;
        weight[ii+1] = saveW;
      }
      ii--;
    }
  }
  return(0);
}


/* Time and message functions */
double timeNow(void)
{
#ifdef INTEGERTIME
  return((double)time(NULL));
#elif defined CLOCKTIME
  return((double)clock()/CLOCKS_PER_SEC /* CLK_TCK */);
#elif defined PosixTime
  struct timespec t;
# if 0
  clock_gettime(CLOCK_REALTIME, &t);
  return( (double) t.tv_sec + (double) t.tv_nsec/1.0e9 );
# else
  static double   timeBase;

  clock_gettime(CLOCK_MONOTONIC, &t);
  if(timeBase == 0)
    timeBase = clockNow() - ((double) t.tv_sec + (double) t.tv_nsec/1.0e9);
  return( timeBase + (double) t.tv_sec + (double) t.tv_nsec/1.0e9 );
# endif
#elif defined EnhTime
  static LARGE_INTEGER freq;
  static double        timeBase;
  LARGE_INTEGER        now;

  QueryPerformanceCounter(&now);
  if(timeBase == 0) {
    QueryPerformanceFrequency(&freq);
    timeBase = clockNow() - (double) now.QuadPart/(double) freq.QuadPart;
  }
  return( timeBase + (double) now.QuadPart/(double) freq.QuadPart );
#else
  struct timeb buf;

  ftime(&buf);
  return((double)buf.time+((double) buf.millitm)/1000.0);
#endif
}


/* Miscellaneous reporting functions */

/* List a vector of INT values for the given index range */
void blockWriteINT(FILE *output, char *label, int *myvector, int first, int last)
{
  int i, k = 0;

  fprintf(output, "%s", label);
  fprintf(output, "\n");
  for(i = first; i <= last; i++) {
    fprintf(output, " %5d", myvector[i]);
    k++;
    if(k % 12 == 0) {
      fprintf(output, "\n");
      k = 0;
    }
  }
  if(k % 12 != 0)
    fprintf(output, "\n");
}

/* List a vector of MYBOOL values for the given index range */
void blockWriteBOOL(FILE *output, char *label, MYBOOL *myvector, int first, int last, MYBOOL asRaw)
{
  int i, k = 0;

  fprintf(output, "%s", label);
  fprintf(output, "\n");
  for(i = first; i <= last; i++) {
    if(asRaw)
      fprintf(output, " %1d", myvector[i]);
    else
      fprintf(output, " %5s", my_boolstr(myvector[i]));
    k++;
    if(k % 36 == 0) {
      fprintf(output, "\n");
      k = 0;
    }
  }
  if(k % 36 != 0)
    fprintf(output, "\n");
}

/* List a vector of REAL values for the given index range */
void blockWriteREAL(FILE *output, char *label, REAL *myvector, int first, int last)
{
  int i, k = 0;

  fprintf(output, "%s", label);
  fprintf(output, "\n");
  for(i = first; i <= last; i++) {
    fprintf(output, " %18g", myvector[i]);
    k++;
    if(k % 4 == 0) {
      fprintf(output, "\n");
      k = 0;
    }
  }
  if(k % 4 != 0)
    fprintf(output, "\n");
}


/* CONSOLE vector and matrix printing routines */
void printvec( int n, REAL *x, int modulo )
{
  int i;

  if (modulo <= 0) modulo = 5;
  for (i = 1; i<=n; i++) {
    if(mod(i, modulo) == 1)
      printf("\n%2d:%12g", i, x[i]);
    else
      printf(" %2d:%12g", i, x[i]);
  }
  if(i % modulo != 0) printf("\n");
}


void printmatUT( int size, int n, REAL *U, int modulo)
{
   int i, ll;
   ll = 0;
   for(i = 1; i<=n; i++) {
     printvec(n-i+1, &U[ll], modulo);
     ll += size-i+1;
   }
}


void printmatSQ( int size, int n, REAL *X, int modulo)
{
   int i, ll;
   ll = 0;
   for(i = 1; i<=n; i++) {
     printvec(n, &X[ll], modulo);
     ll += size;
   }
}

/* Miscellaneous file functions */
#if defined _MSC_VER
/* Check MS versions before 7 */
#if _MSC_VER < 1300
# define intptr_t long
#endif

int fileCount( char *filemask )
{
  struct   _finddata_t c_file;
  intptr_t hFile;
  int      count = 0;

  /* Find first .c file in current directory */
  if( (hFile = _findfirst( filemask, &c_file )) == -1L )
    ;
  /* Iterate over all matching names */
  else {
     while( _findnext( hFile, &c_file ) == 0 )
       count++;
    _findclose( hFile );
  }
  return( count );
}
MYBOOL fileSearchPath( char *envvar, char *searchfile, char *foundpath )
{
   char pathbuffer[_MAX_PATH];

   _searchenv( searchfile, envvar, pathbuffer );
   if(pathbuffer[0] == '\0')
     return( FALSE );
   else {
     if(foundpath != NULL)
       strcpy(foundpath, pathbuffer);
     return( TRUE );
   }
}
#endif