+#endif
+
+/* check whether the value t is in a given range.
+ examples: 3 is in range 1-10: true
+ 7 is in range 2-4,6,8-10: false
+ 9 is in range 1,2,3-12: true
+*/
+static char is_in_range(int t, char*irange)
+{
+ char*pos = irange;
+ char*digits;
+ int num;
+ char range = 0;
+ int last=0;
+ char tmp;
+
+ if(!irange) // no range resembles (-OO,OO)
+ return 1;
+
+ while(*pos)
+ {
+ while(*pos == ' ' || *pos == '\r' || *pos == '\n' || *pos == '\t')
+ pos++;
+
+ digits = pos;
+ while(*digits>='0' && *digits<='9')
+ digits++;
+ if(digits == pos) {
+ fprintf(stderr, "Error: \"%s\" is not a valid format (digit expected)\n",irange);
+ exit(1);
+ }
+
+ tmp=*digits;*digits=0;
+ num = atoi(pos);
+ *digits=tmp;
+ pos = digits;
+
+ while(*pos == ' ' || *pos == '\r' || *pos == '\n' || *pos == '\t')
+ pos++;
+
+ if(range && last<=t && num>=t)
+ return 1;
+ if(range) {
+ range = 0;
+ if(*pos)
+ pos ++;
+ continue;
+ }
+
+ if(*pos=='-')
+ {
+ if(range) {
+ fprintf(stderr, "Error: \"%s\" is not a valid format (too many '-'s)\n",irange);
+ exit(1);
+ }
+ last = num;
+ range = 1;
+ if(*pos)
+ pos ++;
+ continue;
+ }
+ else
+ {
+ /* if it isn't a '-', we assume it is a seperator like
+ ',', ';', ':', whatever. */
+ if(t == num)
+ return 1;
+ if(*pos)
+ pos ++;
+ continue;
+ }
+ }
+ if(range && last<=t)
+ return 1;
+ return 0;
+}
+
+static char* filename2template(char*filename, int*startindex)
+{
+ int l = strlen(filename);
+ char*newname = (char*)malloc(l+5);
+ /* first look whether the file is already numbered */
+ while(1) {
+ l--;
+ if(l<0 || strchr("0123456789", filename[l]))
+ break;
+ };
+ if(l>=0) {
+ int lastdigit=l;
+ int firstdigit=l;
+ while(firstdigit && strchr("0123456789", filename[firstdigit-1]))
+ firstdigit--;
+ *startindex = atoi(filename+firstdigit);
+ memcpy(newname, filename, firstdigit);
+ sprintf(newname+firstdigit, "%%%dd", lastdigit+1-firstdigit);
+ strcat(newname+firstdigit, filename+lastdigit+1);
+ return newname;
+ }
+ /* if it isn't, try to paste a %d between filename and extension */
+ char*dot = strrchr(filename, '.');
+ if(dot) {
+ int pos = dot-filename;
+ memcpy(newname, filename, pos);
+ newname[pos++] = '.';
+ newname[pos++] = '%';
+ newname[pos++] = 'd';
+ strcpy(newname+pos, dot);
+ *startindex = 1;
+ return newname;
+ }
+ /* if that didn't work either, just append the number at the end */
+ strcpy(newname, filename);
+ strcat(newname, ".%d");
+ *startindex = 1;
+ return newname;
+}
+