1 /*
2     Copyright (C) 2016,2019 Alois Schloegl <alois.schloegl@gmail.com>
3     This file is part of the "BioSig for C/C++" repository
4     (biosig4c++/libbiosig) at http://biosig.sf.net/
5 
6     This program is free software; you can redistribute it and/or
7     modify it under the terms of the GNU General Public License
8     as published by the Free Software Foundation; either version 3
9     of the License, or (at your option) any later version.
10 
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15 
16     You should have received a copy of the GNU General Public License
17     along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 
19 References:
20     https://cran.r-project.org/doc/manuals/R-exts.html
21 
22  */
23 
24 #include <R.h>
25 #include <Rdefines.h>
26 #include <R_ext/Rdynload.h>
27 
28 #include <biosig.h>
29 
sload(SEXP filename,SEXP channels)30 SEXP sload(SEXP filename, SEXP channels) {
31 
32 	// sanity check of input
33 	if(!isString(filename) || length(filename) != 1)
34 		error("filename is not a single string");
35 
36 	// Open file
37 	HDRTYPE *hdr = sopen(CHAR(asChar(filename)), "r", NULL);
38 	if (serror2(hdr)) return R_NilValue;
39 
40 	long NS = biosig_get_number_of_channels(hdr);
41 	size_t SPR = biosig_get_number_of_samples(hdr);
42 
43 	// allocate memory for results
44 	SEXP result = PROTECT(allocMatrix(REALSXP, SPR, NS));
45 
46 	// read data from file and write into result
47 	int status = sread(REAL(result), 0, SPR, hdr);
48 	if (serror2(hdr)) {
49 		destructHDR(hdr);
50 		Free(result);
51 		UNPROTECT(1);
52 		return R_NilValue;
53 	}
54 
55 	// close file, and cleanup memory to avoid any leaks
56 	destructHDR(hdr);
57 	UNPROTECT(1);
58 	return result;
59 }
60 
jsonHeader(SEXP filename)61 SEXP jsonHeader (SEXP filename) {
62 	// sanity check of input
63 	if(!isString(filename) || length(filename) != 1)
64 		error("filename is not a single string");
65 
66 	// Open file
67 	HDRTYPE *hdr = sopen(CHAR(asChar(filename)), "r", NULL);
68 	if (serror2(hdr)) return R_NilValue;
69 
70 	// convert header to json-string
71 	SEXP result    = R_NilValue;
72 	char *str      = NULL;
73 	asprintf_hdr2json(&str, hdr);
74 	if (str != NULL) {
75 		result = PROTECT(allocVector(STRSXP, strlen(str)+1));
76 		SET_STRING_ELT(result, 0, mkChar(str));
77 		free(str);
78 	}
79 
80 	// close file, and cleanup memory to avoid any leaks
81 	destructHDR(hdr);
82 	UNPROTECT(1);
83 	return result;
84 }
85