1 /*
2 Authored by abakh <abakh@tuta.io>
3 To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
4
5 You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
6
7
8 */
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <limits.h>
13 #include <stdbool.h>
14 #include <unistd.h>
15 #include "config.h"
16 #define FOPEN_FAIL -10
17
18 FILE* score_file;
score_write(const char * path,long wscore,byte save_to_num)19 byte score_write(const char* path, long wscore, byte save_to_num){// only saves the top 10, returns the place in the chart
20 score_file=fopen(path,"r");
21 if(!score_file){
22 score_file=fopen(path,"w");
23 if(!score_file){
24 return FOPEN_FAIL;
25 }
26 }
27
28 char name_buff[save_to_num][60];
29 long score_buff[save_to_num];
30
31 memset(name_buff,0,save_to_num*60*sizeof(char) );
32 memset(score_buff,0,save_to_num*sizeof(long) );
33
34 long scanned_score =0;
35 char scanned_name[60]={0};
36 byte location=0;
37
38 while( fscanf(score_file,"%59s : %ld\n",scanned_name,&scanned_score) == 2 && location<save_to_num){
39 strcpy(name_buff[location],scanned_name);
40 score_buff[location] = scanned_score;
41 ++location;//so it doesn't save more scores than intented
42
43 memset(scanned_name,0,60);
44 scanned_score=0;
45 }
46 score_file = fopen(path,"w+") ;//will get rid of the previous text
47 if(!score_file){
48 return FOPEN_FAIL;
49 }
50 byte scores_count=location;//if 5 scores were scanned, it is 5. the number of scores it reached
51 byte ret = -1;
52 bool wrote_it=0;
53
54 for(byte i=0;i<=scores_count && i<save_to_num-wrote_it;++i){
55 if(!wrote_it && (i>=scores_count || wscore>=score_buff[i]) ){
56 fprintf(score_file,"%s : %ld\n",getenv("USER"),wscore);
57 ret=i;
58 wrote_it=1;
59 }
60 if(i<save_to_num-wrote_it && i<scores_count){
61 fprintf(score_file,"%s : %ld\n",name_buff[i],score_buff[i]);
62 }
63 }
64 fflush(score_file);
65 return ret;
66 }
67
fallback_to_home(const char * name,long wscore,byte save_to_num)68 byte fallback_to_home(const char* name,long wscore,byte save_to_num){// only saves the top 10, returns the place in the chart
69 byte ret;
70 char full_path[1000]={0};
71 snprintf(full_path,1000,"%s/%s",SCORES_DIR,name);
72 ret=score_write(full_path,wscore,save_to_num);
73 if(ret==FOPEN_FAIL){
74 snprintf(full_path,1000,"%s/.%s",getenv("HOME"),name);
75 ret=score_write(full_path,wscore,save_to_num);
76 }
77 return ret;
78 }
79
80