JAL-3141 Fixed what happens when suffix template has no '%n' index
[jalview.git] / src / jalview / io / BackupFilenameParts.java
1 package jalview.io;
2
3 import java.io.File;
4
5 public class BackupFilenameParts
6 {
7   String base;
8
9   String templateStart;
10
11   int num;
12
13   int digits;
14
15   String templateEnd;
16
17   boolean isBackupFile;
18
19   public BackupFilenameParts(File file, String base, String template, int digits)
20   {
21     this(file.getName(), base, template, digits);
22   }
23
24   public BackupFilenameParts(String filename, String base, String template,
25           int suggesteddigits)
26   {
27     this.isBackupFile = false;
28
29     int numcharstart = template.indexOf(BackupFiles.NUM_PLACEHOLDER);
30     int digits = 0;
31     String templateStart = template;
32     String templateEnd = "";
33     if (numcharstart > -1)
34     {
35       templateStart = template.substring(0, numcharstart);
36       templateEnd = template.substring(
37               numcharstart + BackupFiles.NUM_PLACEHOLDER.length());
38       digits = suggesteddigits;
39     }
40     
41     // calculate minimum length of a backup filename
42     int minlength = base.length() + template.length()
43             - BackupFiles.NUM_PLACEHOLDER.length() + digits ;
44
45     if (!(filename.startsWith(base) && filename.length() >= minlength))
46     {
47       // non-starter
48       return;
49     }
50
51     int startLength = base.length() + templateStart.length();
52     int endLength = templateEnd.length();
53     String numString = numcharstart > -1?filename.substring(startLength,
54             filename.length() - endLength):"";
55
56     if (filename.length() >= startLength + digits + endLength
57             && filename.startsWith(base + templateStart)
58             && filename.endsWith(templateEnd)
59             && numString.matches("[0-9]*"))
60     {
61       this.base = base;
62       this.templateStart = templateStart;
63       this.num = numString.length() > 0?Integer.parseInt(numString):0;
64       this.digits = digits;
65       this.templateEnd = templateEnd;
66       this.isBackupFile = true;
67     }
68     
69   }
70
71   public boolean isBackupFile()
72   {
73     return this.isBackupFile;
74   }
75
76   public int indexNum()
77   {
78     return this.num;
79   }
80 }