some readme and general cleanups
[picodrive.git] / tools / gcda.c
CommitLineData
b542be46 1#include <stdio.h>
2//#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5
6
7static int search_gcda(const char *str, int len)
8{
9 int i;
10 for (i = 0; i < len - 6; i++)
11 if (str[i] == '.' && str[i+1] == 'g' && str[i+2] == 'c' &&
12 str[i+3] == 'd' && str[i+4] == 'a' && str[i+5] == 0)
13 return i;
14 return -1;
15}
16
17static int is_good_char(char c)
18{
19 return c >= ' ' && c < 0x7f;
20}
21
22static int is_good_path(char *path)
23{
24 int len = strlen(path);
25
26 path[len-2] = 'n';
27 path[len-1] = 'o';
28
29 FILE *f = fopen(path, "rb");
30
31 path[len-2] = 'd';
32 path[len-1] = 'a';
33
34 if (f) {
35 fclose(f);
36 return 1;
37 }
110df09c 38 printf("not good path: %s\n", path);
b542be46 39 return 0;
40}
41
42int main(int argc, char *argv[])
43{
44 char buff[1024], *p;
45 char cwd[4096];
46 FILE *f;
47 int l, pos, pos1, old_len, cwd_len;
48
49 if (argc != 2) return 1;
50
51 getcwd(cwd, sizeof(cwd));
52 cwd_len = strlen(cwd);
53 if (cwd[cwd_len-1] != '/') {
54 cwd[cwd_len++] = '/';
55 cwd[cwd_len] = 0;
56 }
57
58 f = fopen(argv[1], "rb+");
59 if (f == NULL) return 2;
60
61 while (1)
62 {
63readnext:
64 l = fread(buff, 1, sizeof(buff), f);
65 if (l <= 16) break;
66
67 pos = 0;
68 while (pos < l)
69 {
70 pos1 = search_gcda(buff + pos, l - pos);
71 if (pos1 < 0) {
110df09c 72 fseek(f, -6, SEEK_CUR);
b542be46 73 goto readnext;
74 }
75 pos += pos1;
76
77 while (pos > 0 && is_good_char(buff[pos-1])) pos--;
78
79 if (pos == 0) {
110df09c 80 fseek(f, -(sizeof(buff) + 16), SEEK_CUR);
b542be46 81 goto readnext;
82 }
83
84 // paths must start with /
85 while (pos < l && buff[pos] != '/') pos++;
86 p = buff + pos;
87 old_len = strlen(p);
88
89 if (!is_good_path(p)) {
90 pos += old_len;
91 continue;
92 }
93
94 if (strncmp(p, cwd, cwd_len) != 0) {
95 printf("can't handle: %s\n", p);
96 pos += old_len;
97 continue;
98 }
99
100 memmove(p, p + cwd_len, old_len - cwd_len + 1);
101 fseek(f, -(sizeof(buff) - pos), SEEK_CUR);
102 fwrite(p, 1, old_len, f);
103 goto readnext;
104 }
105 }
106
107 fclose(f);
108
109 return 0;
110}
111