initial commit
[ansitris] / src / main.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <termios.h>
7 #include <sys/stat.h>
8 #include "game.h"
9
10 int init(void);
11 void cleanup(void);
12
13 const char *termfile = "/dev/tty";
14 struct termios saved_term;
15
16 int main(int argc, char **argv)
17 {
18         if(argc > 1) {
19                 termfile = argv[1];
20         }
21
22         if(init() == -1) {
23                 return 1;
24         }
25
26         for(;;) {
27                 proc_input();
28                 if(quit) break;
29         }
30
31         cleanup();
32         return 0;
33 }
34
35 int init(void)
36 {
37         int fd;
38         struct termios term;
39
40         if((fd = open(termfile, O_RDWR)) == -1) {
41                 fprintf(stderr, "failed to open terminal device: %s: %s\n", termfile, strerror(errno));
42                 return -1;
43         }
44
45         if(tcgetattr(fd, &term) == -1) {
46                 fprintf(stderr, "failed to get terminal attributes: %s\n", strerror(errno));
47                 return -1;
48         }
49         saved_term = term;
50         term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
51         term.c_oflag &= ~OPOST;
52         term.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
53         term.c_cflag = (term.c_cflag & ~(CSIZE | PARENB)) | CS8;
54
55         if(tcsetattr(fd, TCSAFLUSH, &term) == -1) {
56                 fprintf(stderr, "failed to change terminal attributes: %s\n", strerror(errno));
57                 return -1;
58         }
59
60         close(0);
61         close(1);
62         close(2);
63         dup(fd);
64         dup(fd);
65
66         umask(002);
67         open("ansitris.log", O_WRONLY | O_CREAT, 0664);
68
69
70         if(init_game() == -1) {
71                 return -1;
72         }
73
74         return 0;
75 }
76
77 void cleanup(void)
78 {
79         cleanup_game();
80         tcsetattr(0, TCSAFLUSH, &saved_term);
81 }