Make gtk build conditional
[jelmer/at89prog.git] / hexfile.c
1 /* 
2         at89prog
3         (c) 2003-2004 Jelmer Vernooij <jelmer@samba.org>
4
5         This program is free software; you can redistribute it and/or modify
6         it under the terms of the GNU General Public License as published by
7         the Free Software Foundation; either version 2 of the License, or
8         (at your option) any later version.
9
10         This program is distributed in the hope that it will be useful,
11         but WITHOUT ANY WARRANTY; without even the implied warranty of
12         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13         GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to the Free Software
17         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <string.h>
23 #include <sys/io.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include "pins.h"
27 #include "at89ser.h"
28 #include "delays.h"
29 #include "hexfile.h"
30
31 int readhexline(FILE *fd, void **data, size_t *len, long *address)
32 {
33         int checksum1, checksum2;
34         int length, addr1, addr2, type;
35         int j, byte;
36
37         do { 
38                 checksum1 = 0;
39                 if(feof(fd)) {
40                         return HEX_FILE_END_OF_FILE;
41                 }
42
43                 if(fscanf(fd, ":%2x%2x%2x%2x", &length, &addr1, &addr2, &type) < 3) {
44                         return HEX_FILE_CORRUPT_LINE;
45                 }
46         } while(type == 1 || type == 2);
47
48         checksum1+=length;
49         checksum1+=type;
50         checksum1+=addr1;
51         checksum1+=addr2;
52
53         *address = addr1 * 0x100 + addr2;
54
55         *data = malloc(length);
56         *len = length;
57
58         for(j = 0; j < length; j++) {
59                 if(fscanf(fd, "%2x", &byte) < 1) {
60                         return HEX_FILE_CORRUPT_LINE;
61                 }
62
63                 checksum1+=byte;
64                 ((char *)(*data))[j] = byte;
65         }
66
67         if(fscanf(fd, "%2x", &checksum2) < 1) {
68                 return HEX_FILE_CORRUPT_LINE;
69         }
70
71         checksum1 &= 0xFF;
72         checksum1 = (~checksum1 + 1) & 0xFF;
73
74         if(checksum1 != checksum2) {
75                 return HEX_FILE_ERR_CHECKSUM;
76         }
77
78         /* Find the next newline so we're in position for the next read */
79         while(!feof(fd)) { 
80                 byte = getc(fd); 
81                 if(byte != '\n' && byte != '\r') {
82                         ungetc(byte, fd);
83                         break; 
84                 }
85         }
86         return 0;
87 }