summaryrefslogtreecommitdiff
path: root/src/export/map_branches_v4.c
blob: 160945d8c66e4b1c16e9becec586956f3d176f89 (plain)
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
#define _WITH_GETLINE
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

typedef struct {
  long code;
  char *name;
} branchen_code;

enum { MAX_CODES = 128 * 1024 };
branchen_code g_codes[MAX_CODES];
long g_code_count;

static int find_code( const void *key, const void *bc)
{
  return (long)key - ((branchen_code*)bc)->code;
}

static int qsort_cmp( const void *a, const void *b )
{
  return ((branchen_code*)a)->code - ((branchen_code*)b)->code;
}

int main( int argc, char ** args )
{
  FILE * map_file;
  char *end_p, *input = malloc(1024);
  size_t input_length = 1024;
  ssize_t ll;

  if( argc != 2 ) { fprintf( stderr, "Syntax: %s <branchcodes> < <branches_files>\n", args[0] ); exit(111); }

  map_file = fopen( args[1], "r" );
  if (!map_file || !input) { fprintf( stderr, "Error allocating resources\n" ); exit( 111 ); }

  /* Fill array with maps */
  while ( (ll = getline( &input, &input_length, map_file ) ) >= 0 ) {
    char * r = strchr(input, 10);
    if (r) *r = 0;
    g_codes[g_code_count].code = strtoul(input, &end_p, 10);
    asprintf(&g_codes[g_code_count].name, "%s", end_p + 1) ;
    // printf( "%ld: %s\n", g_codes[g_code_count].code, g_codes[g_code_count].name);
    g_code_count++;
  }

  qsort(g_codes, g_code_count, sizeof(branchen_code), qsort_cmp );

  /* Now scan lines from 09_Verweise for semicolon separated branchen codes */
  while ( (ll = getline( &input, &input_length, stdin ) ) >= 0 ) {
    char *codes = input;
    branchen_code *bc;
    int multiple;
    for (multiple = 0;; ++multiple) {
      long code = strtoul(codes, &end_p, 10);
      if (codes == end_p) break;
      bc = (branchen_code*)bsearch((void *)(uintptr_t)code, g_codes, g_code_count, sizeof(branchen_code), find_code);
      if (bc) {
        if (multiple) putchar(';');
        printf("%s", bc->name);
      }
      if (*end_p != ';') break;
      codes = end_p + 1;
    }
    putchar(10);
  }
  return 0;
}