Ian Jauslin
summaryrefslogtreecommitdiff
path: root/src/io.c
blob: 94816f94261c728849bf3427f0797333ce203d36 (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
113
114
115
#include <stdbool.h>
#include <stdlib.h>
#include "io.h"
#include "navier-stokes.h"

// write final entry to file
int write_u(_Complex double* u, int K1, int K2, FILE* file){
  int kx,ky;

  // do nothing if there is no file
  if(file==NULL){
    return 0;
  }

  for(kx=0;kx<=K1;kx++){
    for (ky=-K2;ky<=K2;ky++){
      fprintf(file,"% 3d % 3d % .15e % .15e\n",kx,ky,__real__ u[klookup_sym(kx,ky,K2)],__imag__ u[klookup_sym(kx,ky,K2)]);
    }
  }

  return 0;
}

// read u from file
int read_u(_Complex double* u, int K1, int K2, FILE* file){
  int kx,ky;
  double r,i;
  char* line;
  unsigned int len=256;
  unsigned int pos=0;
  char* line_realloc;
  char c;
  int ret;
  unsigned int counter=0;
  bool commented=false;

  // error if there is no file (this should not happen)
  if (file==NULL){
    fprintf(stderr,"error reading u from file (this is a bug!)\n");
    return -1;
  }

  // allocate line buffer
  line=calloc(sizeof(char), len);

  while(1){
    c=fgetc(file);

    // end of file
    if (feof(file)){
      break;
    }

    // newline: read line and reset buffer
    if(c=='\n' || c=='\r'){
      // increment line counter
      counter++;

      // read entry
      // ignore empty lines
      if(pos>0){
	ret=sscanf(line, "%d %d %le %le", &kx, &ky, &r, &i);

	// errors
	if(ret!=4){
	  fprintf(stderr, "warning: line %d does not match the input format: '%s', skipping\n", counter, line);
	}
	else{
	  if(kx>K1 || kx<-K1 || ky>K2 || ky<-K2){
	    fprintf(stderr, "warning: reading line %d: kx or ky out of bounds: %d,%d, skipping\n", counter, kx, ky);
	  }
	  else if (kx<0){
	    fprintf(stderr, "warning: reading line %d: kx should be >=0, skipping\n", counter);
	  }
	  else{
	    // set u
	    u[klookup_sym(kx, ky, K2)]=r+i*I;
	  }
	}
      }

      // reset buffer
      pos=0;
      line[pos]='\0';
      commented=false;
    }
    // comment: stop reading
    else if (c=='#'){
      commented=true;
    }
    // add to buffer (unless we are in a comment)
    else if (!(commented)){
      // check that there is room in buffer
      if(pos==len){
	// too short: reallocate
	line_realloc=calloc(sizeof(char), 2*len);
	for(pos=0;pos<len;pos++){
	  line_realloc[pos]=line[pos];
	}
	free(line);
	line=line_realloc;
	len=2*len;
      }

      // add c to line
      line[pos]=c;
      pos++;
      line[pos]='\0';
    }
  }

  free(line);

  return 0;
}