summaryrefslogtreecommitdiffstats
path: root/drivers/sound/hex2hex.h
blob: 05d12b1cf9fd09d292e0460deaca33666b72c294 (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
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
/*
 * This file is a part of configure.c
 *
 * hex2hex reads an input file in Intel HEX format and produces
 * an (unsigned char) array which contains the bytes and writes it to the
 * output file using C syntax
 */

#define MAX_SIZE (256*1024)
#define ABANDON(why) { \
		fprintf(stderr, "%s: " why "\n", source); \
		return 0; \
		}

int loadhex(FILE *inf, unsigned char *buf, char *source)
{
	int l=0, c, i;

	while ((c=getc(inf))!=EOF)
	{
		if (c == ':')	/* Sync with beginning of line */
		{
			int n, check;
			unsigned char sum;
			int addr;
			int linetype;

			if (fscanf(inf, "%02x", &n) != 1)
			   ABANDON("File format error");
			sum = n;

			if (fscanf(inf, "%04x", &addr) != 1)
			   ABANDON("File format error");
			sum += addr/256;
			sum += addr%256;

			if (fscanf(inf, "%02x", &linetype) != 1)
			   ABANDON("File format error");
			sum += linetype;

			if (linetype != 0)
			   continue;

			for (i=0;i<n;i++)
			{
				if (fscanf(inf, "%02x", &c) != 1)
			   	   ABANDON("File format error");
				if (addr >= MAX_SIZE)
				   ABANDON("File too large");
				buf[addr++] = c;
				if (addr > l)
				   l = addr;
				sum += c;
			}

			if (fscanf(inf, "%02x", &check) != 1)
			   ABANDON("File format error");

			sum = ~sum + 1;
			if (check != sum)
			   ABANDON("Line checksum error");
		}
	}

	return l;
}

int hex2hex(char *source, char *target, char *varline)
{
	FILE *inf, *outf;

	int i,l;
	unsigned char buf[MAX_SIZE];

	if ((inf=fopen(source, "r"))==NULL)
	{
		perror(source);
		return 0;
	}

	if ((outf=fopen(target, "w"))==NULL)
	{
		perror(target);
		fclose(inf);
		return 0;
	}

	l=loadhex(inf, buf, source);
	if (l<=0)
        {
           fclose(inf);
	   fclose(outf);
	   return l;
	}


	fprintf(outf, "/*\n *\t Computer generated file. Do not edit.\n */\n");
        fprintf(outf, "static int %s_len = %d;\n", varline, l);
	fprintf(outf, "static unsigned char %s[] = {\n", varline);

	for (i=0;i<l;i++)
	{
		if (i) fprintf(outf, ",");
		if (i && !(i % 16)) fprintf(outf, "\n");
		fprintf(outf, "0x%02x", buf[i]);
	}

	fprintf(outf, "\n};\n\n");
	fclose(inf);
	fclose(outf);
	return 1;
}