#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
    FILE *fin, *fout;
    char s[1024], *addr, *sym, *c;
    int text = 0, len;
    long last = 0;

	if (argc < 3) {
		fprintf(stderr, "Usage: map2d input.map output.d\n");
		return -1;
	}

    if (!(fin = fopen(argv[1], "rt"))){
        fprintf(stderr, "Can't open '%s' for reading\n", argv[1]);
        return -1;
    }

    if (!(fout = fopen(argv[2], "wt"))){
        fclose(fin);
        fprintf(stderr, "Can't open '%s' for writing\n", argv[2]);
        return -1;
    }

    while (fgets(s, sizeof(s) - 1, fin) != NULL){
        len = strlen(s);
        if (len > 0 && s[len-1]=='\n') s[len-1] = '\0';
        len = strlen(s);
        if (len > 0 && s[len-1]=='\r') s[len-1] = '\0';
//        printf("s='%s'\n", s);
        //if (c[0] == ' ') c++;

        if (s[0] == '.'){
            text = strncmp(s, ".text", 5) == 0;
            if (text){
                strtok(s, " \r\n");
                addr = strtok(NULL, " \r\n");
                c = strtok(NULL, " \r\n");
    //            printf("text=%d\n", text);
                //printf("addr=%s c=%s\n", addr, c);
                last = strtol(addr, NULL, 16) + strtol(c, NULL, 16);
            }
        }
//        if (c[0] == '*') continue;

        if (!text) continue;
        if (strncmp(s, "      ", 6) != 0) continue;

        addr = strtok(s, " ");
        sym = strtok(NULL, " ");
        c = strtok(NULL, " ");
        if (c) continue;
        if (strncmp(addr, "0x", 2) == 0) addr += 2;
        while (addr[0] == '0') addr++;
        if (sym[0] == '_') sym++;
        fprintf(fout, "%s %s\n", addr, sym);
    }
    fprintf(fout, "%lx\n", last);
    fclose(fin);
    fclose(fout);
    return 0;
}
