Improve the highscore related functions in plugin lib (FS#10350)
[kugel-rb/myfork.git] / apps / plugins / lib / highscore.c
blobe8e1c883b07143a1c60c8599654d1bec99eb2a18
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Linus Nielsen Feltzing
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "plugin.h"
22 #include "highscore.h"
24 int highscore_save(char *filename, struct highscore *scores, int num_scores)
26 int i;
27 int fd;
28 int rc;
29 char buf[80];
31 fd = rb->open(filename, O_WRONLY|O_CREAT);
32 if(fd < 0)
33 return -1;
35 for(i = 0;i < num_scores;i++)
37 rb->snprintf(buf, sizeof(buf), "%d:%d:%s\n",
38 scores[i].score, scores[i].level, scores[i].name);
39 rc = rb->write(fd, buf, rb->strlen(buf));
40 if(rc < 0)
42 rb->close(fd);
43 return -2;
46 rb->close(fd);
47 return 0;
50 int highscore_load(char *filename, struct highscore *scores, int num_scores)
52 int i;
53 int fd;
54 char buf[80];
55 char *score, *level, *name;
57 rb->memset(scores, 0, sizeof(struct highscore)*num_scores);
59 fd = rb->open(filename, O_RDONLY);
60 if(fd < 0)
61 return -1;
63 i = 0;
64 while(rb->read_line(fd, buf, sizeof(buf)) > 0 && i < num_scores)
66 DEBUGF("%s\n", buf);
68 if ( !rb->settings_parseline(buf, &score, &level) )
69 continue;
70 if ( !rb->settings_parseline(level, &level, &name) )
71 continue;
73 scores[i].score = rb->atoi(score);
74 scores[i].level = rb->atoi(level);
75 rb->strncpy(scores[i].name, name, sizeof(scores[i].name)-1);
76 i++;
78 rb->close(fd);
79 return 0;
82 int highscore_update(int score, int level, const char *name,
83 struct highscore *scores, int num_scores)
85 int pos;
86 struct highscore *entry;
88 if (!highscore_would_update(score, scores, num_scores))
89 return -1;
91 pos = num_scores-1;
92 while (pos > 0 && score > scores[pos-1].score)
94 /* move down one */
95 rb->memcpy((void *)&scores[pos], (void *)&scores[pos-1],
96 sizeof(struct highscore));
97 pos--;
100 entry = scores + pos;
101 entry->score = score;
102 entry->level = level;
103 rb->strncpy(entry->name, name, sizeof(entry->name));
104 entry->name[sizeof(entry->name)-1] = '\0';
106 return pos;
109 bool highscore_would_update(int score, struct highscore *scores,
110 int num_scores)
112 return (num_scores > 0) && (score > scores[num_scores-1].score);