+static gboolean check_file_first_line(FILE* f, gchar *patterns[])
+{
+ gchar **s;
+ gchar *bp;
+ fpos_t pos;
+ gchar buf[33];
+ size_t nr;
+
+ memset(buf, 0, sizeof(buf));
+ fgetpos(f, &pos);
+ rewind(f);
+ nr = fread(buf, 1, sizeof(buf) - 1, f);
+ fsetpos(f, &pos);
+ for (bp = buf; (bp < (buf + sizeof(buf) - 1)) && (nr > (bp - buf)); bp++) {
+ if (!(isspace(*bp)))
+ break;
+ }
+ if ((bp >= (buf + sizeof(buf) -1)) || ((bp - buf) >= nr))
+ return FALSE;
+ for (s = patterns; *s; s++) {
+ if (strncasecmp(*s, bp, strlen(*s)) == 0)
+ return TRUE;
+ }
+ return FALSE;
+}
+
+gboolean a_check_html_file(FILE* f)
+{
+ gchar * html_str[] = {
+ "<html",
+ "<!DOCTYPE html",
+ "<head",
+ "<title",
+ NULL
+ };
+
+ return check_file_first_line(f, html_str);
+}
+
+gboolean a_check_map_file(FILE* f)
+{
+ /* FIXME no more true since a_check_kml_file */
+ return !a_check_html_file(f);
+}
+
+gboolean a_check_kml_file(FILE* f)
+{
+ gchar * kml_str[] = {
+ "<?xml",
+ NULL
+ };
+
+ return check_file_first_line(f, kml_str);
+}
+
+static GList *file_list = NULL;
+static GMutex *file_list_mutex = NULL;
+
+/* spin button scales */
+static VikLayerParamScale params_scales[] = {
+ {1, 365, 1, 0}, /* download_tile_age */
+};
+
+static VikLayerParamData convert_to_display ( VikLayerParamData value )
+{
+ // From seconds into days
+ return VIK_LPD_UINT ( value.u / 86400 );
+}
+
+static VikLayerParamData convert_to_internal ( VikLayerParamData value )
+{
+ // From days into seconds
+ return VIK_LPD_UINT ( 86400 * value.u );
+}
+
+static VikLayerParam prefs[] = {
+ { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_NAMESPACE "download_tile_age", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, N_("Tile age (days):"), VIK_LAYER_WIDGET_SPINBUTTON, ¶ms_scales[0], NULL, NULL, NULL, convert_to_display, convert_to_internal },
+};
+
+void a_download_init (void)
+{
+ VikLayerParamData tmp;
+ tmp.u = VIK_CONFIG_DEFAULT_TILE_AGE / 86400; // Now in days
+ a_preferences_register(prefs, tmp, VIKING_PREFERENCES_GROUP_KEY);
+
+ file_list_mutex = g_mutex_new();
+}
+
+static gboolean lock_file(const char *fn)
+{
+ gboolean locked = FALSE;
+ g_mutex_lock(file_list_mutex);
+ if (g_list_find_custom(file_list, fn, (GCompareFunc)g_strcmp0) == NULL)
+ {
+ // The filename is not yet locked
+ file_list = g_list_append(file_list, (gpointer)fn),
+ locked = TRUE;
+ }
+ g_mutex_unlock(file_list_mutex);
+ return locked;
+}
+
+static void unlock_file(const char *fn)
+{
+ g_mutex_lock(file_list_mutex);
+ file_list = g_list_remove(file_list, (gconstpointer)fn);
+ g_mutex_unlock(file_list_mutex);
+}