Index: applications/editors/josm/plugins/HouseNumberTaggingTool/src/org/openstreetmap/josm/plugins/housenumbertool/TagDialog.java
===================================================================
--- applications/editors/josm/plugins/HouseNumberTaggingTool/src/org/openstreetmap/josm/plugins/housenumbertool/TagDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/HouseNumberTaggingTool/src/org/openstreetmap/josm/plugins/housenumbertool/TagDialog.java	(revision 30738)
@@ -411,9 +411,10 @@
       try {
          path.mkdirs();
-
-         FileOutputStream file = new FileOutputStream(fileName);
-         ObjectOutputStream o = new ObjectOutputStream(file);
-         o.writeObject(dto);
-         o.close();
+         try (
+	         FileOutputStream file = new FileOutputStream(fileName);
+	         ObjectOutputStream o = new ObjectOutputStream(file)
+         ) {
+             o.writeObject(dto);
+         }
       } catch (Exception ex) {
          logger.log(Level.SEVERE, ex.getMessage());
@@ -534,34 +535,32 @@
    }
 
-   private Dto loadDto() {
-      Dto dto = new Dto();
-      File fileName = new File(pluginDir + TagDialog.TEMPLATE_DATA);
-
-      try {
-
-         if (fileName.exists()) {
-            FileInputStream file = new FileInputStream(fileName);
-            ObjectInputStream o = new ObjectInputStream(file);
-
-            dto = (Dto) o.readObject();
-            o.close();
-         } else {
-            dto.setCity(selection.get(TagDialog.TAG_ADDR_CITY));
-            dto.setCountry(selection.get(TagDialog.TAG_ADDR_COUNTRY));
-            dto.setHousenumber(selection.get(TagDialog.TAG_ADDR_HOUSENUMBER));
-            dto.setPostcode(selection.get(TagDialog.TAG_ADDR_POSTCODE));
-            dto.setStreet(selection.get(TagDialog.TAG_ADDR_STREET));
-            dto.setState(selection.get(TagDialog.TAG_ADDR_STATE));
-         }
-      } catch (Exception ex) {
+    private Dto loadDto() {
+        Dto dto = new Dto();
+        File fileName = new File(pluginDir + TagDialog.TEMPLATE_DATA);
+
+        try {
+            if (fileName.exists()) {
+                try (
+					FileInputStream file = new FileInputStream(fileName);
+					ObjectInputStream o = new ObjectInputStream(file);
+                ) {
+                	dto = (Dto) o.readObject();
+                }
+            } else {
+	            dto.setCity(selection.get(TagDialog.TAG_ADDR_CITY));
+	            dto.setCountry(selection.get(TagDialog.TAG_ADDR_COUNTRY));
+	            dto.setHousenumber(selection.get(TagDialog.TAG_ADDR_HOUSENUMBER));
+	            dto.setPostcode(selection.get(TagDialog.TAG_ADDR_POSTCODE));
+	            dto.setStreet(selection.get(TagDialog.TAG_ADDR_STREET));
+	            dto.setState(selection.get(TagDialog.TAG_ADDR_STATE));
+            }
+        } catch (Exception ex) {
             logger.log(Level.SEVERE, ex.getMessage());
             fileName.delete();
-      }
-      return dto;
-
-   }
-
-    class RadioChangeListener implements ItemListener
-    {
+        }
+        return dto;
+    }
+
+    class RadioChangeListener implements ItemListener {
 
          @Override
Index: applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java
===================================================================
--- applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java	(revision 30738)
@@ -95,7 +95,7 @@
             // add menu entries
             //Main.main.menu.fileMenu.insert(loadFileAction, 8);
-            
+
             //Main.main.menu.fileMenu.insertSeparator(9);
-            
+
             ExtensionFileFilter.importers.add(new ImportImageFileImporter());
 
@@ -129,6 +129,5 @@
 
         // if properties file doesn't exist, install plugin
-        if(!isInstalled)
-        {
+        if (!isInstalled) {
 
             /*----------- Begin installation ---------------*/
@@ -147,23 +146,21 @@
 
             // create local properties file
-            if(pluginProps == null || pluginProps.isEmpty()){
-
-                FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH));
-                URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
-                pluginProps = new Properties();
-                pluginProps.load(propertiesURL.openStream());
-                pluginProps.store(fw, null);
-                fw.close();
+            if (pluginProps == null || pluginProps.isEmpty()) {
+                try (FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH))) {
+	                URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
+	                pluginProps = new Properties();
+	                pluginProps.load(propertiesURL.openStream());
+	                pluginProps.store(fw, null);
+                }
                 logger.debug("Plugin properties loaded");
             }
 
-            if(!new File(LOGGING_PROPERTIES_FILEPATH).exists())
-            {
-                FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH));
-                URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
-                Properties loggingProps = new Properties();
-                loggingProps.load(propertiesURL.openStream());
-                loggingProps.store(fw, null);
-                fw.close();
+            if (!new File(LOGGING_PROPERTIES_FILEPATH).exists()) {
+                try (FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH))) {
+	                URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
+	                Properties loggingProps = new Properties();
+	                loggingProps.load(propertiesURL.openStream());
+	                loggingProps.store(fw, null);
+                }
                 logger.debug("Logging properties created");
             }
@@ -172,5 +169,4 @@
         }
     }
-
 
     /**
Index: applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java
===================================================================
--- applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java	(revision 30738)
@@ -31,4 +31,5 @@
 import org.opengis.referencing.NoSuchAuthorityCodeException;
 import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.openstreetmap.josm.Main;
 
 /**
@@ -36,11 +37,11 @@
  * - general and spatial information about the georeferenced image
  * - a possiblitly to change the source reference system of the image
- * 
- * 
+ *
+ *
  * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny
  *
  */
 public class LayerPropertiesDialog extends JFrame{
-    
+
     private Vector<String> supportedCRS;
     private ImageLayer imageLayer;
@@ -86,6 +87,6 @@
 
     /**
-     * This method initializes 
-     * 
+     * This method initializes
+     *
      */
     public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {
@@ -95,8 +96,8 @@
         initialize();
     }
-    
-    /**
-     * This method initializes 
-     * 
+
+    /**
+     * This method initializes
+     *
      */
     public LayerPropertiesDialog(Vector<String> supportedCRS) {
@@ -105,9 +106,9 @@
         initialize();
     }
-    
+
 
     /**
      * This method initializes this
-     * 
+     *
      */
     private void initialize() {
@@ -115,11 +116,11 @@
         this.setContentPane(getMainPanel());
         this.setPreferredSize(new Dimension(404, 485));
-            
-    }
-
-    /**
-     * This method initializes mainPanel    
-     *  
-     * @return javax.swing.JPanel   
+
+    }
+
+    /**
+     * This method initializes mainPanel
+     *
+     * @return javax.swing.JPanel
      */
     private JPanel getMainPanel() {
@@ -134,7 +135,7 @@
 
     /**
-     * This method initializes jPanel   
-     *  
-     * @return javax.swing.JPanel   
+     * This method initializes jPanel
+     *
+     * @return javax.swing.JPanel
      */
     private JPanel getJPanel() {
@@ -155,7 +156,7 @@
 
     /**
-     * This method initializes buttonPanel  
-     *  
-     * @return javax.swing.JPanel   
+     * This method initializes buttonPanel
+     *
+     * @return javax.swing.JPanel
      */
     private JPanel getButtonPanel() {
@@ -170,7 +171,7 @@
 
     /**
-     * This method initializes jTabbedPane  
-     *  
-     * @return javax.swing.JTabbedPane  
+     * This method initializes jTabbedPane
+     *
+     * @return javax.swing.JTabbedPane
      */
     private JTabbedPane getJTabbedPane() {
@@ -184,7 +185,7 @@
 
     /**
-     * This method initializes infoPanel    
-     *  
-     * @return javax.swing.JPanel   
+     * This method initializes infoPanel
+     *
+     * @return javax.swing.JPanel
      */
     private JPanel getInfoPanel() {
@@ -226,5 +227,5 @@
             crsValueLabel = new JLabel();
             crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));
-            
+
             String crsDescription = "";
             try {
@@ -233,5 +234,5 @@
             }
             crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");
-            
+
             crsLabel = new JLabel();
             crsLabel.setBounds(new Rectangle(15, 150, 118, 16));
@@ -281,7 +282,7 @@
 
     /**
-     * This method initializes crsPanel 
-     *  
-     * @return javax.swing.JPanel   
+     * This method initializes crsPanel
+     *
+     * @return javax.swing.JPanel
      */
     private JPanel getCrsPanel() {
@@ -295,5 +296,5 @@
             }
             currentCRSValueLabel.setText(crsDescription);
-            
+
             currentCRSLabel = new JLabel();
             currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));
@@ -339,7 +340,7 @@
 
     /**
-     * This method initializes okButton 
-     *  
-     * @return javax.swing.JButton  
+     * This method initializes okButton
+     *
+     * @return javax.swing.JButton
      */
     private JButton getOkButton() {
@@ -349,6 +350,7 @@
             okButton.setText("OK");
             okButton.addActionListener(new java.awt.event.ActionListener() {
-                public void actionPerformed(java.awt.event.ActionEvent e) {
-                    
+                @Override
+				public void actionPerformed(java.awt.event.ActionEvent e) {
+
                     setVisible(false);
                     dispose();
@@ -360,7 +362,7 @@
 
     /**
-     * This method initializes searchField  
-     *  
-     * @return javax.swing.JTextField   
+     * This method initializes searchField
+     *
+     * @return javax.swing.JTextField
      */
     private JTextField getSearchField() {
@@ -370,8 +372,9 @@
             searchField.setToolTipText("Enter keywords or EPSG codes");
             searchField.addKeyListener(new java.awt.event.KeyAdapter() {
-                public void keyTyped(java.awt.event.KeyEvent e) {
-                    
+                @Override
+				public void keyTyped(java.awt.event.KeyEvent e) {
+
                     for (Iterator<String> iterator = supportedCRS.iterator(); iterator.hasNext();) {
-                        String type = (String) iterator.next();
+                        String type = iterator.next();
                         if (type.contains(searchField.getText())) {
                             crsJList.setSelectedIndex(supportedCRS.indexOf(type));
@@ -379,5 +382,5 @@
                             break;
                         }
-                        
+
                     }
                 }
@@ -388,7 +391,7 @@
 
     /**
-     * This method initializes crsListScrollPane    
-     *  
-     * @return javax.swing.JScrollPane  
+     * This method initializes crsListScrollPane
+     *
+     * @return javax.swing.JScrollPane
      */
     private JScrollPane getCrsListScrollPane() {
@@ -402,7 +405,7 @@
 
     /**
-     * This method initializes crsJList 
-     *  
-     * @return javax.swing.JList    
+     * This method initializes crsJList
+     *
+     * @return javax.swing.JList
      */
     private JList<String> getCrsJList() {
@@ -415,7 +418,7 @@
 
     /**
-     * This method initializes useDefaultCRSButton  
-     *  
-     * @return javax.swing.JButton  
+     * This method initializes useDefaultCRSButton
+     *
+     * @return javax.swing.JButton
      */
     private JButton getUseDefaultCRSButton() {
@@ -425,8 +428,9 @@
             useDefaultCRSButton.setText("Apply Default");
             useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() {
-                public void actionPerformed(java.awt.event.ActionEvent e) {
-                    
+                @Override
+				public void actionPerformed(java.awt.event.ActionEvent e) {
+
                     try {
-                        
+
                         setCursor(new Cursor(Cursor.WAIT_CURSOR));
                         if(PluginOperations.defaultSourceCRS != null){
@@ -436,5 +440,5 @@
                             JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>");
                         }
-                        
+
                     } catch (NoSuchAuthorityCodeException e1) {
                         // TODO Auto-generated catch block
@@ -457,7 +461,7 @@
 
     /**
-     * This method initializes applySelectedCRSButton   
-     *  
-     * @return javax.swing.JButton  
+     * This method initializes applySelectedCRSButton
+     *
+     * @return javax.swing.JButton
      */
     private JButton getApplySelectedCRSButton() {
@@ -469,15 +473,16 @@
             applySelectedCRSButton.setText("<html>Apply<br>Selection</html>");
             applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() {
-                public void actionPerformed(java.awt.event.ActionEvent e) {
-                    
-                    String selection = (String) crsJList.getSelectedValue();
+                @Override
+				public void actionPerformed(java.awt.event.ActionEvent e) {
+
+                    String selection = crsJList.getSelectedValue();
                     String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
-                    
+
                     CoordinateReferenceSystem newRefSys = null;
                     try {
                         newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected());
-                        
+
                         setCursor(new Cursor(Cursor.WAIT_CURSOR));
-                        
+
                         imageLayer.resample(newRefSys);
 
@@ -495,6 +500,6 @@
                         setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                     }
-                    
-                    
+
+
                 }
             });
@@ -504,7 +509,7 @@
 
     /**
-     * This method initializes setSelectedCRSAsDefaultButton    
-     *  
-     * @return javax.swing.JButton  
+     * This method initializes setSelectedCRSAsDefaultButton
+     *
+     * @return javax.swing.JButton
      */
     private JButton getSetSelectedCRSAsDefaultButton() {
@@ -515,37 +520,29 @@
             setSelectedCRSAsDefaultButton
                     .addActionListener(new java.awt.event.ActionListener() {
-                        public void actionPerformed(java.awt.event.ActionEvent e) {
-                            
+                        @Override
+						public void actionPerformed(java.awt.event.ActionEvent e) {
+
                             if(crsJList.getSelectedValue() != null){
-                                String selection = (String) crsJList.getSelectedValue();
+                                String selection = crsJList.getSelectedValue();
                                 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
-                                
+
                                 try {
                                     PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected());
                                     PluginOperations.defaultSourceCRSDescription = selection;
-                                    
+
                                     ImportImagePlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected());
                                     ImportImagePlugin.pluginProps.setProperty("default_crs_srid", code);
-                                    FileWriter fileWriter = new FileWriter(new File(ImportImagePlugin.PLUGINPROPERTIES_PATH));
-                                    ImportImagePlugin.pluginProps.store(fileWriter, null);
-                                    fileWriter.close();
-                                    
+                                    try (FileWriter fileWriter = new FileWriter(new File(ImportImagePlugin.PLUGINPROPERTIES_PATH))) {
+                                    	ImportImagePlugin.pluginProps.store(fileWriter, null);
+                                    }
+
                                     defaultCRSLabel.setText(selection);
-                                    
-                                } catch (IOException e2) {
-                                    // TODO Auto-generated catch block
-                                    e2.printStackTrace();
-                                } catch (NoSuchAuthorityCodeException e3) {
-                                    // TODO Auto-generated catch block
-                                    e3.printStackTrace();
-                                } catch (FactoryException e4) {
-                                    // TODO Auto-generated catch block
-                                    e4.printStackTrace();
+
+                                } catch (IOException | FactoryException e2) {
+                                    Main.error(e2);
                                 }
-                            }else{
+                            } else {
                                 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list.");
                             }
-
-                            
                         }
                     });
@@ -553,9 +550,9 @@
         return setSelectedCRSAsDefaultButton;
     }
-    
-    /**
-     * This method initializes eastingFirstCheckBox 
-     *  
-     * @return javax.swing.JCheckBox    
+
+    /**
+     * This method initializes eastingFirstCheckBox
+     *
+     * @return javax.swing.JCheckBox
      */
     private JCheckBox getEastingFirstCheckBox() {
@@ -568,6 +565,6 @@
     }
 
-    
-    
+
+
     /**
      * Listener setting text in the search field if selection has changed.
@@ -575,5 +572,6 @@
      */
     class ListSelectionHandler implements ListSelectionListener {
-        public void valueChanged(ListSelectionEvent e) {
+        @Override
+		public void valueChanged(ListSelectionEvent e) {
             if(e.getValueIsAdjusting())
             {
Index: applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java
===================================================================
--- applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java	(revision 30737)
+++ applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java	(revision 30738)
@@ -296,13 +296,10 @@
         logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());
 
-        StringBuilder sb = new StringBuilder();
-        String content = null;
-        BufferedReader br = new BufferedReader(new FileReader(prjFile));
-        while((content = br.readLine()) != null)
-        {
-            sb.append(content);
-        }
-        br.close();
-        try {
+        try (BufferedReader br = new BufferedReader(new FileReader(prjFile))) {
+            StringBuilder sb = new StringBuilder();
+            String content = null;
+            while((content = br.readLine()) != null) {
+                sb.append(content);
+            }
             refSys = CRS.parseWKT(sb.toString().trim());
         } catch (FactoryException e) {
Index: applications/editors/josm/plugins/NanoLog/src/nanolog/NanoLogLayer.java
===================================================================
--- applications/editors/josm/plugins/NanoLog/src/nanolog/NanoLogLayer.java	(revision 30737)
+++ applications/editors/josm/plugins/NanoLog/src/nanolog/NanoLogLayer.java	(revision 30738)
@@ -103,38 +103,38 @@
         final SimpleDateFormat fmt = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SS");
         List<NanoLogEntry> result = new ArrayList<>();
-        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
-        while( r.ready() ) {
-            String line = r.readLine();
-            if( line != null ) {
-                Matcher m = NANOLOG_LINE.matcher(line);
-                if( m.matches() ) {
-                    String time = m.group(1);
-                    String message = m.group(2);
-                    String lat = m.group(3);
-                    String lon = m.group(4);
-                    String dir = m.group(5);
-                    Date timeDate = null;
-                    try {
-                        timeDate = fmt.parse(time);
-                    } catch( ParseException e ) {
-                    }
-                    if( message == null || message.length() == 0 || timeDate == null )
-                        continue;
-                    LatLon pos = null;
-                    Integer direction = null;
-                    if( lat != null && lon != null ) {
-                        try {
-                            pos = new LatLon(Double.parseDouble(lat), Double.parseDouble(lon));
-                            direction = new Integer(dir);
-                        } catch( NumberFormatException e ) {
-                            // well...
-                        }
-                    }
-                    NanoLogEntry entry = new NanoLogEntry(timeDate, message, pos, direction);
-                    result.add(entry);
-                }
-            }
-        }
-        r.close();
+        try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"))) {
+	        while( r.ready() ) {
+	            String line = r.readLine();
+	            if( line != null ) {
+	                Matcher m = NANOLOG_LINE.matcher(line);
+	                if( m.matches() ) {
+	                    String time = m.group(1);
+	                    String message = m.group(2);
+	                    String lat = m.group(3);
+	                    String lon = m.group(4);
+	                    String dir = m.group(5);
+	                    Date timeDate = null;
+	                    try {
+	                        timeDate = fmt.parse(time);
+	                    } catch( ParseException e ) {
+	                    }
+	                    if( message == null || message.length() == 0 || timeDate == null )
+	                        continue;
+	                    LatLon pos = null;
+	                    Integer direction = null;
+	                    if( lat != null && lon != null ) {
+	                        try {
+	                            pos = new LatLon(Double.parseDouble(lat), Double.parseDouble(lon));
+	                            direction = new Integer(dir);
+	                        } catch( NumberFormatException e ) {
+	                            // well...
+	                        }
+	                    }
+	                    NanoLogEntry entry = new NanoLogEntry(timeDate, message, pos, direction);
+	                    result.add(entry);
+	                }
+	            }
+	        }
+        }
         return result;
     }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java	(revision 30738)
@@ -1,4 +1,24 @@
 // License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others
 package cadastre_fr;
+
+import static org.openstreetmap.josm.tools.I18n.tr;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import javax.swing.JDialog;
+import javax.swing.JOptionPane;
+
+import org.openstreetmap.josm.Main;
+
 /**
  * This class handles the WMS layer cache mechanism. The design is oriented for a good performance (no
@@ -10,16 +30,4 @@
  * is inserted before each append and an exception is raised at objects read).
  */
-
-import static org.openstreetmap.josm.tools.I18n.tr;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.swing.JDialog;
-import javax.swing.JOptionPane;
-import org.openstreetmap.josm.Main;
-
 public class CacheControl implements Runnable {
 
@@ -32,4 +40,5 @@
             super(out);
         }
+        @Override
         protected void writeStreamHeader() throws IOException {
             reset();
@@ -40,5 +49,4 @@
 
     public static int cacheSize = 500;
-
 
     public WMSLayer wmsLayer = null;
@@ -141,9 +149,8 @@
     public boolean loadCache(File file, int currentLambertZone) {
         boolean successfulRead = false;
-        FileInputStream fis = null;
-        ObjectInputStream ois = null;
-        try {
-            fis = new FileInputStream(file);
-            ois = new ObjectInputStream(fis);
+        try (
+            FileInputStream fis = new FileInputStream(file);
+            ObjectInputStream ois = new ObjectInputStream(fis);
+        ) {
             successfulRead = wmsLayer.read(file, ois, currentLambertZone);
         } catch (Exception ex) {
@@ -151,11 +158,4 @@
             JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."), tr("Error"), JOptionPane.ERROR_MESSAGE);
             return false;
-        } finally {
-            try {
-                ois.close();
-                fis.close();
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
         }
         if (successfulRead && wmsLayer.isRaster()) {
@@ -165,5 +165,4 @@
         return successfulRead;
     }
-
 
     public synchronized void saveCache(GeorefImage image) {
@@ -177,4 +176,5 @@
      * Thread saving the grabbed images in background.
      */
+    @Override
     public synchronized void run() {
         for (;;) {
@@ -186,21 +186,21 @@
                 try {
                     if (file.exists()) {
-                        ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
-                                new BufferedOutputStream(new FileOutputStream(file, true)));
-                        for (int i=0; i < size; i++) {
-                            oos.writeObject(imagesToSave.get(i));
+                        try (ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
+                                new BufferedOutputStream(new FileOutputStream(file, true)))) {
+                            for (int i=0; i < size; i++) {
+                                oos.writeObject(imagesToSave.get(i));
+                            }
                         }
-                        oos.close();
                     } else {
-                        ObjectOutputStream oos = new ObjectOutputStream(
-                                new BufferedOutputStream(new FileOutputStream(file)));
-                        wmsLayer.write(file, oos);
-                        for (int i=0; i < size; i++) {
-                            oos.writeObject(imagesToSave.get(i));
+                        try (ObjectOutputStream oos = new ObjectOutputStream(
+                                new BufferedOutputStream(new FileOutputStream(file)))) {
+                            wmsLayer.write(file, oos);
+                            for (int i=0; i < size; i++) {
+                                oos.writeObject(imagesToSave.get(i));
+                            }
                         }
-                        oos.close();
                     }
                 } catch (IOException e) {
-                    e.printStackTrace(System.out);
+                    Main.error(e);
                 }
                 imagesLock.lock();
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java	(revision 30738)
@@ -22,6 +22,6 @@
     private CadastreInterface wmsInterface = new CadastreInterface();
 
-    public GeorefImage grab(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws IOException, OsmTransferException {
-
+    public GeorefImage grab(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax)
+            throws IOException, OsmTransferException {
         try {
             URL url = null;
@@ -88,8 +88,7 @@
         wmsInterface.urlConn.setRequestMethod("GET");
         wmsInterface.setCookie();
-        InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
-        BufferedImage img = ImageIO.read(is);
-        is.close();
-        return img;
+        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
+            return ImageIO.read(is);
+        }
     }
 
@@ -97,4 +96,3 @@
         return wmsInterface;
     }
-
 }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java	(revision 30738)
@@ -229,5 +229,5 @@
             }
             if (Main.isDebugEnabled()) {
-            	Main.debug(lines);
+                Main.debug(lines);
             }
         } catch (MalformedURLException e) {
@@ -284,14 +284,14 @@
             urlConn.setDoInput(true);
             setCookie();
-            OutputStream wr = urlConn.getOutputStream();
-            wr.write(content.getBytes());
-            System.out.println("POST "+content);
-            wr.flush();
-            wr.close();
-            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
-            while ((ln = rd.readLine()) != null) {
-                lines += ln;
-            }
-            rd.close();
+            try (OutputStream wr = urlConn.getOutputStream()) {
+                wr.write(content.getBytes());
+                Main.info("POST "+content);
+                wr.flush();
+            }
+            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
+                while ((ln = rd.readLine()) != null) {
+                    lines += ln;
+                }
+            }
             urlConn.disconnect();
             if (lines != null) {
@@ -371,15 +371,14 @@
             setCookie(urlConn2);
             urlConn2.connect();
-            System.out.println("GET "+getAllImagesURL);
-            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()));
-            while ((ln = rd.readLine()) != null) {
-                lines += ln;
-            }
-            rd.close();
+            Main.info("GET "+getAllImagesURL);
+            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()))) {
+                while ((ln = rd.readLine()) != null) {
+                    lines += ln;
+                }
+            }
             urlConn2.disconnect();
-            //System.out.println("GET="+lines);
         } catch (IOException e) {
             listOfFeuilles.clear();
-            e.printStackTrace();
+            Main.error(e);
         }
         return lines;
@@ -483,9 +482,9 @@
         }
         System.out.println("GET "+searchFormURL);
-        BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
-        while ((ln = in.readLine()) != null) {
-            line += ln;
-        }
-        in.close();
+        try (BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
+            while ((ln = in.readLine()) != null) {
+                line += ln;
+            }
+        }
         urlConn.disconnect();
         parseBBoxCommune(wmsLayer, line);
@@ -511,5 +510,5 @@
 
     private void parseGeoreferences(WMSLayer wmsLayer, String input) {
-        /* commented since cadastre WMS changes mid july 2013 
+        /* commented since cadastre WMS changes mid july 2013
          * until new GeoBox coordinates parsing is solved */
 //        if (input.lastIndexOf(cBBoxCommunStart) != -1) {
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionExporter.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionExporter.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionExporter.java	(revision 30738)
@@ -30,11 +30,11 @@
     }
 
-	@Override
-	public Collection<Layer> getDependencies() {
+    @Override
+    public Collection<Layer> getDependencies() {
         return Collections.emptySet();
-	}
+    }
 
-	@Override
-	public Component getExportPanel() {
+    @Override
+    public Component getExportPanel() {
         final JPanel p = new JPanel(new GridBagLayout());
         export = new JCheckBox();
@@ -46,18 +46,18 @@
         p.add(GBC.glue(1,0), GBC.std().fill(GBC.HORIZONTAL));
         return p;
-	}
+    }
 
-	@Override
-	public boolean shallExport() {
+    @Override
+    public boolean shallExport() {
         return export.isSelected();
-	}
+    }
 
-	@Override
-	public boolean requiresZip() {
-		return false;
-	}
+    @Override
+    public boolean requiresZip() {
+        return false;
+    }
 
-	@Override
-	public Element export(ExportSupport support) throws IOException {
+    @Override
+    public Element export(ExportSupport support) throws IOException {
         Element layerEl = support.createElement("layer");
         layerEl.setAttribute("type", "cadastre-fr");
@@ -76,5 +76,5 @@
         file.appendChild(support.createTextNode(url.toString()));
         return layerEl;
-	}
+    }
 
 }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java	(revision 30738)
@@ -22,8 +22,8 @@
 public class CadastreSessionImporter implements SessionLayerImporter{
 
-	@Override
-	public Layer load(Element elem, ImportSupport support,
-			ProgressMonitor progressMonitor) throws IOException,
-			IllegalDataException {
+    @Override
+    public Layer load(Element elem, ImportSupport support,
+            ProgressMonitor progressMonitor) throws IOException,
+            IllegalDataException {
         String version = elem.getAttribute("version");
         if (!"0.1".equals(version)) {
@@ -41,5 +41,5 @@
             fileStr = URLDecoder.decode(fileStr, "UTF-8");
             fileStr = fileStr.substring(fileStr.indexOf(":/")+2);
-    		String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
+            String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
             String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
             // create layer and load cache
@@ -60,5 +60,5 @@
             throw new RuntimeException(e);
         }
-	}
+    }
 
 }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java	(revision 30738)
@@ -43,5 +43,7 @@
     private static String errorMessage;
 
-
+    /**
+     * Constructs a new {@code DownloadSVGBuilding}.
+     */
     public DownloadSVGBuilding(WMSLayer wmsLayer) {
         super(tr("Downloading {0}", wmsLayer.getName()));
@@ -240,25 +242,22 @@
         wmsInterface.urlConn.setRequestMethod("GET");
         wmsInterface.setCookie();
-        InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
         File file = new File(CadastrePlugin.cacheDir + "building.svg");
         String svg = new String();
-        try {
+        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
             if (file.exists())
                 file.delete();
-            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
-            InputStreamReader isr =new InputStreamReader(is);
-            BufferedReader br = new BufferedReader(isr);
-            String line="";
-            while ( null!=(line=br.readLine())){
-                line += "\n";
-                bos.write(line.getBytes());
-                svg += line;
-            }
-            br.close();
-            bos.close();
+            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
+                 InputStreamReader isr = new InputStreamReader(is);
+                 BufferedReader br = new BufferedReader(isr)) {
+                String line="";
+                while ( null!=(line=br.readLine())){
+                    line += "\n";
+                    bos.write(line.getBytes());
+                    svg += line;
+                }
+            }
         } catch (IOException e) {
-            e.printStackTrace(System.out);
-        }
-        is.close();
+            Main.error(e);
+        }
         return svg;
     }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java	(revision 30738)
@@ -47,4 +47,7 @@
     private static String errorMessage;
 
+    /**
+     * Constructs a new {@code DownloadSVGTask}.
+     */
     public DownloadSVGTask(WMSLayer wmsLayer) {
         super(tr("Downloading {0}", wmsLayer.getName()));
@@ -194,25 +197,22 @@
         wmsInterface.urlConn.setRequestMethod("GET");
         wmsInterface.setCookie();
-        InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
         File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
         String svg = new String();
-        try {
+        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
             if (file.exists())
                 file.delete();
-            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
-            InputStreamReader isr =new InputStreamReader(is);
-            BufferedReader br = new BufferedReader(isr);
-            String line="";
-            while ( null!=(line=br.readLine())){
-                line += "\n";
-                bos.write(line.getBytes());
-                svg += line;
+            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
+                 InputStreamReader isr =new InputStreamReader(is);
+                 BufferedReader br = new BufferedReader(isr)) {
+                String line="";
+                while ( null!=(line=br.readLine())){
+                    line += "\n";
+                    bos.write(line.getBytes());
+                    svg += line;
+                }
             }
-            br.close();
-            bos.close();
         } catch (IOException e) {
-            e.printStackTrace(System.out);
-        }
-        is.close();
+            Main.error(e);
+        }
         return svg;
     }
Index: applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java
===================================================================
--- applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java	(revision 30737)
+++ applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java	(revision 30738)
@@ -133,5 +133,5 @@
         // if the layer is currently saving the images in the cache, wait until it's finished
         if(grabThread != null)
-        		grabThread.cancel();
+                grabThread.cancel();
         grabThread = null;
         super.destroy();
Index: applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanVecTile.java
===================================================================
--- applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanVecTile.java	(revision 30737)
+++ applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanVecTile.java	(revision 30738)
@@ -23,298 +23,298 @@
 
 public class CanVecTile {
-	CanvecLayer layer;
-	public boolean can_download = false;
-	private ArrayList<String> sub_tile_ids = new ArrayList<>();
-	private boolean zip_scanned = false;
-	
-	private ArrayList<CanVecTile> sub_tiles = new ArrayList<>();
-	private boolean sub_tiles_made = false;
-
-	private ArrayList<String> index;
-	private int depth;
-	
-	int corda,cordc;
-	private boolean valid = false;
-	String cordb,cordd;
-	private Bounds bounds;
-	public String tileid;
-	public CanVecTile(String tileid,CanvecLayer layer) {
-		String parta,partb,partc,partd;
-		parta = tileid.substring(0,3);
-		partb = tileid.substring(3, 4);
-		partc = tileid.substring(4, 6);
-		partd = tileid.substring(6);
-		int a,c;
-		a = Integer.parseInt(parta);
-		c = Integer.parseInt(partc);
-		real_init(a,partb,c,partd,layer,new ArrayList<String>());
-	}
-	public CanVecTile(int a,String b,int c,String d,CanvecLayer layer,ArrayList<String> index) {
-		real_init(a,b,c,d,layer,index);
-	}
-	public void real_init(int a,String b,int c,String d,CanvecLayer layer, ArrayList<String> index) {
-		this.index = index;
-		this.layer = layer;
-		corda = a;
-		cordb = b;
-		cordc = c;
-		cordd = d;
-		double zero_point_lat,zero_point_lon;
-		double lat_span,lon_span;
-		double lat2,lon2;
-		if ((a >= 0) && (a <= 119)) { // main block of tiles
-			int column = a / 10;
-			int row = a % 10;
-			if (row > 6) {
-				// cant handle x7 x8 and x9 yet
-				return;
-			}
-			zero_point_lat = 40 + 4 * row;
-			zero_point_lon = -56 - 8 * column;
-		
-			// size of each grid
-			if (row <= 6) {
-				// each is 4x8 degrees, broken into a 4x4 grid
-				lat_span = 4;
-				lon_span = 8;
-				depth = 1;
-			} else {
-				return;
-			}
-		} else { // last few tiles, very far north
-			return;
-		}
-
-		// a 4x4 grid of A thru P
-		// map A-P to 1-16
-		int grid2;
-		if (b == "") grid2 = 0;
-		else grid2 = b.charAt(0) - 64;
-		int rows1[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
-		int cols1[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
-		lat2 = zero_point_lat + (lat_span/4)*rows1[grid2];
-		lon2 = zero_point_lon + (lon_span/4)*cols1[grid2];
-
-		if (grid2 != 0) {
-			lat_span = lat_span / 4;
-			lon_span = lon_span / 4;
-			depth = 2;
-		}
-
-		int rows3[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
-		lat2 = lat2 + (lat_span/4)*rows3[c];
-		int cols3[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
-		lon2 = lon2 + (lon_span/4)*cols3[c];
-
-		if (c != 0) {
-			lat_span = lat_span / 4;
-			lon_span = lon_span / 4;
-			depth = 3;
-		}
-		
-		if (cordd != "") {
-			depth = 4;
-			System.out.println("cordd: "+cordd);
-			String foo[] = cordd.split("\\.");
-			for (int i = 0; i < foo.length; i++) {
-				int cell;
-				System.out.println(foo[i]);
-				if (foo[i] == "osm") break;
-				if (foo[i] == "") continue;
-				try {
-					cell = Integer.parseInt(foo[i]);
-				} catch (NumberFormatException e) {
-					continue;
-				}
-				switch (cell) {
-				case 0:
-					break;
-				case 1:
-					lat2 = lat2 + lat_span/2;
-					break;
-				case 2:
-					lat2 = lat2 + lat_span/2;
-					lon2 = lon2 + lon_span/2;
-					break;
-				case 3:
-					lon2 = lon2 + lon_span/2;
-					break;
-				}
-				lat_span = lat_span/2;
-				lon_span = lon_span/2;
-			}
-		}
-
-		bounds = new Bounds(lat2,lon2,lat2+lat_span,lon2+lon_span);
-		if (cordb == "") this.tileid = String.format("%03d",corda);
-		else if (cordc == 0) this.tileid = String.format("%03d%s",corda,cordb);
-		else if (cordd == "") this.tileid = String.format("%03d%s%02d",corda,cordb,cordc);
-		else this.tileid = String.format("%03d%s%02d%s",corda,cordb,cordc,cordd);
-		valid = true;
-		//debug(index.toString());
-		//debug("creating tileid: "+this.tileid);
-	}
-	public boolean isValid() { return valid; }
-	public String getTileId() {
-		return this.tileid;
-	}
-	private void debug(String line) {
-		System.out.println(depth + "_" + tileid + ": " + line);
-	}
-	public boolean isVisible(Bounds view) {
-		return view.intersects(bounds);
-	}
-	public Point[] getCorners(MapView mv) {
-		LatLon min = bounds.getMin();
-		LatLon max = bounds.getMax();
-		LatLon x1 = new LatLon(min.lat(),max.lon());
-		LatLon x2 = new LatLon(max.lat(),min.lon());
-		return new Point[] {
-			mv.getPoint(min), // south west
-			mv.getPoint(x1),
-			mv.getPoint(max),
-			mv.getPoint(x2) // north west
-			};
-	}
-	public String getDownloadUrl() {
-		return String.format("http://ftp2.cits.rncan.gc.ca/OSM/pub/%1$03d/%2$s/%1$03d%2$s%3$02d.zip",corda,cordb,cordc);
-	}
-	private ZipFile open_zip() throws IOException {
-		File download_path = new File(layer.plugin_self.getPluginDir() + File.separator);
-		download_path.mkdir();
-		CachedFile tile_zip = new CachedFile(getDownloadUrl()).setDestDir(download_path.toString());
-		return new ZipFile(tile_zip.getFile());
-	}
-	public void downloadSelf() {
-		if (zip_scanned) return;
-		ZipFile zipFile;
-		try {
-			zipFile = open_zip();
-		} catch (IOException e) {
-			e.printStackTrace();
-			return;
-		}
-		Enumeration<? extends ZipEntry> entries = zipFile.entries();
-		while (entries.hasMoreElements()) {
-			ZipEntry entry = entries.nextElement();
-			if (entry.getName().equals("Metadata.txt")) continue;
-			sub_tile_ids.add(entry.getName());
-			zip_scanned = true;
-			CanVecTile final_tile = new CanVecTile(entry.getName(),layer);
-			if (final_tile.isValid()) sub_tiles.add(final_tile);
-		}
-	}
-	public void load_raw_osm() {
-		ZipFile zipFile;
-		try {
-			zipFile = open_zip();
-			Enumeration<? extends ZipEntry> entries = zipFile.entries();
-			while (entries.hasMoreElements()) {
-				ZipEntry entry = entries.nextElement();
-				if (tileid.equals(entry.getName())) {
-					debug("found myself!");
-					InputStream rawtile = zipFile.getInputStream(entry);
-					OsmImporter importer = new OsmImporter();
-					debug("loading raw osm");
-					OsmImporterData temp = importer.loadLayer(rawtile, null, entry.getName(), null);
-					Main.worker.submit(temp.getPostLayerTask());
-					Main.main.addLayer(temp.getLayer());
-					temp.getLayer().data.setUploadDiscouraged(false);
-				}
-			}
-		} catch (IOException e) {
-			e.printStackTrace();
-			return;
-		} catch (IllegalDataException e) {
-			e.printStackTrace();
-			return;
-		}
-	}
-	private void make_sub_tiles(int layer) {
-		ArrayList<String> buffer = new ArrayList<>();
-		Pattern p;
-		if (sub_tiles_made) return;
-		switch (layer) {
-		case 1:
-			p = Pattern.compile("\\d\\d\\d([A-Z]).*");
-			String last_cell = "";
-			for (int i = 0; i < index.size(); i++) {
-				Matcher m = p.matcher(index.get(i));
-				m.matches();
-
-				String cell = m.group(1);
-				if (cell.equals(last_cell)) {
-					buffer.add(m.group(0));
-				} else if (last_cell == "") {
-					buffer.add(m.group(0));
-				} else {
-					sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
-					buffer = new ArrayList<>();
-					buffer.add(m.group(0));
-				}
-				last_cell = cell;
-			}
-			sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
-			break;
-		case 2:
-			p = Pattern.compile("\\d\\d\\d[A-Z](\\d\\d).*");
-			int last_cell2 = -1;
-			for (int i = 0; i < index.size(); i++) {
-				Matcher m = p.matcher(index.get(i));
-				m.matches();
-
-				int cell = Integer.parseInt(m.group(1));
-				if (cell == last_cell2) {
-					buffer.add(m.group(0));
-				} else if (last_cell2 == -1) {
-					buffer.add(m.group(0));
-				} else {
-					sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
-					buffer = new ArrayList<>();
-					buffer.add(m.group(0));
-				}
-				last_cell2 = cell;
-			}
-			if (last_cell2 != -1) sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
-			break;
-		}
-		sub_tiles_made = true;
-	}
-	public void paint(Graphics2D g, MapView mv, Bounds bounds, int max_zoom) {
-		boolean show_sub_tiles = false;
-		if (!isVisible(bounds)) return;
-		if (depth == 4) {
-			layer.openable.add(this);
-		}
-		if ((depth == 3) && (bounds.getArea() < 0.5)) { // 022B01
-			if (zip_scanned) {
-				show_sub_tiles = true;
-			} else if (can_download) {
-				downloadSelf();
-				show_sub_tiles = true;
-			} else {
-				layer.downloadable.add(this);
-			}
-		} else if ((depth == 2) && (bounds.getArea() < 20)) { // its a layer2 tile
-			make_sub_tiles(2);
-			show_sub_tiles = true;
-		} else if ((depth == 1) && (bounds.getArea() < 40)) { // its a layer1 tile and zoom too small
-			// draw layer2 tiles for self
-			make_sub_tiles(1);
-			show_sub_tiles = true;
-		}
-		if (show_sub_tiles && (depth < max_zoom)) {
-			for (int i = 0; i < sub_tiles.size(); i++) {
-				CanVecTile tile = sub_tiles.get(i);
-				tile.paint(g,mv,bounds,max_zoom);
-			}
-		} else {
-			Point corners[] = getCorners(mv);
-			int xs[] = { corners[0].x, corners[1].x, corners[2].x, corners[3].x };
-			int ys[] = { corners[0].y, corners[1].y, corners[2].y, corners[3].y };
-			Polygon shape = new Polygon(xs,ys,4);
-			g.draw(shape);
-			g.drawString(getTileId(),corners[0].x,corners[0].y);
-		}
-	}
+    CanvecLayer layer;
+    public boolean can_download = false;
+    private ArrayList<String> sub_tile_ids = new ArrayList<>();
+    private boolean zip_scanned = false;
+    
+    private ArrayList<CanVecTile> sub_tiles = new ArrayList<>();
+    private boolean sub_tiles_made = false;
+
+    private ArrayList<String> index;
+    private int depth;
+    
+    int corda,cordc;
+    private boolean valid = false;
+    String cordb,cordd;
+    private Bounds bounds;
+    public String tileid;
+    public CanVecTile(String tileid,CanvecLayer layer) {
+        String parta,partb,partc,partd;
+        parta = tileid.substring(0,3);
+        partb = tileid.substring(3, 4);
+        partc = tileid.substring(4, 6);
+        partd = tileid.substring(6);
+        int a,c;
+        a = Integer.parseInt(parta);
+        c = Integer.parseInt(partc);
+        real_init(a,partb,c,partd,layer,new ArrayList<String>());
+    }
+    public CanVecTile(int a,String b,int c,String d,CanvecLayer layer,ArrayList<String> index) {
+        real_init(a,b,c,d,layer,index);
+    }
+    public void real_init(int a,String b,int c,String d,CanvecLayer layer, ArrayList<String> index) {
+        this.index = index;
+        this.layer = layer;
+        corda = a;
+        cordb = b;
+        cordc = c;
+        cordd = d;
+        double zero_point_lat,zero_point_lon;
+        double lat_span,lon_span;
+        double lat2,lon2;
+        if ((a >= 0) && (a <= 119)) { // main block of tiles
+            int column = a / 10;
+            int row = a % 10;
+            if (row > 6) {
+                // cant handle x7 x8 and x9 yet
+                return;
+            }
+            zero_point_lat = 40 + 4 * row;
+            zero_point_lon = -56 - 8 * column;
+        
+            // size of each grid
+            if (row <= 6) {
+                // each is 4x8 degrees, broken into a 4x4 grid
+                lat_span = 4;
+                lon_span = 8;
+                depth = 1;
+            } else {
+                return;
+            }
+        } else { // last few tiles, very far north
+            return;
+        }
+
+        // a 4x4 grid of A thru P
+        // map A-P to 1-16
+        int grid2;
+        if (b == "") grid2 = 0;
+        else grid2 = b.charAt(0) - 64;
+        int rows1[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
+        int cols1[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
+        lat2 = zero_point_lat + (lat_span/4)*rows1[grid2];
+        lon2 = zero_point_lon + (lon_span/4)*cols1[grid2];
+
+        if (grid2 != 0) {
+            lat_span = lat_span / 4;
+            lon_span = lon_span / 4;
+            depth = 2;
+        }
+
+        int rows3[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
+        lat2 = lat2 + (lat_span/4)*rows3[c];
+        int cols3[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
+        lon2 = lon2 + (lon_span/4)*cols3[c];
+
+        if (c != 0) {
+            lat_span = lat_span / 4;
+            lon_span = lon_span / 4;
+            depth = 3;
+        }
+        
+        if (cordd != "") {
+            depth = 4;
+            System.out.println("cordd: "+cordd);
+            String foo[] = cordd.split("\\.");
+            for (int i = 0; i < foo.length; i++) {
+                int cell;
+                System.out.println(foo[i]);
+                if (foo[i] == "osm") break;
+                if (foo[i] == "") continue;
+                try {
+                    cell = Integer.parseInt(foo[i]);
+                } catch (NumberFormatException e) {
+                    continue;
+                }
+                switch (cell) {
+                case 0:
+                    break;
+                case 1:
+                    lat2 = lat2 + lat_span/2;
+                    break;
+                case 2:
+                    lat2 = lat2 + lat_span/2;
+                    lon2 = lon2 + lon_span/2;
+                    break;
+                case 3:
+                    lon2 = lon2 + lon_span/2;
+                    break;
+                }
+                lat_span = lat_span/2;
+                lon_span = lon_span/2;
+            }
+        }
+
+        bounds = new Bounds(lat2,lon2,lat2+lat_span,lon2+lon_span);
+        if (cordb == "") this.tileid = String.format("%03d",corda);
+        else if (cordc == 0) this.tileid = String.format("%03d%s",corda,cordb);
+        else if (cordd == "") this.tileid = String.format("%03d%s%02d",corda,cordb,cordc);
+        else this.tileid = String.format("%03d%s%02d%s",corda,cordb,cordc,cordd);
+        valid = true;
+        //debug(index.toString());
+        //debug("creating tileid: "+this.tileid);
+    }
+    public boolean isValid() { return valid; }
+    public String getTileId() {
+        return this.tileid;
+    }
+    private void debug(String line) {
+        System.out.println(depth + "_" + tileid + ": " + line);
+    }
+    public boolean isVisible(Bounds view) {
+        return view.intersects(bounds);
+    }
+    public Point[] getCorners(MapView mv) {
+        LatLon min = bounds.getMin();
+        LatLon max = bounds.getMax();
+        LatLon x1 = new LatLon(min.lat(),max.lon());
+        LatLon x2 = new LatLon(max.lat(),min.lon());
+        return new Point[] {
+            mv.getPoint(min), // south west
+            mv.getPoint(x1),
+            mv.getPoint(max),
+            mv.getPoint(x2) // north west
+            };
+    }
+    public String getDownloadUrl() {
+        return String.format("http://ftp2.cits.rncan.gc.ca/OSM/pub/%1$03d/%2$s/%1$03d%2$s%3$02d.zip",corda,cordb,cordc);
+    }
+    private ZipFile open_zip() throws IOException {
+        File download_path = new File(layer.plugin_self.getPluginDir() + File.separator);
+        download_path.mkdir();
+        CachedFile tile_zip = new CachedFile(getDownloadUrl()).setDestDir(download_path.toString());
+        return new ZipFile(tile_zip.getFile());
+    }
+    public void downloadSelf() {
+        if (zip_scanned) return;
+        ZipFile zipFile;
+        try {
+            zipFile = open_zip();
+        } catch (IOException e) {
+            e.printStackTrace();
+            return;
+        }
+        Enumeration<? extends ZipEntry> entries = zipFile.entries();
+        while (entries.hasMoreElements()) {
+            ZipEntry entry = entries.nextElement();
+            if (entry.getName().equals("Metadata.txt")) continue;
+            sub_tile_ids.add(entry.getName());
+            zip_scanned = true;
+            CanVecTile final_tile = new CanVecTile(entry.getName(),layer);
+            if (final_tile.isValid()) sub_tiles.add(final_tile);
+        }
+    }
+    public void load_raw_osm() {
+        ZipFile zipFile;
+        try {
+            zipFile = open_zip();
+            Enumeration<? extends ZipEntry> entries = zipFile.entries();
+            while (entries.hasMoreElements()) {
+                ZipEntry entry = entries.nextElement();
+                if (tileid.equals(entry.getName())) {
+                    debug("found myself!");
+                    InputStream rawtile = zipFile.getInputStream(entry);
+                    OsmImporter importer = new OsmImporter();
+                    debug("loading raw osm");
+                    OsmImporterData temp = importer.loadLayer(rawtile, null, entry.getName(), null);
+                    Main.worker.submit(temp.getPostLayerTask());
+                    Main.main.addLayer(temp.getLayer());
+                    temp.getLayer().data.setUploadDiscouraged(false);
+                }
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+            return;
+        } catch (IllegalDataException e) {
+            e.printStackTrace();
+            return;
+        }
+    }
+    private void make_sub_tiles(int layer) {
+        ArrayList<String> buffer = new ArrayList<>();
+        Pattern p;
+        if (sub_tiles_made) return;
+        switch (layer) {
+        case 1:
+            p = Pattern.compile("\\d\\d\\d([A-Z]).*");
+            String last_cell = "";
+            for (int i = 0; i < index.size(); i++) {
+                Matcher m = p.matcher(index.get(i));
+                m.matches();
+
+                String cell = m.group(1);
+                if (cell.equals(last_cell)) {
+                    buffer.add(m.group(0));
+                } else if (last_cell == "") {
+                    buffer.add(m.group(0));
+                } else {
+                    sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
+                    buffer = new ArrayList<>();
+                    buffer.add(m.group(0));
+                }
+                last_cell = cell;
+            }
+            sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
+            break;
+        case 2:
+            p = Pattern.compile("\\d\\d\\d[A-Z](\\d\\d).*");
+            int last_cell2 = -1;
+            for (int i = 0; i < index.size(); i++) {
+                Matcher m = p.matcher(index.get(i));
+                m.matches();
+
+                int cell = Integer.parseInt(m.group(1));
+                if (cell == last_cell2) {
+                    buffer.add(m.group(0));
+                } else if (last_cell2 == -1) {
+                    buffer.add(m.group(0));
+                } else {
+                    sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
+                    buffer = new ArrayList<>();
+                    buffer.add(m.group(0));
+                }
+                last_cell2 = cell;
+            }
+            if (last_cell2 != -1) sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
+            break;
+        }
+        sub_tiles_made = true;
+    }
+    public void paint(Graphics2D g, MapView mv, Bounds bounds, int max_zoom) {
+        boolean show_sub_tiles = false;
+        if (!isVisible(bounds)) return;
+        if (depth == 4) {
+            layer.openable.add(this);
+        }
+        if ((depth == 3) && (bounds.getArea() < 0.5)) { // 022B01
+            if (zip_scanned) {
+                show_sub_tiles = true;
+            } else if (can_download) {
+                downloadSelf();
+                show_sub_tiles = true;
+            } else {
+                layer.downloadable.add(this);
+            }
+        } else if ((depth == 2) && (bounds.getArea() < 20)) { // its a layer2 tile
+            make_sub_tiles(2);
+            show_sub_tiles = true;
+        } else if ((depth == 1) && (bounds.getArea() < 40)) { // its a layer1 tile and zoom too small
+            // draw layer2 tiles for self
+            make_sub_tiles(1);
+            show_sub_tiles = true;
+        }
+        if (show_sub_tiles && (depth < max_zoom)) {
+            for (int i = 0; i < sub_tiles.size(); i++) {
+                CanVecTile tile = sub_tiles.get(i);
+                tile.paint(g,mv,bounds,max_zoom);
+            }
+        } else {
+            Point corners[] = getCorners(mv);
+            int xs[] = { corners[0].x, corners[1].x, corners[2].x, corners[3].x };
+            int ys[] = { corners[0].y, corners[1].y, corners[2].y, corners[3].y };
+            Polygon shape = new Polygon(xs,ys,4);
+            g.draw(shape);
+            g.drawString(getTileId(),corners[0].x,corners[0].y);
+        }
+    }
 }
Index: applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelper.java
===================================================================
--- applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelper.java	(revision 30737)
+++ applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelper.java	(revision 30738)
@@ -8,15 +8,15 @@
 public class CanvecHelper extends Plugin {
     
-	public CanvecHelper(PluginInformation info) {
-		super(info);
-		Main.main.menu.imagerySubMenu.add(new CanvecHelperAction(this));
-	}
-	
+    public CanvecHelper(PluginInformation info) {
+        super(info);
+        Main.main.menu.imagerySubMenu.add(new CanvecHelperAction(this));
+    }
+    
     @Override
-	public void mapFrameInitialized(MapFrame old, MapFrame new1) {
-		updateLayer();
-	}
+    public void mapFrameInitialized(MapFrame old, MapFrame new1) {
+        updateLayer();
+    }
     
-	private synchronized void updateLayer() {
-	}
+    private synchronized void updateLayer() {
+    }
 }
Index: applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelperAction.java
===================================================================
--- applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelperAction.java	(revision 30737)
+++ applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelperAction.java	(revision 30738)
@@ -5,14 +5,14 @@
 
 public class CanvecHelperAction extends JosmAction {
-	private CanvecHelper parent_temp;
-	public CanvecHelperAction(CanvecHelper parent) {
-		super("CanVec Helper","layericon24",null,null,false);
-		parent_temp = parent;
-	}
+    private CanvecHelper parent_temp;
+    public CanvecHelperAction(CanvecHelper parent) {
+        super("CanVec Helper","layericon24",null,null,false);
+        parent_temp = parent;
+    }
         @Override
-	public void actionPerformed(java.awt.event.ActionEvent action) {
-		CanvecLayer layer;
-		layer = new CanvecLayer("canvec tile helper",parent_temp);
-		Main.main.addLayer(layer);
-	}
+    public void actionPerformed(java.awt.event.ActionEvent action) {
+        CanvecLayer layer;
+        layer = new CanvecLayer("canvec tile helper",parent_temp);
+        Main.main.addLayer(layer);
+    }
 }
Index: applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecLayer.java
===================================================================
--- applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecLayer.java	(revision 30737)
+++ applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecLayer.java	(revision 30738)
@@ -1,19 +1,22 @@
 package org.openstreetmap.josm.plugins.canvec_helper;
+
+import static org.openstreetmap.josm.tools.I18n.tr;
 
 import java.awt.Color;
 import java.awt.Component;
+import java.awt.Graphics2D;
+import java.awt.Toolkit;
 import java.awt.event.ActionEvent;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
-import java.awt.Graphics2D;
-import java.awt.Toolkit;
 import java.io.BufferedReader;
+import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+
 import javax.swing.AbstractAction;
 import javax.swing.Action;
@@ -22,209 +25,212 @@
 import javax.swing.JMenu;
 import javax.swing.JMenuItem;
+
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.Bounds;
 import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
+import org.openstreetmap.josm.gui.MapView;
 import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
 import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
 import org.openstreetmap.josm.gui.layer.Layer;
-import org.openstreetmap.josm.gui.MapView;
 import org.openstreetmap.josm.io.CachedFile;
-import static org.openstreetmap.josm.tools.I18n.tr;
 
 // most of the layout was copied from the openstreetbugs plugin to get things started
 public class CanvecLayer extends Layer implements MouseListener {
-	private Icon layerIcon = null;
-	private int max_zoom = 4;
-	public CanvecHelper plugin_self;
-	private ArrayList<CanVecTile> tiles = new ArrayList<>();
-	public ArrayList<CanVecTile> downloadable = new ArrayList<>();
-	public ArrayList<CanVecTile> openable = new ArrayList<>();
-
-	public CanvecLayer(String name,CanvecHelper self){
-		super(name);
-		plugin_self = self;
-		this.setBackgroundLayer(true);
-/*		for (int i = 0; i < 119; i++) {
-			CanVecTile tile = new CanVecTile(i,"",0,"",plugin_self);
-			if (tile.isValid()) tiles.add(tile);
-		}*/
-		layerIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("/images/layericon.png")));
-		try {
-			long start = System.currentTimeMillis();
-			Pattern p = Pattern.compile("(\\d\\d\\d)([A-Z]\\d\\d).*");
-			InputStream index = new CachedFile("http://ftp2.cits.rncan.gc.ca/OSM/pub/ZippedOsm.txt").getInputStream();
-			BufferedReader br = new BufferedReader(new InputStreamReader(index));
-			String line;
-			int last_cell = -1;
-			ArrayList<String> list = new ArrayList<>();
-			while ((line = br.readLine()) != null) {
-				Matcher m = p.matcher(line);
-				if (m.find()) {
-					int cell = Integer.parseInt(m.group(1));
-					if (cell == last_cell) {
-						list.add(m.group(0));
-					} else if (last_cell != -1) {
-						CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
-						if (tile.isValid()) tiles.add(tile);
-						list = new ArrayList<>();
-						list.add(m.group(0));
-					}
-					last_cell = cell;
-				} else if (line.contains("Metadata.txt")) {
-				} else {
-						System.out.print("bad line '" + line + "'\n");
-				}
-			}
-			br.close();
-			CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
-			if (tile.isValid()) tiles.add(tile);
-
-			long end = System.currentTimeMillis();
-			System.out.println((end-start)+"ms spent");
-		} catch (IOException e) {
-			System.out.println("exception getting index");
-			e.printStackTrace();
-		}
-	}
-        @Override
-	public Action[] getMenuEntries() {
-		return new Action[]{
-			LayerListDialog.getInstance().createShowHideLayerAction(),
-			LayerListDialog.getInstance().createDeleteLayerAction(),
-			SeparatorLayerAction.INSTANCE,
-			new LayerListPopup.InfoAction(this),
-			new MaxZoomAction(this),
-			new DownloadCanvecAction(this),
-			new OpenOsmAction(this)};
-	}
-	public class MaxZoomAction extends AbstractAction implements LayerAction {
-		private CanvecLayer parent;
-		public MaxZoomAction(CanvecLayer parent) {
-			this.parent = parent;
-		}
-                @Override
-		public void actionPerformed(ActionEvent e) {}
-                @Override
-		public boolean supportLayers(List<Layer> layers) {
-			return false;
-		}
-                @Override
-		public Component createMenuComponent() {
-			JMenu max_zoom = new JMenu("max zoom");
-			max_zoom.add(new JMenuItem(new SetMaxZoom(parent,1)));
-			max_zoom.add(new JMenuItem(new SetMaxZoom(parent,2)));
-			max_zoom.add(new JMenuItem(new SetMaxZoom(parent,3)));
-			max_zoom.add(new JMenuItem(new SetMaxZoom(parent,4)));
-			return max_zoom;
-		}
-	}
-	private class AllowDownload extends AbstractAction {
-		CanVecTile tile;
-		public AllowDownload(CanVecTile tile) {
-			super(tile.tileid);
-			this.tile = tile;
-		}
-                @Override
-		public void actionPerformed(ActionEvent arg0) {
-			tile.can_download = true;
-		}
-	}
-	private class OpenOsmAction extends AbstractAction implements LayerAction {
-		private CanvecLayer layer;
-		public OpenOsmAction(CanvecLayer layer) {
-			this.layer = layer;
-		}
-                @Override
-		public void actionPerformed(ActionEvent e) {}
-                @Override
-		public Component createMenuComponent() {
-			JMenu OpenOsm = new JMenu("Open tile");
-			for (int i = 0; i < layer.openable.size(); i++) {
-				OpenOsm.add(new JMenuItem(new DoOpenOsm(layer.openable.get(i))));
-			}
-			return OpenOsm;
-		}
-                @Override
-		public boolean supportLayers(List<Layer> layers) {
-			return false;
-		}
-	}
-	private class DoOpenOsm extends AbstractAction {
-		CanVecTile tile;
-		public DoOpenOsm(CanVecTile tile) {
-			super(tile.tileid);
-			this.tile = tile;
-		}
-                @Override
-		public void actionPerformed(ActionEvent e) {
-			tile.load_raw_osm();
-		}
-	}
-	private class DownloadCanvecAction extends AbstractAction implements LayerAction {
-		private CanvecLayer parent;
-		public DownloadCanvecAction(CanvecLayer parent) {
-			this.parent = parent;
-		}
-                @Override
-		public void actionPerformed(ActionEvent e) {}
-                @Override
-		public boolean supportLayers(List<Layer> layers) {
-			return false;
-		}
-                @Override
-		public Component createMenuComponent() {
-			JMenu downloadCanvec = new JMenu("Download zip's");
-			for (int i = 0; i < parent.downloadable.size(); i++) {
-				downloadCanvec.add(new JMenuItem(new AllowDownload(parent.downloadable.get(i))));
-			}
-			return downloadCanvec;
-		}
-	}
-	public void setMaxZoom(int max_zoom) {
-		this.max_zoom = max_zoom;
-	}
-        @Override
-	public Object getInfoComponent() {
-		return getToolTipText();
-	}
-        @Override
-	public String getToolTipText() {
-		return tr("canvec tile helper");
-	}
-        @Override
-	public void visitBoundingBox(BoundingXYVisitor v) {}
-        @Override
-	public boolean isMergable(Layer other) {
-		return false;
-	}
-        @Override
-	public void mergeFrom(Layer from) {}
-        @Override
-	public Icon getIcon() { return layerIcon; }
-        @Override
-	public void paint(Graphics2D g, MapView mv, Bounds bounds) {
-		//long start = System.currentTimeMillis();
-		//System.out.println("painting the area covered by "+bounds.toString());
-		downloadable = new ArrayList<>();
-		openable = new ArrayList<>();
-		// loop over each canvec tile in the db and check bounds.intersects(Bounds)
-		g.setColor(Color.red);
-		for (int i = 0; i < tiles.size(); i++) {
-			CanVecTile tile = tiles.get(i);
-			tile.paint(g,mv,bounds,max_zoom);
-		}
-		//long end = System.currentTimeMillis();
-		//System.out.println((end-start)+"ms spent");
-	}
-        @Override
-	public void mouseExited(MouseEvent e) {}
-        @Override
-	public void mouseEntered(MouseEvent e) {}
-        @Override
-	public void mouseReleased(MouseEvent e) {}
-        @Override
-	public void mousePressed(MouseEvent e) {}
-        @Override
-	public void mouseClicked(MouseEvent e) {
-		System.out.println("click!");
-	}
+    private Icon layerIcon = null;
+    private int max_zoom = 4;
+    public CanvecHelper plugin_self;
+    private ArrayList<CanVecTile> tiles = new ArrayList<>();
+    public ArrayList<CanVecTile> downloadable = new ArrayList<>();
+    public ArrayList<CanVecTile> openable = new ArrayList<>();
+
+    public CanvecLayer(String name,CanvecHelper self){
+        super(name);
+        plugin_self = self;
+        this.setBackgroundLayer(true);
+/*        for (int i = 0; i < 119; i++) {
+            CanVecTile tile = new CanVecTile(i,"",0,"",plugin_self);
+            if (tile.isValid()) tiles.add(tile);
+        }*/
+        layerIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("/images/layericon.png")));
+        long start = System.currentTimeMillis();
+        try (
+            InputStream index = new CachedFile("http://ftp2.cits.rncan.gc.ca/OSM/pub/ZippedOsm.txt").getInputStream();
+            BufferedReader br = new BufferedReader(new InputStreamReader(index));
+        ) {
+            Pattern p = Pattern.compile("(\\d\\d\\d)([A-Z]\\d\\d).*");
+            String line;
+            int last_cell = -1;
+            ArrayList<String> list = new ArrayList<>();
+            while ((line = br.readLine()) != null) {
+                Matcher m = p.matcher(line);
+                if (m.find()) {
+                    int cell = Integer.parseInt(m.group(1));
+                    if (cell == last_cell) {
+                        list.add(m.group(0));
+                    } else if (last_cell != -1) {
+                        CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
+                        if (tile.isValid()) tiles.add(tile);
+                        list = new ArrayList<>();
+                        list.add(m.group(0));
+                    }
+                    last_cell = cell;
+                } else if (line.contains("Metadata.txt")) {
+                } else {
+                    System.out.print("bad line '" + line + "'\n");
+                }
+            }
+            CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
+            if (tile.isValid()) tiles.add(tile);
+
+            if (Main.isDebugEnabled()) {
+                long end = System.currentTimeMillis();
+                Main.debug((end-start)+"ms spent");
+            }
+        } catch (IOException e) {
+            Main.error("exception getting index");
+            Main.error(e);
+        }
+    }
+    @Override
+    public Action[] getMenuEntries() {
+        return new Action[]{
+            LayerListDialog.getInstance().createShowHideLayerAction(),
+            LayerListDialog.getInstance().createDeleteLayerAction(),
+            SeparatorLayerAction.INSTANCE,
+            new LayerListPopup.InfoAction(this),
+            new MaxZoomAction(this),
+            new DownloadCanvecAction(this),
+            new OpenOsmAction(this)};
+    }
+    public class MaxZoomAction extends AbstractAction implements LayerAction {
+        private CanvecLayer parent;
+        public MaxZoomAction(CanvecLayer parent) {
+            this.parent = parent;
+        }
+                @Override
+        public void actionPerformed(ActionEvent e) {}
+                @Override
+        public boolean supportLayers(List<Layer> layers) {
+            return false;
+        }
+                @Override
+        public Component createMenuComponent() {
+            JMenu max_zoom = new JMenu("max zoom");
+            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,1)));
+            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,2)));
+            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,3)));
+            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,4)));
+            return max_zoom;
+        }
+    }
+    private class AllowDownload extends AbstractAction {
+        CanVecTile tile;
+        public AllowDownload(CanVecTile tile) {
+            super(tile.tileid);
+            this.tile = tile;
+        }
+                @Override
+        public void actionPerformed(ActionEvent arg0) {
+            tile.can_download = true;
+        }
+    }
+    private class OpenOsmAction extends AbstractAction implements LayerAction {
+        private CanvecLayer layer;
+        public OpenOsmAction(CanvecLayer layer) {
+            this.layer = layer;
+        }
+                @Override
+        public void actionPerformed(ActionEvent e) {}
+                @Override
+        public Component createMenuComponent() {
+            JMenu OpenOsm = new JMenu("Open tile");
+            for (int i = 0; i < layer.openable.size(); i++) {
+                OpenOsm.add(new JMenuItem(new DoOpenOsm(layer.openable.get(i))));
+            }
+            return OpenOsm;
+        }
+                @Override
+        public boolean supportLayers(List<Layer> layers) {
+            return false;
+        }
+    }
+    private class DoOpenOsm extends AbstractAction {
+        CanVecTile tile;
+        public DoOpenOsm(CanVecTile tile) {
+            super(tile.tileid);
+            this.tile = tile;
+        }
+                @Override
+        public void actionPerformed(ActionEvent e) {
+            tile.load_raw_osm();
+        }
+    }
+    private class DownloadCanvecAction extends AbstractAction implements LayerAction {
+        private CanvecLayer parent;
+        public DownloadCanvecAction(CanvecLayer parent) {
+            this.parent = parent;
+        }
+                @Override
+        public void actionPerformed(ActionEvent e) {}
+                @Override
+        public boolean supportLayers(List<Layer> layers) {
+            return false;
+        }
+                @Override
+        public Component createMenuComponent() {
+            JMenu downloadCanvec = new JMenu("Download zip's");
+            for (int i = 0; i < parent.downloadable.size(); i++) {
+                downloadCanvec.add(new JMenuItem(new AllowDownload(parent.downloadable.get(i))));
+            }
+            return downloadCanvec;
+        }
+    }
+    public void setMaxZoom(int max_zoom) {
+        this.max_zoom = max_zoom;
+    }
+        @Override
+    public Object getInfoComponent() {
+        return getToolTipText();
+    }
+        @Override
+    public String getToolTipText() {
+        return tr("canvec tile helper");
+    }
+        @Override
+    public void visitBoundingBox(BoundingXYVisitor v) {}
+        @Override
+    public boolean isMergable(Layer other) {
+        return false;
+    }
+        @Override
+    public void mergeFrom(Layer from) {}
+        @Override
+    public Icon getIcon() { return layerIcon; }
+        @Override
+    public void paint(Graphics2D g, MapView mv, Bounds bounds) {
+        //long start = System.currentTimeMillis();
+        //System.out.println("painting the area covered by "+bounds.toString());
+        downloadable = new ArrayList<>();
+        openable = new ArrayList<>();
+        // loop over each canvec tile in the db and check bounds.intersects(Bounds)
+        g.setColor(Color.red);
+        for (int i = 0; i < tiles.size(); i++) {
+            CanVecTile tile = tiles.get(i);
+            tile.paint(g,mv,bounds,max_zoom);
+        }
+        //long end = System.currentTimeMillis();
+        //System.out.println((end-start)+"ms spent");
+    }
+        @Override
+    public void mouseExited(MouseEvent e) {}
+        @Override
+    public void mouseEntered(MouseEvent e) {}
+        @Override
+    public void mouseReleased(MouseEvent e) {}
+        @Override
+    public void mousePressed(MouseEvent e) {}
+        @Override
+    public void mouseClicked(MouseEvent e) {
+        System.out.println("click!");
+    }
 }
Index: applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/SetMaxZoom.java
===================================================================
--- applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/SetMaxZoom.java	(revision 30737)
+++ applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/SetMaxZoom.java	(revision 30738)
@@ -5,14 +5,14 @@
 
 class SetMaxZoom extends AbstractAction {
-	private CanvecLayer parent;
-	private int level;
-	public SetMaxZoom(CanvecLayer parent,int level) {
-		super(""+level);
-		this.level = level;
-		this.parent = parent;
-	}
+    private CanvecLayer parent;
+    private int level;
+    public SetMaxZoom(CanvecLayer parent,int level) {
+        super(""+level);
+        this.level = level;
+        this.parent = parent;
+    }
         @Override
-	public void actionPerformed(ActionEvent ev) {
-		parent.setMaxZoom(level);
-	}
+    public void actionPerformed(ActionEvent ev) {
+        parent.setMaxZoom(level);
+    }
 }
Index: applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java
===================================================================
--- applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java	(revision 30737)
+++ applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java	(revision 30738)
@@ -1,5 +1,4 @@
 package org.openstreetmap.josm.plugins.czechaddress.parser;
 
-import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.*;
 import java.io.BufferedOutputStream;
 import java.io.File;
@@ -9,6 +8,8 @@
 import java.net.HttpURLConnection;
 import java.net.URL;
+
 import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.plugins.czechaddress.DatabaseLoadException;
+import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.Database;
 
 /**
@@ -109,15 +110,13 @@
                         "Požadavek na server selhal, číslo chyby: " + String.valueOf( con.getResponseCode() ));
 
-            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(getDatabasePath()));
-
-            int total = 0, count;
-            byte[] buffer = new byte[1024*512];
-            while ((count = con.getInputStream().read(buffer)) >= 0) {
-                bos.write(buffer, 0, count);
-                total += count;
-                System.err.println("CzechAddress: MVČR database: " + String.valueOf(total/1024) + " kb downloaded.");
+            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(getDatabasePath()))) {
+	            int total = 0, count;
+	            byte[] buffer = new byte[1024*512];
+	            while ((count = con.getInputStream().read(buffer)) >= 0) {
+	                bos.write(buffer, 0, count);
+	                total += count;
+	                Main.error("CzechAddress: MVČR database: " + String.valueOf(total/1024) + " kb downloaded.");
+	            }
             }
-
-            bos.close();
 
             // Look for a detailed error message from the server
Index: applications/editors/josm/plugins/dataimport/src/org/openstreetmap/josm/plugins/dataimport/io/TangoGPS.java
===================================================================
--- applications/editors/josm/plugins/dataimport/src/org/openstreetmap/josm/plugins/dataimport/io/TangoGPS.java	(revision 30737)
+++ applications/editors/josm/plugins/dataimport/src/org/openstreetmap/josm/plugins/dataimport/io/TangoGPS.java	(revision 30738)
@@ -30,5 +30,6 @@
 
 /**
- * @author dmuecke Data import for TangoGPS file format.
+ * Data import for TangoGPS file format.
+ * @author dmuecke
  */
 public class TangoGPS extends FileImporter {
@@ -40,6 +41,5 @@
     /**
      * @author cbrill
-     * This function imports data from file and adds trackpoints
-     *         to a layer.
+     * This function imports data from file and adds trackpoints to a layer.
      * Read a log file from TangoGPS. These are simple text files in the
      * form: <lat>,<lon>,<elevation>,<speed>,<course>,<hdop>,<datetime>
@@ -53,9 +53,8 @@
         int failure = 0;
 
-        BufferedReader rd = null;
-        try {
+        try (
             InputStream source = new FileInputStream(file);
-            rd = new BufferedReader(new InputStreamReader(source));
-
+            BufferedReader rd = new BufferedReader(new InputStreamReader(source));
+         ) {
             String line;
             while ((line = rd.readLine()) != null) {
@@ -72,5 +71,5 @@
                         imported++;
                     } catch (NumberFormatException e) {
-                        e.printStackTrace();
+                        Main.error(e);
                     }
                 }
@@ -92,8 +91,4 @@
             }
             showInfobox(imported,failure);
-        } finally {
-            if (rd != null) {
-                rd.close();
-            }
         }
     }
@@ -106,6 +101,5 @@
         if (lineElements.length < 2)
             return null;
-        return new LatLon(parseCoord(lineElements[0]),
-                parseCoord(lineElements[1]));
+        return new LatLon(parseCoord(lineElements[0]), parseCoord(lineElements[1]));
     }
 
@@ -118,5 +112,3 @@
         }
     }
-
-
 }
Index: applications/editors/josm/plugins/ext_tools/src/ext_tools/ToolsInformation.java
===================================================================
--- applications/editors/josm/plugins/ext_tools/src/ext_tools/ToolsInformation.java	(revision 30737)
+++ applications/editors/josm/plugins/ext_tools/src/ext_tools/ToolsInformation.java	(revision 30738)
@@ -8,4 +8,6 @@
 import java.util.ArrayList;
 import java.util.List;
+
+import org.openstreetmap.josm.Main;
 
 public class ToolsInformation {
@@ -20,7 +22,6 @@
 
     public void load() {
-        try {
-            BufferedReader rdr = new BufferedReader(new InputStreamReader(
-                    new FileInputStream(filename), "UTF-8"));
+        try (BufferedReader rdr = new BufferedReader(new InputStreamReader(
+                    new FileInputStream(filename), "UTF-8"))) {
             StringBuilder sb = new StringBuilder();
             String line;
@@ -32,21 +33,15 @@
                 }
             }
-            rdr.close();
         } catch (Exception e) {
-	    System.err.println("Ext_Tools warning: can not load file "+filename);
-//            e.printStackTrace();
+            Main.warn("Ext_Tools warning: can not load file "+filename);
         }
     }
 
     public void save() {
-        try {
-            OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(filename),
-                    "UTF-8");
+        try (OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")) {
             for (ExtTool tool : tools)
                 w.write(tool.serialize());
-            w.close();
         } catch (Exception e) {
-	    System.err.println("Ext_Tools warning: can not save file "+filename);
-//            e.printStackTrace();
+            Main.warn("Ext_Tools warning: can not save file "+filename);
         }
     }
Index: applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java
===================================================================
--- applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java	(revision 30737)
+++ applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java	(revision 30738)
@@ -11,4 +11,6 @@
 import java.nio.ByteBuffer;
 import java.util.Properties;
+
+import org.openstreetmap.josm.Main;
 
 /**
@@ -107,5 +109,6 @@
     }
 
-    public String toString()
+    @Override
+	public String toString()
     {
         return
@@ -459,39 +462,21 @@
         props.setProperty(propUnk3, "" + unk3);
         props.setProperty(propUnk4, "" + unk4);
-        OutputStream os = null;
-        try
-        {
-            os = new FileOutputStream(fName);
+
+        try (OutputStream os = new FileOutputStream(fName)) {
             props.store(os, "dg100 config");
-        }
-        catch (Exception ex)
-        {
-            ex.printStackTrace();
+        } catch (Exception ex) {
+            Main.error(ex);
             throw ex;
         }
-        finally
-        {
-            if (os != null) {os.close();}
-        }
-    }
-
-    public void readProps(String fName)
-        throws Exception
-    {
+    }
+
+    public void readProps(String fName) throws Exception {
         Properties props = new Properties();
-        InputStream is = null;
-        try
-        {
-            is = new FileInputStream(fName);
+
+        try (InputStream is = new FileInputStream(fName)) {
             props.load(is);
-        }
-        catch (Exception ex)
-        {
-            ex.printStackTrace();
+        } catch (Exception ex) {
+            Main.error(ex);;
             throw ex;
-        }
-        finally
-        {
-            if (is != null) {is.close();}
         }
         logFormat = Byte.parseByte(props.getProperty(propLogFormat, "2"));
Index: applications/editors/josm/plugins/gpxfilter/src/gpxfilter/GpxGrabber.java
===================================================================
--- applications/editors/josm/plugins/gpxfilter/src/gpxfilter/GpxGrabber.java	(revision 30737)
+++ applications/editors/josm/plugins/gpxfilter/src/gpxfilter/GpxGrabber.java	(revision 30738)
@@ -23,5 +23,5 @@
     private final double lat2;
     private final double lon2;
-    
+
     private int page;
 
@@ -31,5 +31,5 @@
         this.lat2 = downloadArea.getMax().lat();
         this.lon2 = downloadArea.getMax().lon();
-        
+
         page = 0;
     }
@@ -42,12 +42,9 @@
      */
     public GpxData parseRawGps() throws IOException, SAXException,OsmTransferException {
-        try {
-            String url = "trackpoints?bbox="+lon1+","+lat1+","+lon2+","+lat2+"&page="+page;
-
-            InputStream in = getInputStream(url, NullProgressMonitor.INSTANCE);
+        String url = "trackpoints?bbox="+lon1+","+lat1+","+lon2+","+lat2+"&page="+page;
+        try (InputStream in = getInputStream(url, NullProgressMonitor.INSTANCE)) {
             GpxReader reader = new GpxReader(in);
             reader.parse(false);
             GpxData result = reader.getGpxData();
-            in.close();
             result.fromServer = true;
             page++;
@@ -70,5 +67,6 @@
                 return null;
             throw e;
-        }    }
+        }
+    }
 
     @Override
Index: applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java
===================================================================
--- applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java	(revision 30738)
@@ -1,16 +1,21 @@
 package iodb;
 
+import static org.openstreetmap.josm.tools.I18n.marktr;
+
 import java.awt.event.KeyEvent;
-import java.util.*;
+import java.util.Collection;
+import java.util.LinkedList;
+
 import javax.swing.JMenu;
+
 import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.Version;
+import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
 import org.openstreetmap.josm.plugins.Plugin;
 import org.openstreetmap.josm.plugins.PluginInformation;
-import static org.openstreetmap.josm.tools.I18n.marktr;
 
 /**
  * A plugin to request and store imagery offsets in the centralized database.
- * 
+ *
  * @author Zverik
  * @license WTFPL
@@ -19,5 +24,5 @@
     private GetImageryOffsetAction getAction;
     private StoreImageryOffsetAction storeAction;
-    
+
     /**
      * Add both actions to their own menu. This creates
@@ -28,8 +33,8 @@
     public ImageryOffsetPlugin( PluginInformation info ) {
         super(info);
-        
+
         getAction = new GetImageryOffsetAction();
         storeAction = new StoreImageryOffsetAction();
-        
+
         // before 5803 imagery menu was constantly regenerated, erasing extra items
         // before 5729 it was regenerated only when the imagery list was modified (also bad)
@@ -43,5 +48,5 @@
         // an ugly hack to add this plugin to the toolbar
         if( Main.pref.getBoolean("iodb.modify.toolbar", true) ) {
-            Collection<String> toolbar = new LinkedList<>(Main.toolbar.getToolString());
+            Collection<String> toolbar = new LinkedList<>(ToolbarPreferences.getToolString());
             if( !toolbar.contains("getoffset") ) {
                 toolbar.add("getoffset");
Index: applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java
===================================================================
--- applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java	(revision 30738)
@@ -1,5 +1,14 @@
 package iodb;
 
-import java.awt.*;
+import static org.openstreetmap.josm.tools.I18n.tr;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.FlowLayout;
+import java.awt.Graphics2D;
+import java.awt.GridLayout;
+import java.awt.Point;
+import java.awt.RenderingHints;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
@@ -8,9 +17,22 @@
 import java.net.HttpURLConnection;
 import java.net.URL;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
-import javax.swing.*;
+
+import javax.swing.AbstractAction;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.KeyStroke;
 import javax.swing.border.CompoundBorder;
 import javax.swing.border.EmptyBorder;
+
 import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.Bounds;
@@ -19,10 +41,12 @@
 import org.openstreetmap.josm.gui.layer.ImageryLayer;
 import org.openstreetmap.josm.gui.layer.MapViewPaintable;
-import org.openstreetmap.josm.tools.*;
-import static org.openstreetmap.josm.tools.I18n.tr;
+import org.openstreetmap.josm.tools.ImageProvider;
+import org.openstreetmap.josm.tools.LanguageInfo;
+import org.openstreetmap.josm.tools.OpenBrowser;
+import org.openstreetmap.josm.tools.Utils;
 
 /**
  * The dialog which presents a choice between imagery align options.
- * 
+ *
  * @author Zverik
  * @license WTFPL
@@ -31,5 +55,5 @@
     protected static final String PREF_CALIBRATION = "iodb.show.calibration";
     protected static final String PREF_DEPRECATED = "iodb.show.deprecated";
-    private static final int MAX_OFFSETS = Main.main.pref.getInteger("iodb.max.offsets", 4);
+    private static final int MAX_OFFSETS = Main.pref.getInteger("iodb.max.offsets", 4);
 
     /**
@@ -45,5 +69,5 @@
 
     /**
-     * Initialize the dialog and install listeners. 
+     * Initialize the dialog and install listeners.
      * @param offsets The list of offset to choose from.
      */
@@ -60,5 +84,5 @@
                 JComponent.WHEN_IN_FOCUSED_WINDOW);
     }
-    
+
     /**
      * Creates the GUI.
@@ -69,5 +93,6 @@
         calibrationBox.setSelected(Main.pref.getBoolean(PREF_CALIBRATION, true));
         calibrationBox.addActionListener(new ActionListener() {
-            public void actionPerformed( ActionEvent e ) {
+            @Override
+			public void actionPerformed( ActionEvent e ) {
                 Main.pref.put(PREF_CALIBRATION, calibrationBox.isSelected());
                 updateButtonPanel();
@@ -77,5 +102,6 @@
         deprecatedBox.setSelected(Main.pref.getBoolean(PREF_DEPRECATED, false));
         deprecatedBox.addActionListener(new ActionListener() {
-            public void actionPerformed( ActionEvent e ) {
+            @Override
+			public void actionPerformed( ActionEvent e ) {
                 Main.pref.put(PREF_DEPRECATED, deprecatedBox.isSelected());
                 updateButtonPanel();
@@ -154,5 +180,6 @@
      * It does nothing, only passes the event to all displayed offset buttons.
      */
-    public void zoomChanged() {
+    @Override
+	public void zoomChanged() {
         for( Component c : buttonPanel.getComponents() ) {
             if( c instanceof OffsetDialogButton ) {
@@ -166,5 +193,6 @@
      * value, but looks nice.
      */
-    public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
+    @Override
+	public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
         if( offsets == null )
             return;
@@ -181,5 +209,5 @@
         }
     }
-    
+
     /**
      * Display the dialog and get the return value is case of a modal frame.
@@ -208,5 +236,6 @@
      * @see #applyOffset()
      */
-    public void actionPerformed( ActionEvent e ) {
+    @Override
+	public void actionPerformed( ActionEvent e ) {
         if( e.getSource() instanceof OffsetDialogButton ) {
             selectedOffset = ((OffsetDialogButton)e.getSource()).getOffset();
@@ -283,5 +312,6 @@
          * Remove the deprecated offset from the offsets list. Then rebuild the button panel.
          */
-        public void queryPassed() {
+        @Override
+		public void queryPassed() {
             offset.setDeprecated(new Date(), JosmUserIdentityManager.getInstance().getUserName(), "");
             updateButtonPanel();
@@ -299,5 +329,6 @@
         }
 
-        public void actionPerformed( ActionEvent e ) {
+        @Override
+		public void actionPerformed( ActionEvent e ) {
             String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/");
             String lang = LanguageInfo.getWikiLanguagePrefix();
Index: applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java
===================================================================
--- applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java	(revision 30737)
+++ applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java	(revision 30738)
@@ -117,5 +117,5 @@
                 query.append(key).append('=').append(URLEncoder.encode(params.get(key), "UTF8"));
             }
-            Main.main.worker.submit(new SimpleOffsetQueryTask(query.toString(), tr("Uploading a new offset...")));
+            Main.worker.submit(new SimpleOffsetQueryTask(query.toString(), tr("Uploading a new offset...")));
         } catch( UnsupportedEncodingException ex ) {
             // WTF
Index: applications/editors/josm/plugins/imagerycache/src/org/openstreetmap/josm/plugins/imagerycache/OsmDBTilesLoader.java
===================================================================
--- applications/editors/josm/plugins/imagerycache/src/org/openstreetmap/josm/plugins/imagerycache/OsmDBTilesLoader.java	(revision 30737)
+++ applications/editors/josm/plugins/imagerycache/src/org/openstreetmap/josm/plugins/imagerycache/OsmDBTilesLoader.java	(revision 30738)
@@ -11,4 +11,5 @@
 import java.util.Map;
 import java.util.Random;
+
 import org.openstreetmap.gui.jmapviewer.JobDispatcher;
 import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
@@ -20,24 +21,25 @@
 import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
 import org.openstreetmap.gui.jmapviewer.interfaces.TileSource.TileUpdate;
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.preferences.BooleanProperty;
 
 /**
- * 
+ *
  * @author Alexei Kasatkin, based on OsmFileCacheTileLoader by @author Jan Peter Stotz, @author Stefan Zeller
  */
 class OsmDBTilesLoader extends OsmTileLoader implements CachedTileLoader {
-    
-    
+
+
     public static final long FILE_AGE_ONE_DAY = 1000 * 60 * 60 * 24;
     public static final long FILE_AGE_ONE_WEEK = FILE_AGE_ONE_DAY * 7;
-    
+
     public static final boolean debug = new BooleanProperty("imagerycache.debug", false).get();
-            
+
     TileDAOMapDB dao;
-   
+
     protected long maxCacheFileAge = FILE_AGE_ONE_WEEK;
     protected long recheckAfter = FILE_AGE_ONE_DAY;
 
-    
+
     public OsmDBTilesLoader(TileLoaderListener smap, File cacheFolder) {
         super(smap);
@@ -45,5 +47,5 @@
         dao.setCacheFolder(cacheFolder);
     }
-    
+
     @Override
     public TileJob createTileLoaderJob(final Tile tile) {
@@ -60,19 +62,19 @@
         dao.cleanStorage(source.getName());
     }
-    
+
     protected class DatabaseLoadJob implements TileJob {
 
         private final Tile tile;
         File tileCacheDir;
-        
+
         /**
-         * Stores the tile loaded from database, null if nothing found. 
+         * Stores the tile loaded from database, null if nothing found.
          */
         DBTile dbTile = null;
         long fileAge = 0;
-        
+
         long id;
         String sourceName;
-        
+
         public DatabaseLoadJob(Tile tile) {
             this.tile = tile;
@@ -112,5 +114,5 @@
 
         /**
-         * Loads tile from database. 
+         * Loads tile from database.
          * There can be dbTile != null but the tile is outdated and reload is still needed
          * @return true if no loading from server is needed.
@@ -120,8 +122,8 @@
             try {
                 dbTile = dao.getById(sourceName, id);
-                
+
                 if (dbTile == null) return false;
-                
-                loadMetadata(); 
+
+                loadMetadata();
                 if (debug) System.out.println(id+": found in cache, metadata ="+dbTile.metaData);
 
@@ -149,6 +151,6 @@
                 }
             } catch (Exception e) {
-                System.out.println("Error: Can not load tile from database: "+sourceName+":"+id);
-                e.printStackTrace(System.out);
+            	Main.error("Error: Can not load tile from database: "+sourceName+":"+id);
+            	Main.error(e);
                 try {
                     if (bin != null) {
@@ -161,7 +163,7 @@
                 return false; // tile is not because of some error (corrupted database, etc.)
             } catch (Error e) { // this is bad, bat MapDB throws it
-                System.out.println("Serious database error: Can not load tile from database: "+sourceName+":"+id);
-                e.printStackTrace(System.out);
-                dbTile = null;  fileAge = 0;  return false;                                            
+                Main.error("Serious database error: Can not load tile from database: "+sourceName+":"+id);
+            	Main.error(e);
+                dbTile = null;  fileAge = 0;  return false;
             }
         }
@@ -170,7 +172,7 @@
             return System.currentTimeMillis() - maxCacheFileAge + recheckAfter;
         }
-                
+
         private void loadOrUpdateTileFromServer() {
-            
+
             try {
                 URLConnection urlConn = loadTileFromOsm(tile);
@@ -195,5 +197,5 @@
                     dbTile = new DBTile();
                 }
-                
+
                 if (tileUpdate == TileSource.TileUpdate.ETag || tileUpdate == TileSource.TileUpdate.IfNoneMatch) {
                     String fileETag = tile.getValue("etag");
@@ -224,5 +226,5 @@
                 loadTileMetadata(tile, urlConn);
                 dbTile.metaData = tile.getMetadata();
-                
+
                 if ("no-tile".equals(tile.getValue("tile-info")))
                 {
@@ -248,5 +250,5 @@
                     }
                 }
-                
+
             } catch (Exception e) {
                 tile.setError(e.getMessage());
@@ -261,6 +263,6 @@
             }
         }
-        
-        
+
+
         protected byte[] loadTileInBuffer(URLConnection urlConn) throws IOException {
             InputStream input = urlConn.getInputStream();
@@ -292,5 +294,5 @@
          * </ul>
          *
-         * @param fileAge time of the 
+         * @param fileAge time of the
          * @return <code>true</code> if the tile on the server is newer than the
          *         file
Index: applications/editors/josm/plugins/mapdust/src/org/openstreetmap/josm/plugins/mapdust/util/http/HttpConnector.java
===================================================================
--- applications/editors/josm/plugins/mapdust/src/org/openstreetmap/josm/plugins/mapdust/util/http/HttpConnector.java	(revision 30737)
+++ applications/editors/josm/plugins/mapdust/src/org/openstreetmap/josm/plugins/mapdust/util/http/HttpConnector.java	(revision 30738)
@@ -38,4 +38,5 @@
 import java.net.URLEncoder;
 import java.util.Map;
+
 import org.openstreetmap.josm.plugins.mapdust.util.retry.RetryAgent;
 import org.openstreetmap.josm.plugins.mapdust.util.retry.RetrySetup;
@@ -160,9 +161,8 @@
                 /* 3: write content */
                 if (sbEncodeParameters.length() > 0) {
-                    OutputStreamWriter out =
-                            new OutputStreamWriter(connection.getOutputStream());
-
-                    out.write(sbEncodeParameters.toString());
-                    out.close();
+                    try (OutputStreamWriter out =
+                            new OutputStreamWriter(connection.getOutputStream())) {
+                        out.write(sbEncodeParameters.toString());
+                    }
                 }
 
Index: applications/editors/josm/plugins/native-password-manager/src/org/netbeans/modules/keyring/kde/KWalletProvider.java
===================================================================
--- applications/editors/josm/plugins/native-password-manager/src/org/netbeans/modules/keyring/kde/KWalletProvider.java	(revision 30737)
+++ applications/editors/josm/plugins/native-password-manager/src/org/netbeans/modules/keyring/kde/KWalletProvider.java	(revision 30738)
@@ -49,4 +49,5 @@
 import java.util.logging.Level;
 import java.util.logging.Logger;
+
 import org.netbeans.spi.keyring.KeyringProvider;
 
@@ -69,7 +70,7 @@
         }
         CommandResult result = runCommand("isEnabled");
-        if(new String(result.retVal).equals("true")) {        
+        if(new String(result.retVal).equals("true")) {
             return updateHandler();
-        }                   
+        }
         return false;
     };
@@ -121,15 +122,15 @@
         }
         handler = new String(handler).equals("")? "0".toCharArray() : handler;
-        CommandResult result = runCommand("isOpen",handler);          
+        CommandResult result = runCommand("isOpen",handler);
         if(new String(result.retVal).equals("true")){
             return true;
         }
         char[] localWallet = defaultLocalWallet;
-        result = runCommand("localWallet");                      
-        if(result.exitCode == 0) {                    
+        result = runCommand("localWallet");
+        if(result.exitCode == 0) {
             localWallet = result.retVal;
         }
-            
-        if(new String(localWallet).contains(".service")) {            
+
+        if(new String(localWallet).contains(".service")) {
             //Temporary workaround for the bug in kdelibs/kdeui/util/kwallet.cpp
             //The bug was fixed http://svn.reviewboard.kde.org/r/5885/diff/
@@ -138,19 +139,19 @@
         }
         result = runCommand("open", localWallet , "0".toCharArray(), getApplicationName(true));
-        if(result.exitCode == 2) { 
+        if(result.exitCode == 2) {
             warning("time out happened while accessing KWallet");
             //don't try to open KWallet anymore until bug https://bugs.kde.org/show_bug.cgi?id=259229 is fixed
             timeoutHappened = true;
             return false;
-        }      
+        }
         if(result.exitCode != 0 || new String(result.retVal).equals("-1")) {
             warning("failed to access KWallet");
             return false;
-        }         
+        }
         handler = result.retVal;
         return true;
     }
-          
-    
+
+
 
     private CommandResult runCommand(String command,char[]... commandArgs) {
@@ -174,24 +175,23 @@
             }
             Process pr = rt.exec(argv);
-            
-            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
-
             String line;
-            while((line = input.readLine()) != null) {
-                if (!retVal.equals("")){
-                    retVal = retVal.concat("\n");
+
+            try (BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
+                while((line = input.readLine()) != null) {
+                    if (!retVal.equals("")){
+                        retVal = retVal.concat("\n");
+                    }
+                    retVal = retVal.concat(line);
                 }
-                retVal = retVal.concat(line);
-            }            
-            input.close();
-            input = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
-
-            while((line = input.readLine()) != null) {
-                if (!errVal.equals("")){
-                    errVal = errVal.concat("\n");
+            }
+
+            try (BufferedReader input = new BufferedReader(new InputStreamReader(pr.getErrorStream()))) {
+                while((line = input.readLine()) != null) {
+                    if (!errVal.equals("")){
+                        errVal = errVal.concat("\n");
+                    }
+                    errVal = errVal.concat(line);
                 }
-                errVal = errVal.concat(line);
-            }
-            input.close();
+            }
 
             exitCode = pr.waitFor();
@@ -199,5 +199,5 @@
                 logger.log(Level.FINE, "application exit with code {0} for commandString: {1}; errVal: {2}",
                             new Object[]{exitCode, Arrays.toString(argv), errVal});
-            }       
+            }
         } catch (InterruptedException ex) {
             logger.log(Level.FINE,
@@ -210,5 +210,5 @@
         }
         return new CommandResult(exitCode, retVal.trim().toCharArray(), errVal.trim());
-    }    
+    }
 
     private char[] getApplicationName(){
@@ -222,16 +222,14 @@
     private void warning(String descr) {
         logger.log(Level.WARNING, "Something went wrong: {0}", descr);
-    }      
-  
+    }
+
     private class CommandResult {
         private int exitCode;
         private char[] retVal;
-        private String errVal;
 
         public CommandResult(int exitCode, char[] retVal, String errVal) {
             this.exitCode = exitCode;
             this.retVal = retVal;
-            this.errVal = errVal;
-        }                        
+        }
     }
 
Index: applications/editors/josm/plugins/opendata/includes/org/apache/poi/hssf/record/formula/function/FunctionMetadataReader.java
===================================================================
--- applications/editors/josm/plugins/opendata/includes/org/apache/poi/hssf/record/formula/function/FunctionMetadataReader.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/includes/org/apache/poi/hssf/record/formula/function/FunctionMetadataReader.java	(revision 30738)
@@ -22,5 +22,4 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
 import java.util.Arrays;
 import java.util.HashSet;
@@ -32,5 +31,5 @@
 /**
  * Converts the text meta-data file into a <tt>FunctionMetadataRegistry</tt>
- * 
+ *
  * @author Josh Micich
  */
@@ -38,5 +37,5 @@
 
 	private static final String METADATA_FILE_NAME = "functionMetadata.txt";
-	
+
 	/** plain ASCII text metadata file uses three dots for ellipsis */
 	private static final String ELLIPSIS = "...";
@@ -59,13 +58,7 @@
 		}
 
-		BufferedReader br;
-		try {
-			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
-		} catch(UnsupportedEncodingException e) {
-			throw new RuntimeException(e);
-		}
 		FunctionDataBuilder fdb = new FunctionDataBuilder(400);
 
-		try {
+		try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
 			while (true) {
 				String line = br.readLine();
@@ -82,5 +75,4 @@
 				processLine(fdb, line);
 			}
-			br.close();
 		} catch (IOException e) {
 			throw new RuntimeException(e);
@@ -107,8 +99,8 @@
 		validateFunctionName(functionName);
 		// TODO - make POI use isVolatile
-		fdb.add(functionIndex, functionName, minParams, maxParams, 
+		fdb.add(functionIndex, functionName, minParams, maxParams,
 				returnClassCode, parameterClassCodes, hasNote);
 	}
-	
+
 
 	private static byte parseReturnTypeCode(String code) {
@@ -164,5 +156,5 @@
 
 	/**
-	 * Makes sure that footnote digits from the original OOO document have not been accidentally 
+	 * Makes sure that footnote digits from the original OOO document have not been accidentally
 	 * left behind
 	 */
@@ -182,5 +174,5 @@
 			return;
 		}
-		throw new RuntimeException("Invalid function name '" + functionName 
+		throw new RuntimeException("Invalid function name '" + functionName
 				+ "' (is footnote number incorrectly appended)");
 	}
Index: applications/editors/josm/plugins/opendata/modules/fr.datagouvfr/src/org/openstreetmap/josm/plugins/opendata/modules/fr/datagouvfr/datasets/hydrologie/EauxDeSurfaceHandler.java
===================================================================
--- applications/editors/josm/plugins/opendata/modules/fr.datagouvfr/src/org/openstreetmap/josm/plugins/opendata/modules/fr/datagouvfr/datasets/hydrologie/EauxDeSurfaceHandler.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/modules/fr.datagouvfr/src/org/openstreetmap/josm/plugins/opendata/modules/fr/datagouvfr/datasets/hydrologie/EauxDeSurfaceHandler.java	(revision 30738)
@@ -14,4 +14,5 @@
 import java.util.regex.Pattern;
 
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.osm.DataSet;
 import org.openstreetmap.josm.plugins.opendata.core.io.archive.DefaultArchiveHandler;
@@ -23,5 +24,5 @@
     private static final String ZIP_PATTERN = "FR(.*)_SW";
     private static final String SHP_PATTERN = "FR_(.*)_SWB_.W_20......";
-    
+
     private static final class WaterAgency {
         public final String code;
@@ -34,5 +35,5 @@
         }
     }
-    
+
     private static final WaterAgency[] waterAgencies = new WaterAgency[]{
         new WaterAgency("A",  "Escaut Somme", "Escaut-Somme-30381967"),
@@ -49,10 +50,10 @@
         new WaterAgency("L",  "La Réunion", "Réunion-30381991"),
     };
-    
+
     public EauxDeSurfaceHandler() {
         setName("Eaux de surface");
         setArchiveHandler(new InternalZipHandler());
     }
-    
+
     @Override
     public boolean acceptsFilename(String filename) {
@@ -63,5 +64,5 @@
         return result;
     }
-    
+
     @Override
     public boolean acceptsUrl(String url) {
@@ -91,5 +92,5 @@
         // TODO Auto-generated method stub
     }
-    
+
     @Override
     public List<Pair<String, URL>> getDataURLs() {
@@ -106,25 +107,25 @@
 
     private Pair<String, URL> getDownloadURL(WaterAgency a) throws MalformedURLException {
-        return new Pair<>("SurfaceWater_"+a.name, new URL("http://www.rapportage.eaufrance.fr/sites/default/files/SIG/FR"+a.code+"_SW.zip"));
+        return new Pair<>("SurfaceWater_"+a.name,
+                new URL("http://www.rapportage.eaufrance.fr/sites/default/files/SIG/FR"+a.code+"_SW.zip"));
     }
-    
+
     private class InternalZipHandler extends DefaultArchiveHandler {
         @Override
         public void notifyTempFileWritten(File file) {
-            if (file.getName().matches(SHP_PATTERN.replace("(.*)", "F")+"\\.prj")) { // Adour-Garonne .prj files cannot be parsed because they do not contain quotes... 
-                try {
-                    BufferedReader reader = new BufferedReader(new FileReader(file));
+            // Adour-Garonne .prj files cannot be parsed because they do not contain quotes...
+            if (file.getName().matches(SHP_PATTERN.replace("(.*)", "F")+"\\.prj")) {
+                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                     String line = reader.readLine();
-                    reader.close();
                     if (!line.contains("\"")) {
                         for (String term : new String[]{"GCS_ETRS_1989", "D_ETRS_1989", "GRS_1980", "Greenwich", "Degree"}) {
                             line = line.replace(term, "\""+term+"\"");
                         }
-                        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
-                        writer.write(line);
-                        writer.close();
+                        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
+                            writer.write(line);
+                        }
                     }
                 } catch (Exception e) {
-                    e.printStackTrace();
+                    Main.error(e);
                 }
             }
Index: applications/editors/josm/plugins/opendata/src/org/geotools/data/shapefile/files/TabFiles.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/geotools/data/shapefile/files/TabFiles.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/geotools/data/shapefile/files/TabFiles.java	(revision 30738)
@@ -717,4 +717,5 @@
      *                 if a problem occurred opening the stream.
      */
+    @SuppressWarnings("resource")
     @Override
     public OutputStream getOutputStream(ShpFileType type,
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/NeptuneReader.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/NeptuneReader.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/NeptuneReader.java	(revision 30738)
@@ -4,5 +4,4 @@
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -54,5 +53,5 @@
 /**
  * NEPTUNE -> OSM converter
- * See http://www.chouette.mobi/IMG/pdf/NF__F_-Neptune-maj.pdf 
+ * See http://www.chouette.mobi/IMG/pdf/NF__F_-Neptune-maj.pdf
  */
 public class NeptuneReader extends AbstractReader implements FrenchConstants {
@@ -81,9 +80,9 @@
         schemas.add(NeptuneReader.class.getResource(NEPTUNE_XSD));
     }
-    
+
     private ChouettePTNetworkType root;
-    
+
     private final Map<String, OsmPrimitive> tridentObjects = new HashMap<>();
-    
+
     public static final boolean acceptsXmlNeptuneFile(File file) {
         return acceptsXmlNeptuneFile(file, null);
@@ -91,11 +90,10 @@
 
     public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) {
-        
+
         if (schemaURL == null) {
             schemaURL = schemas.get(0);
         }
-        
-        try {
-            FileInputStream in = new FileInputStream(file);
+
+        try (FileInputStream in = new FileInputStream(file)) {
             Source xmlFile = new StreamSource(in);
             try {
@@ -112,18 +110,12 @@
                 Main.error(xmlFile.getSystemId() + " is NOT valid");
                 Main.error("Reason: " + e.getLocalizedMessage());
-            } finally {
-                try {
-                    in.close();
-                } catch (IOException e) {
-                    // Ignore exception 
-                }
             }
-        } catch (FileNotFoundException e) {
+        } catch (IOException e) {
             Main.error(e.getMessage());
         }
-        
+
         return false;
     }
-    
+
     public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance) throws JAXBException {
         return new NeptuneReader().parse(in, instance);
@@ -138,5 +130,5 @@
         return doc.getValue();
     }
-    
+
     private final void linkTridentObjectToOsmPrimitive(TridentObjectType object, OsmPrimitive p) {
         p.put("ref:neptune", object.getObjectId());
@@ -151,5 +143,5 @@
         return n;
     }
-    
+
     private Node createPlatform(StopPointType stop) {
         Node n = createNode(createLatLon(stop));
@@ -181,5 +173,5 @@
         return r;
     }
-    
+
     protected Relation createNetwork(PTNetworkType network) {
         Relation r = createRelation(OSM_NETWORK);
@@ -188,5 +180,5 @@
         return r;
     }
-    
+
     protected Relation createRouteMaster(LineType line) {
         Relation r = createPtRelation(OSM_ROUTE_MASTER, line);
@@ -219,5 +211,5 @@
         return r;
     }
-    
+
     protected Relation createStopArea(StopAreaType sa) {
         Relation r = createPtRelation(OSM_STOP_AREA, sa);
@@ -225,9 +217,9 @@
         return r;
     }
-    
+
     protected LatLon createLatLon(PointType point) {
         return new LatLon(point.getLatitude().doubleValue(), point.getLongitude().doubleValue());
     }
-    
+
     protected final <T extends TridentObjectType> T findTridentObject(List<T> list, String id) {
         for (T object : list) {
@@ -238,5 +230,5 @@
         return null;
     }
-    
+
     protected StopPoint findStopPoint(String id) {
         return findTridentObject(root.getChouetteLineDescription().getStopPoint(), id);
@@ -311,5 +303,5 @@
                             }
                         }
-                        
+
                     } else if (childId.contains("StopPoint")) {
                         StopPoint child = findStopPoint(childId);
@@ -352,5 +344,5 @@
                         addStopToRoute(route, start);
                     }
-                    
+
                     if (end == null) {
                         System.err.println("Cannot find end StopPoint: "+ptlink.getEndOfLink());
@@ -361,8 +353,8 @@
             }
         }
-        
+
         return ds;
     }
-        
+
     private static final boolean addStopToRoute(Relation route, OsmPrimitive stop) {
         if (route.getMembersCount() == 0 || !route.getMember(route.getMembersCount()-1).getMember().equals(stop) ) {
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/SevenZipReader.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/SevenZipReader.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/SevenZipReader.java	(revision 30738)
@@ -33,5 +33,5 @@
 
     private final IInArchive archive = new Handler();
-    
+
     public SevenZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) throws IOException {
         super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser);
@@ -41,22 +41,22 @@
             Utils.copyStream(in, out);
         }
-        IInStream random = new MyRandomAccessFile(tmpFile.getPath(), "r");
-        if (archive.Open(random) != 0) {
-            String message = "Unable to open 7z archive: "+tmpFile.getPath();
-            Main.warn(message);
-            random.close();
-            if (!tmpFile.delete()) {
-                tmpFile.deleteOnExit();
+        try (IInStream random = new MyRandomAccessFile(tmpFile.getPath(), "r")) {
+            if (archive.Open(random) != 0) {
+                String message = "Unable to open 7z archive: "+tmpFile.getPath();
+                Main.warn(message);
+                if (!tmpFile.delete()) {
+                    tmpFile.deleteOnExit();
+                }
+                throw new IOException(message);
             }
-            throw new IOException(message);
         }
     }
-    
-    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
+
+    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
             throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
         return new SevenZipReader(in, handler, promptUser).parseDoc(instance);
     }
 
-    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
+    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
             throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
         return new SevenZipReader(in, handler, promptUser).parseDocs(instance);
@@ -71,8 +71,8 @@
         archive.Extract(null, -1, IInArchive.NExtract_NAskMode_kExtract, new ExtractCallback(archive, temp, candidates));
     }
-    
+
     private class ExtractCallback extends ArchiveExtractCallback {
         private final List<File> candidates;
-        
+
         public ExtractCallback(IInArchive archive, File tempDir, List<File> candidates) {
             Init(archive);
@@ -81,5 +81,5 @@
         }
 
-        @Override 
+        @Override
         public int GetStream(int index, OutputStream[] outStream, int askExtractMode) throws IOException {
             int res = super.GetStream(index, outStream, askExtractMode);
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/ZipReader.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/ZipReader.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/ZipReader.java	(revision 30738)
@@ -26,7 +26,7 @@
 
     private final ZipInputStream zis;
-    
+
     private ZipEntry entry;
-    
+
     public ZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) {
         super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser);
@@ -34,14 +34,15 @@
     }
 
-    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
+    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
             throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
         return new ZipReader(in, handler, promptUser).parseDoc(instance);
     }
 
-    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
+    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
             throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
         return new ZipReader(in, handler, promptUser).parseDocs(instance);
     }
 
+    @Override
     protected void extractArchive(final File temp, final List<File> candidates) throws IOException, FileNotFoundException {
         while ((entry = zis.getNextEntry()) != null) {
@@ -58,15 +59,15 @@
             }
             if (!entry.isDirectory()) {
-                if (!file.createNewFile()) { 
+                if (!file.createNewFile()) {
                     throw new IOException("Could not create temp file: " + file.getAbsolutePath());
                 }
                 // Write temp file
-                FileOutputStream fos = new FileOutputStream(file);
-                byte[] buffer = new byte[8192];
-                int count = 0;
-                while ((count = zis.read(buffer, 0, buffer.length)) > 0) {
-                    fos.write(buffer, 0, count);
+                try (FileOutputStream fos = new FileOutputStream(file)) {
+                    byte[] buffer = new byte[8192];
+                    int count = 0;
+                    while ((count = zis.read(buffer, 0, buffer.length)) > 0) {
+                        fos.write(buffer, 0, count);
+                    }
                 }
-                fos.close();
                 // Allow handler to perform specific treatments (for example, fix invalid .prj files)
                 if (archiveHandler != null) {
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/tabular/CsvImporter.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/tabular/CsvImporter.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/tabular/CsvImporter.java	(revision 30738)
@@ -18,10 +18,10 @@
 
 public class CsvImporter extends AbstractImporter {
-    
+
     public static final ExtensionFileFilter CSV_FILE_FILTER = new ExtensionFileFilter(
             OdConstants.CSV_EXT, OdConstants.CSV_EXT, tr("CSV files") + " (*."+OdConstants.CSV_EXT+")");
-    
+
     public static final String COLOMBUS_HEADER = "INDEX,TAG,DATE,TIME,LATITUDE N/S,LONGITUDE E/W,HEIGHT,SPEED,HEADING,FIX MODE,VALID,PDOP,HDOP,VDOP,VOX";
-    
+
     public CsvImporter() {
         super(CSV_FILE_FILTER);
@@ -46,12 +46,7 @@
         boolean result = false;
         if (file != null && file.isFile()) {
-            try {
-                BufferedReader reader = new BufferedReader(new FileReader(file));
-                try {
-                    String line = reader.readLine();
-                    result = line != null && line.equalsIgnoreCase(COLOMBUS_HEADER);
-                } finally {
-                    reader.close();
-                }
+            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
+                String line = reader.readLine();
+                result = line != null && line.equalsIgnoreCase(COLOMBUS_HEADER);
             } catch (IOException e) {
                 // Ignore exceptions
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ModuleInformation.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ModuleInformation.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ModuleInformation.java	(revision 30738)
@@ -73,9 +73,8 @@
         this.name = name;
         this.file = file;
-        FileInputStream fis = null;
-        JarInputStream jar = null;
-        try {
-            fis = new FileInputStream(file);
-            jar = new JarInputStream(fis);
+        try (
+            FileInputStream fis = new FileInputStream(file);
+            JarInputStream jar = new JarInputStream(fis);
+        ) {
             Manifest manifest = jar.getManifest();
             if (manifest == null)
@@ -85,15 +84,4 @@
         } catch (IOException e) {
             throw new ModuleException(name, e);
-        } finally {
-            if (jar != null) {
-                try {
-                    jar.close();
-                } catch(IOException e) { /* ignore */ }
-            }
-            if (fis != null) {
-                try {
-                    fis.close();
-                } catch(IOException e) { /* ignore */ }
-            }
         }
     }
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ReadRemoteModuleInformationTask.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ReadRemoteModuleInformationTask.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ReadRemoteModuleInformationTask.java	(revision 30738)
@@ -25,4 +25,5 @@
 import java.util.List;
 
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.Version;
 import org.openstreetmap.josm.gui.PleaseWaitRunnable;
@@ -246,24 +247,20 @@
      */
     protected void cacheModuleList(String site, String list) {
-        PrintWriter writer = null;
         try {
             File moduleDir = OdPlugin.getInstance().getModulesDirectory();
             if (!moduleDir.exists()) {
                 if (! moduleDir.mkdirs()) {
-                    System.err.println(tr("Warning: failed to create module directory ''{0}''. Cannot cache module list from module site ''{1}''.", moduleDir.toString(), site));
+                    Main.warn(tr("Warning: failed to create module directory ''{0}''. Cannot cache module list from module site ''{1}''.",
+                            moduleDir.toString(), site));
                 }
             }
             File cacheFile = createSiteCacheFile(moduleDir, site, CacheType.PLUGIN_LIST);
             getProgressMonitor().subTask(tr("Writing module list to local cache ''{0}''", cacheFile.toString()));
-            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), "utf-8"));
-            writer.write(list);
+            try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), "utf-8"))) {
+                writer.write(list);
+            }
         } catch (IOException e) {
             // just failed to write the cache file. No big deal, but log the exception anyway
-            e.printStackTrace();
-        } finally {
-            if (writer != null) {
-                writer.flush();
-                writer.close();
-            }
+            Main.warn(e);
         }
     }
@@ -300,4 +297,5 @@
             File [] f = new File(location).listFiles(
                     new FilenameFilter() {
+                        @Override
                         public boolean accept(File dir, String name) {
                             return name.matches("^([0-9]+-)?site.*\\.txt$") ||
Index: applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/util/NamesFrUtils.java
===================================================================
--- applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/util/NamesFrUtils.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/util/NamesFrUtils.java	(revision 30738)
@@ -11,4 +11,5 @@
 
 import org.apache.commons.lang3.text.WordUtils;
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.osm.OsmPrimitive;
 import org.openstreetmap.josm.plugins.opendata.core.OdConstants;
@@ -16,5 +17,5 @@
 
 public abstract class NamesFrUtils {
-    
+
     private static Map<String, String> dictionary = initDictionary();
 
@@ -29,10 +30,9 @@
         return result;
     }
-    
+
     private static Map<String, String> initDictionary() {
         Map<String, String> result = new HashMap<>();
-        try {
-            BufferedReader reader = new BufferedReader(new InputStreamReader(
-                    SimpleDataSetHandler.class.getResourceAsStream(OdConstants.DICTIONARY_FR), OdConstants.UTF8));
+        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
+                SimpleDataSetHandler.class.getResourceAsStream(OdConstants.DICTIONARY_FR), OdConstants.UTF8))) {
             String line = reader.readLine(); // Skip first line
             while ((line = reader.readLine()) != null) {
@@ -40,7 +40,6 @@
                 result.put(tab[0].replace("\"", ""), tab[1].replace("\"", ""));
             }
-            reader.close();
         } catch (IOException e) {
-            e.printStackTrace();
+            Main.error(e);
         }
         return result;
@@ -170,5 +169,5 @@
             if (value != null) {
                 value = WordUtils.capitalizeFully(value);
-                // Cas particuliers 
+                // Cas particuliers
                 if (value.equals("Boulingrin")) { // square Boulingrin, mal formé
                     value = "Sq Boulingrin";
Index: applications/editors/josm/plugins/opendata/util/opendata/ModuleListGenerator.java
===================================================================
--- applications/editors/josm/plugins/opendata/util/opendata/ModuleListGenerator.java	(revision 30737)
+++ applications/editors/josm/plugins/opendata/util/opendata/ModuleListGenerator.java	(revision 30738)
@@ -15,4 +15,6 @@
 import java.util.zip.ZipOutputStream;
 
+import org.openstreetmap.josm.Main;
+
 public class ModuleListGenerator {
 
@@ -26,7 +28,8 @@
 			baseDir = args[0];
 		}
-		try {
+		try (
 			BufferedWriter list = new BufferedWriter(new FileWriter(baseDir+"modules.txt"));
 			ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(baseDir+"modules-icons.zip"));
+		) {
 			for (File file : new File(baseDir+"dist").listFiles(new FilenameFilter() {
 				@Override
@@ -37,5 +40,5 @@
 				try {
 					String filename = file.getName();
-					System.out.println("Processing "+filename);
+					Main.info("Processing "+filename);
 					list.write(filename+";"+url+filename); list.newLine();
 					Manifest mf = new JarFile(file).getManifest();
@@ -77,5 +80,5 @@
 									}
 								} catch (IOException e) {
-									System.err.println("Cannot load Image-Icon: "+value.toString());
+									Main.error("Cannot load Image-Icon: "+value.toString());
 								} finally {
 									zip.closeEntry();
@@ -84,14 +87,11 @@
 						}
 					}
-					
+
 				} catch (IOException e) {
-					e.printStackTrace();
+				    Main.error(e);
 				}
 			}
-			System.out.println("Done");
-			zip.close();
-			list.close();
 		} catch (IOException e) {
-			e.printStackTrace();
+			Main.error(e);
 		}
 	}
Index: applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java
===================================================================
--- applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java	(revision 30738)
@@ -54,10 +54,10 @@
 
         @Override
-		public void actionPerformed(ActionEvent e) {
+        public void actionPerformed(ActionEvent e) {
             DataSet ds = Main.main.getCurrentDataSet();
             if (ds == null) {
                 return;
             }
-            
+
             // get all stuff visible on screen
             LatLon bottomLeft = Main.map.mapView.getLatLon(0,Main.map.mapView.getHeight());
@@ -67,14 +67,13 @@
             try {
                 writeGenerated(b);
-            } catch(Exception ex) {
-                //how handle the exception?
-            }
-
+            } catch (Exception ex) {
+                // how handle the exception?
+            	Main.error(ex);
+            }
 
             String firefox = Main.pref.get("osmarender.firefox", "firefox");
-            try {
+            try (OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(new OutputStreamWriter(
+                    new FileOutputStream(getPluginDir()+File.separator+"data.osm"), "UTF-8")), false, "0.6")) {
                 // write to plugin dir
-                OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(new OutputStreamWriter(
-                        new FileOutputStream(getPluginDir()+File.separator+"data.osm"), "UTF-8")), false, "0.6");
                 w.header();
 
@@ -116,5 +115,5 @@
 
                 // get the exec line
-                String argument; 
+                String argument;
                 if (Main.platform instanceof PlatformHookWindows)
                     argument = "file:///"+getPluginDir().replace('\\','/').replace(" ","%20")+File.separator+"generated.xml\"";
@@ -198,27 +197,25 @@
             "maxlon=\"" + b.getMax().lon() + "\" " + "/>";
 
-        BufferedReader reader = new BufferedReader(
-                new FileReader( getPluginDir() + File.separator + "osm-map-features.xml") );
-        PrintWriter writer = new PrintWriter( getPluginDir() + File.separator + "generated.xml", "UTF-8");
-
-        // osm-map-features.xml contain two placemark
-        // (bounds_mkr1 and bounds_mkr2). We write the bounds tag
-        // between the two
-        String str = null;
-        while( (str = reader.readLine()) != null ) {
-            if(str.contains("<!--bounds_mkr1-->")) {
-                writer.println(str);
-                writer.println("    " + bounds_tag);
-                while(!str.contains("<!--bounds_mkr2-->")) {
-                    str = reader.readLine();
-                }
-                writer.println(str);
-            } else {
-                writer.println(str);
-            }
-        }
-
-        writer.close();
-        reader.close();
+        try (
+            BufferedReader reader = new BufferedReader(
+                    new FileReader( getPluginDir() + File.separator + "osm-map-features.xml") );
+            PrintWriter writer = new PrintWriter( getPluginDir() + File.separator + "generated.xml", "UTF-8");
+        ) {
+            // osm-map-features.xml contain two placemark
+            // (bounds_mkr1 and bounds_mkr2). We write the bounds tag between the two
+            String str = null;
+            while( (str = reader.readLine()) != null ) {
+                if(str.contains("<!--bounds_mkr1-->")) {
+                    writer.println(str);
+                    writer.println("    " + bounds_tag);
+                    while(!str.contains("<!--bounds_mkr2-->")) {
+                        str = reader.readLine();
+                    }
+                    writer.println(str);
+                } else {
+                    writer.println(str);
+                }
+            }
+        }
     }
 }
Index: applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/ExifGPSTagger.java
===================================================================
--- applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/ExifGPSTagger.java	(revision 30737)
+++ applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/ExifGPSTagger.java	(revision 30738)
@@ -8,5 +8,4 @@
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
 import java.text.DecimalFormat;
 import java.util.Calendar;
@@ -49,97 +48,81 @@
     }
 
-    public static void setExifGPSTagWorker(File jpegImageFile, File dst, double lat, double lon, long gpsTime, Double ele) throws IOException,
-            ImageReadException, ImageWriteException
-    {
-        OutputStream os = null;
-        try {
-            TiffOutputSet outputSet = null;
+    public static void setExifGPSTagWorker(File jpegImageFile, File dst, double lat, double lon, long gpsTime, Double ele)
+            throws IOException, ImageReadException, ImageWriteException {
+        TiffOutputSet outputSet = null;
 
-            IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
-            JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
-            if (null != jpegMetadata) {
-                TiffImageMetadata exif = jpegMetadata.getExif();
+        IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
+        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
+        if (null != jpegMetadata) {
+            TiffImageMetadata exif = jpegMetadata.getExif();
 
-                if (null != exif) {
-                    outputSet = exif.getOutputSet();
-                }
+            if (null != exif) {
+                outputSet = exif.getOutputSet();
             }
+        }
 
-            if (null == outputSet) {
-                outputSet = new TiffOutputSet();
-            }
+        if (null == outputSet) {
+            outputSet = new TiffOutputSet();
+        }
 
-            Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+        Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
 
-            calendar.setTimeInMillis(gpsTime);
+        calendar.setTimeInMillis(gpsTime);
 
-            final int year =   calendar.get(Calendar.YEAR);
-            final int month =  calendar.get(Calendar.MONTH) + 1;
-            final int day =    calendar.get(Calendar.DAY_OF_MONTH);
-            final int hour =   calendar.get(Calendar.HOUR_OF_DAY);
-            final int minute = calendar.get(Calendar.MINUTE);
-            final int second = calendar.get(Calendar.SECOND);
+        final int year =   calendar.get(Calendar.YEAR);
+        final int month =  calendar.get(Calendar.MONTH) + 1;
+        final int day =    calendar.get(Calendar.DAY_OF_MONTH);
+        final int hour =   calendar.get(Calendar.HOUR_OF_DAY);
+        final int minute = calendar.get(Calendar.MINUTE);
+        final int second = calendar.get(Calendar.SECOND);
 
-            DecimalFormat yearFormatter = new DecimalFormat("0000");
-            DecimalFormat monthFormatter = new DecimalFormat("00");
-            DecimalFormat dayFormatter = new DecimalFormat("00");
+        DecimalFormat yearFormatter = new DecimalFormat("0000");
+        DecimalFormat monthFormatter = new DecimalFormat("00");
+        DecimalFormat dayFormatter = new DecimalFormat("00");
 
-            final String yearStr = yearFormatter.format(year);
-            final String monthStr = monthFormatter.format(month);
-            final String dayStr = dayFormatter.format(day);
-            final String dateStamp = yearStr+":"+monthStr+":"+dayStr;
-            //System.err.println("date: "+dateStamp+"  h/m/s: "+hour+"/"+minute+"/"+second);
+        final String yearStr = yearFormatter.format(year);
+        final String monthStr = monthFormatter.format(month);
+        final String dayStr = dayFormatter.format(day);
+        final String dateStamp = yearStr+":"+monthStr+":"+dayStr;
+        //System.err.println("date: "+dateStamp+"  h/m/s: "+hour+"/"+minute+"/"+second);
 
-            Double[] timeStamp = {new Double(hour), new Double(minute), new Double(second)};
-            TiffOutputField gpsTimeStamp = TiffOutputField.create(
-                    GPSTagConstants.GPS_TAG_GPS_TIME_STAMP,
-                    outputSet.byteOrder, timeStamp);
-            TiffOutputDirectory exifDirectory = outputSet.getOrCreateGPSDirectory();
-            // make sure to remove old value if present (this method will
-            // not fail if the tag does not exist).
-            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_TIME_STAMP);
-            exifDirectory.add(gpsTimeStamp);
+        Double[] timeStamp = {new Double(hour), new Double(minute), new Double(second)};
+        TiffOutputField gpsTimeStamp = TiffOutputField.create(
+                GPSTagConstants.GPS_TAG_GPS_TIME_STAMP,
+                outputSet.byteOrder, timeStamp);
+        TiffOutputDirectory exifDirectory = outputSet.getOrCreateGPSDirectory();
+        // make sure to remove old value if present (this method will
+        // not fail if the tag does not exist).
+        exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_TIME_STAMP);
+        exifDirectory.add(gpsTimeStamp);
 
-            TiffOutputField gpsDateStamp = SanselanFixes.create(
-                    GPSTagConstants.GPS_TAG_GPS_DATE_STAMP,
-                    outputSet.byteOrder, dateStamp);
-            // make sure to remove old value if present (this method will
-            // not fail if the tag does not exist).
-            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_DATE_STAMP);
-            exifDirectory.add(gpsDateStamp);
+        TiffOutputField gpsDateStamp = SanselanFixes.create(
+                GPSTagConstants.GPS_TAG_GPS_DATE_STAMP,
+                outputSet.byteOrder, dateStamp);
+        // make sure to remove old value if present (this method will
+        // not fail if the tag does not exist).
+        exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_DATE_STAMP);
+        exifDirectory.add(gpsDateStamp);
 
-            SanselanFixes.setGPSInDegrees(outputSet, lon, lat);
+        SanselanFixes.setGPSInDegrees(outputSet, lon, lat);
 
-            if (ele != null) {
-                byte eleRef =  ele >= 0 ? (byte) 0 : (byte) 1;
-                TiffOutputField gpsAltitudeRef = new TiffOutputField(
-                        GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF,
-                        FieldType.FIELD_TYPE_BYTE, 1, new byte[] { eleRef });
-                exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
-                exifDirectory.add(gpsAltitudeRef);
+        if (ele != null) {
+            byte eleRef =  ele >= 0 ? (byte) 0 : (byte) 1;
+            TiffOutputField gpsAltitudeRef = new TiffOutputField(
+                    GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF,
+                    FieldType.FIELD_TYPE_BYTE, 1, new byte[] { eleRef });
+            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
+            exifDirectory.add(gpsAltitudeRef);
 
-                Number[] val = new Number[] { Math.abs(ele) };
-                byte[] bytes = FieldType.FIELD_TYPE_RATIONAL.writeData(val, outputSet.byteOrder);
-                TiffOutputField gpsAltitude = new TiffOutputField(
-                        GPSTagConstants.GPS_TAG_GPS_ALTITUDE,
-                        FieldType.FIELD_TYPE_RATIONAL, 1, bytes);
-                exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE);
-                exifDirectory.add(gpsAltitude);
-            }
-
-            os = new FileOutputStream(dst);
-            os = new BufferedOutputStream(os);
-
-            new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
-                    outputSet);
-
-            os.close();
-            os = null;
-        } finally {
-            if (os != null) {
-                try {
-                    os.close();
-                } catch (IOException e) {}
-            }
+            Number[] val = new Number[] { Math.abs(ele) };
+            byte[] bytes = FieldType.FIELD_TYPE_RATIONAL.writeData(val, outputSet.byteOrder);
+            TiffOutputField gpsAltitude = new TiffOutputField(
+                    GPSTagConstants.GPS_TAG_GPS_ALTITUDE,
+                    FieldType.FIELD_TYPE_RATIONAL, 1, bytes);
+            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE);
+            exifDirectory.add(gpsAltitude);
+        }
+        try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst))) {
+            new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
         }
     }
Index: applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/layer/PicLayerFromFile.java
===================================================================
--- applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/layer/PicLayerFromFile.java	(revision 30737)
+++ applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/layer/PicLayerFromFile.java	(revision 30738)
@@ -74,8 +74,5 @@
 
         if (isZip) {
-            ZipFile zipFile = null;
-            try
-            {
-                zipFile = new ZipFile(m_file);
+            try (ZipFile zipFile = new ZipFile(m_file)) {
                 ZipEntry imgEntry = null;
                 Enumeration<? extends ZipEntry> entries = zipFile.entries();
@@ -103,11 +100,4 @@
                 System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
                 return null;
-            } finally {
-                if (zipFile != null) {
-                    try {
-                        zipFile.close();
-                    } catch (IOException ex) {
-                    }
-                }
             }
         } else {
@@ -149,8 +139,5 @@
 
         if (isZip) {
-            ZipFile zipFile = null;
-            try
-            {
-                zipFile = new ZipFile(m_file);
+            try (ZipFile zipFile = new ZipFile(m_file)) {
                 String calFileStr = imgNameInZip + CalibrationFileFilter.EXTENSION;
                 ZipEntry calEntry = zipFile.getEntry(calFileStr);
@@ -183,13 +170,6 @@
                 }
             } catch (Exception e) {
-                System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
+                Main.warn(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
                 return;
-            } finally {
-                if (zipFile != null) {
-                    try {
-                        zipFile.close();
-                    } catch (IOException ex) {
-                    }
-                }
             }
         } else {
Index: applications/editors/josm/plugins/poly/src/poly/PolyExporter.java
===================================================================
--- applications/editors/josm/plugins/poly/src/poly/PolyExporter.java	(revision 30737)
+++ applications/editors/josm/plugins/poly/src/poly/PolyExporter.java	(revision 30738)
@@ -25,5 +25,5 @@
 /**
  * Writes poly files.
- * 
+ *
  * @author zverik
  */
@@ -37,6 +37,5 @@
     public void exportData( File file, Layer layer ) throws IOException {
         if( layer instanceof OsmDataLayer ) {
-            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
-            try {
+            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"))) {
                 DataSet ds = ((OsmDataLayer)layer).data;
                 Map<Way, Boolean> ways = new TreeMap<>();
@@ -71,6 +70,4 @@
                 writer.write("END");
                 writer.newLine();
-            } finally {
-                writer.close();
             }
         }
Index: applications/editors/josm/plugins/poly/src/poly/PolyImporter.java
===================================================================
--- applications/editors/josm/plugins/poly/src/poly/PolyImporter.java	(revision 30737)
+++ applications/editors/josm/plugins/poly/src/poly/PolyImporter.java	(revision 30738)
@@ -1,3 +1,5 @@
 package poly;
+
+import static org.openstreetmap.josm.tools.I18n.tr;
 
 import java.io.BufferedReader;
@@ -7,9 +9,9 @@
 import java.util.ArrayList;
 import java.util.List;
+
 import javax.swing.JOptionPane;
+
 import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.coor.LatLon;
-
-import static org.openstreetmap.josm.tools.I18n.tr;
 import org.openstreetmap.josm.data.osm.DataSet;
 import org.openstreetmap.josm.data.osm.Node;
@@ -19,6 +21,6 @@
 import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
 import org.openstreetmap.josm.gui.progress.ProgressMonitor;
+import org.openstreetmap.josm.io.CachedFile;
 import org.openstreetmap.josm.io.IllegalDataException;
-import org.openstreetmap.josm.io.CachedFile;
 import org.openstreetmap.josm.io.OsmImporter;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
@@ -44,13 +46,11 @@
             progressMonitor = NullProgressMonitor.INSTANCE;
         CheckParameterUtil.ensureParameterNotNull(in, "in");
-        BufferedReader reader = null;
-
-        try {
+
+        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8"))) {
             progressMonitor.beginTask(tr("Reading polygon filter file..."), 2);
             progressMonitor.indeterminateSubTask(tr("Reading polygon filter file..."));
-            reader = new BufferedReader(new InputStreamReader(in, "UTF8"));
             List<Area> areas = loadPolygon(reader);
             progressMonitor.worked(1);
-            
+
             progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
             DataSet ds = constructDataSet(areas);
@@ -60,12 +60,8 @@
             throw new IllegalDataException(tr("Error reading poly file: {0}", e.getMessage()), e);
         } finally {
-            try {
-                if( reader != null )
-                    reader.close();
-            } catch( IOException e ) { }
             progressMonitor.finishTask();
         }
     }
-    
+
     private List<Area> loadPolygon( BufferedReader reader ) throws IllegalDataException, IOException {
         String name = reader.readLine();
@@ -145,5 +141,5 @@
         DataSet ds = new DataSet();
         ds.setUploadDiscouraged(true);
-        
+
         boolean foundInner = false;
         for( Area area : areas ) {
Index: applications/editors/josm/plugins/proj4j/src/org/openstreetmap/josm/plugins/proj4j/Proj4JProjectionChoice.java
===================================================================
--- applications/editors/josm/plugins/proj4j/src/org/openstreetmap/josm/plugins/proj4j/Proj4JProjectionChoice.java	(revision 30737)
+++ applications/editors/josm/plugins/proj4j/src/org/openstreetmap/josm/plugins/proj4j/Proj4JProjectionChoice.java	(revision 30738)
@@ -64,5 +64,5 @@
         sorter = new TableRowSorter<>(model);
     }
-    
+
     @Override
     public String getId() {
@@ -74,7 +74,7 @@
         return new Proj4JPanel(actionListener);
     }
-    
+
     protected class Proj4JPanel extends JPanel {
-        
+
         public Proj4JPanel(ActionListener actionListener) {
             GridBagConstraints c = new GridBagConstraints();
@@ -94,12 +94,15 @@
                     new DocumentListener() {
 
+                        @Override
                         public void insertUpdate(DocumentEvent e) {
                             newFilter();
                         }
 
+                        @Override
                         public void removeUpdate(DocumentEvent e) {
                             newFilter();
                         }
 
+                        @Override
                         public void changedUpdate(DocumentEvent e) {
                             newFilter();
@@ -213,4 +216,5 @@
         }
 
+        @Override
         public void valueChanged(ListSelectionEvent e) {
             updateSelectedCode();
@@ -258,15 +262,16 @@
         public CRSTableModel() throws java.io.IOException {
             // Read projection information from file, (authority, code, description)
-            InputStream inStr = getClass().getResourceAsStream("/resources/projections.txt");
-            BufferedReader fh = new BufferedReader(new InputStreamReader(inStr));
-
-            String s;
-            while ((s = fh.readLine()) != null) {
-                String f[] = s.split("\t");
-                if (f.length >= 3) {
-                    crsList.add(new CRSEntry(f[0], f[1], f[2]));
+            try (
+                InputStream inStr = getClass().getResourceAsStream("/resources/projections.txt");
+                BufferedReader fh = new BufferedReader(new InputStreamReader(inStr));
+            ) {
+                String s;
+                while ((s = fh.readLine()) != null) {
+                    String f[] = s.split("\t");
+                    if (f.length >= 3) {
+                        crsList.add(new CRSEntry(f[0], f[1], f[2]));
+                    }
                 }
             }
-            fh.close();
         }
 
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelation.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelation.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelation.java	(revision 30738)
@@ -150,6 +150,6 @@
                 }
             } else if( element.getType() == OsmPrimitiveType.RELATION ) {
-            	Color oldColor = g.getColor();
-            	g.setColor(Color.magenta);
+                Color oldColor = g.getColor();
+                g.setColor(Color.magenta);
                 drawRelations(g, mv, bbox, (Relation)element);
                 g.setColor(oldColor);
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelationListener.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelationListener.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelationListener.java	(revision 30738)
@@ -9,4 +9,4 @@
  */
 public interface ChosenRelationListener {
-	void chosenRelationChanged( Relation oldRelation, Relation newRelation );
+    void chosenRelationChanged( Relation oldRelation, Relation newRelation );
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/ExtraNameFormatHook.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/ExtraNameFormatHook.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/ExtraNameFormatHook.java	(revision 30738)
@@ -14,31 +14,31 @@
 
     public String checkRelationTypeName( IRelation relation, String defaultName ) {
-	return null;
+    return null;
     }
 
     public String checkFormat( INode node, String defaultName ) {
-	return null;
+    return null;
     }
 
     public String checkFormat( IWay way, String defaultName ) {
-	if( way.get("place") != null && way.get("name") == null && way.get("place_name") != null )
-	    return way.get("place_name") + " " + defaultName;
-	return null;
+    if( way.get("place") != null && way.get("name") == null && way.get("place_name") != null )
+        return way.get("place_name") + " " + defaultName;
+    return null;
     }
 
     public String checkFormat( IRelation relation, String defaultName ) {
-	String type = relation.get("type");
-	if( type != null ) {
-	    String name = relation.get("destination");
-	    if( type.equals("destination_sign") && name != null ) {
-		if( relation.get("distance") != null )
-		    name += " " + relation.get("distance");
-		if( defaultName.indexOf('"') < 0 )
-		    return '"' + name + "\" " + defaultName;
-		else
-		    return defaultName.replaceFirst("\".?+\"", '"'+name+'"');
-	    }
-	}
-	return null;
+    String type = relation.get("type");
+    if( type != null ) {
+        String name = relation.get("destination");
+        if( type.equals("destination_sign") && name != null ) {
+        if( relation.get("distance") != null )
+            name += " " + relation.get("distance");
+        if( defaultName.indexOf('"') < 0 )
+            return '"' + name + "\" " + defaultName;
+        else
+            return defaultName.replaceFirst("\".?+\"", '"'+name+'"');
+        }
+    }
+    return null;
     }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextDialog.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextDialog.java	(revision 30738)
@@ -97,5 +97,5 @@
 /**
  * The new, advanced relation editing panel.
- * 
+ *
  * @author Zverik
  */
@@ -103,5 +103,5 @@
 
     public final static String PREF_PREFIX = "reltoolbox";
-    
+
     private final DefaultTableModel relationsData;
     private ChosenRelation chosenRelation;
@@ -142,4 +142,5 @@
         roleBox.addMouseListener(relationMouseAdapter);
         roleBox.addItemListener(new ItemListener() {
+            @Override
             public void itemStateChanged( ItemEvent e ) {
                 if( e.getStateChange() == ItemEvent.DESELECTED ) return;
@@ -174,4 +175,5 @@
 
         roleBox.addPropertyChangeListener("enabled", new PropertyChangeListener() {
+            @Override
             public void propertyChange( PropertyChangeEvent evt ) {
                 boolean showRoleBox = roleBox.isEnabled();
@@ -182,4 +184,5 @@
 
         sortAndFixAction.addPropertyChangeListener(new PropertyChangeListener() {
+            @Override
             public void propertyChange( PropertyChangeEvent evt ) {
                 sortAndFixButton.setVisible(sortAndFixAction.isEnabled());
@@ -189,4 +192,5 @@
 
         downloadChosenRelationAction.addPropertyChangeListener(new PropertyChangeListener() {
+            @Override
             public void propertyChange( PropertyChangeEvent evt ) {
                 downloadButton.setVisible(downloadChosenRelationAction.isEnabled());
@@ -304,4 +308,5 @@
         columns.getColumn(0).setPreferredWidth(220);
         relationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+            @Override
             public void valueChanged( ListSelectionEvent e ) {
                 int selectedRow = relationsTable.getSelectedRow();
@@ -339,4 +344,5 @@
     }
 
+    @Override
     public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
         if( chosenRelationPanel != null && Main.pref.getBoolean(PREF_PREFIX + ".hidetopline", false) )
@@ -348,4 +354,5 @@
     }
 
+    @Override
     public void selectionChanged( Collection<? extends OsmPrimitive> newSelection ) {
         if( !isVisible() || relationsData == null )
@@ -397,4 +404,5 @@
     }
 
+    @Override
     public void editLayerChanged( OsmDataLayer oldLayer, OsmDataLayer newLayer ) {
         updateSelection();
@@ -410,5 +418,5 @@
         super.destroy();
     }
-    
+
     private static final String POSSIBLE_ROLES_FILE = "relcontext/possible_roles.txt";
     private static final Map<String, List<String>> possibleRoles = loadRoles();
@@ -416,8 +424,9 @@
     private static Map<String, List<String>> loadRoles() {
         Map<String, List<String>> result = new HashMap<>();
-        try {
-            ClassLoader classLoader = RelContextDialog.class.getClassLoader();
-            final InputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE);
+        ClassLoader classLoader = RelContextDialog.class.getClassLoader();
+        try (
+            InputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE);
             BufferedReader r = new BufferedReader(new InputStreamReader(possibleRolesStream));
+        ) {
             while( r.ready() ) {
                 String line = r.readLine();
@@ -431,8 +440,7 @@
                 }
             }
-            r.close();
         } catch( Exception e ) {
-            System.err.println("[RelToolbox] Error reading possible roles file.");
-            e.printStackTrace();
+            Main.error("[RelToolbox] Error reading possible roles file.");
+            Main.error(e);
         }
         return result;
@@ -466,4 +474,5 @@
 
         role.getEditor().addActionListener(new ActionListener() {
+            @Override
             public void actionPerformed( ActionEvent e ) {
                 dlg.setVisible(false);
@@ -589,4 +598,5 @@
         }
 
+        @Override
         public void actionPerformed( ActionEvent e ) {
             String property = e.getActionCommand();
@@ -609,4 +619,5 @@
         }
 
+        @Override
         public void actionPerformed( ActionEvent e ) {
             if( roleBoxModel.membersRole != null ) {
@@ -617,9 +628,10 @@
         }
 
+        @Override
         public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
             setEnabled(newRelation != null);
         }
     }
-        
+
     private class RoleComboBoxModel extends AbstractListModel<String> implements ComboBoxModel<String> {
         private List<String> roles = new ArrayList<>();
@@ -704,8 +716,10 @@
         }
 
+        @Override
         public int getSize() {
             return roles.size();
         }
 
+        @Override
         public String getElementAt( int index ) {
             return getRole(index);
@@ -716,4 +730,5 @@
         }
 
+        @Override
         public void setSelectedItem( Object anItem ) {
             int newIndex = anItem == null ? -1 : roles.indexOf(anItem);
@@ -724,4 +739,5 @@
         }
 
+        @Override
         public Object getSelectedItem() {
             return selectedIndex < 0 || selectedIndex >= getSize() ? null : getRole(selectedIndex);
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextPlugin.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextPlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextPlugin.java	(revision 30738)
@@ -11,5 +11,5 @@
     public RelContextPlugin( PluginInformation info ) {
         super(info);
-	DefaultNameFormatter.registerFormatHook(new ExtraNameFormatHook());
+    DefaultNameFormatter.registerFormatHook(new ExtraNameFormatHook());
     }
 
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/CreateMultipolygonAction.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/CreateMultipolygonAction.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/CreateMultipolygonAction.java	(revision 30738)
@@ -28,127 +28,127 @@
 
     public CreateMultipolygonAction( ChosenRelation chRel ) {
-	super("Multi", "data/multipolygon", tr("Create a multipolygon from selected objects"),
-		Shortcut.registerShortcut("reltoolbox:multipolygon", tr("Relation Toolbox: {0}", tr("Create multipolygon")),
-		KeyEvent.VK_A, Shortcut.ALT_CTRL), false);
-	this.chRel = chRel;
-	updateEnabledState();
+    super("Multi", "data/multipolygon", tr("Create a multipolygon from selected objects"),
+        Shortcut.registerShortcut("reltoolbox:multipolygon", tr("Relation Toolbox: {0}", tr("Create multipolygon")),
+        KeyEvent.VK_A, Shortcut.ALT_CTRL), false);
+    this.chRel = chRel;
+    updateEnabledState();
     }
 
     public CreateMultipolygonAction() {
-	this(null);
+    this(null);
     }
 
     public static boolean getDefaultPropertyValue( String property ) {
-	if( property.equals("boundary") )
-	    return false;
-	else if( property.equals("boundaryways") )
-	    return true;
-	else if( property.equals("tags") )
-	    return true;
-	else if( property.equals("alltags") )
-	    return false;
-	else if( property.equals("single") )
-	    return true;
-	else if( property.equals("allowsplit") )
-	    return false;
-	throw new IllegalArgumentException(property);
+    if( property.equals("boundary") )
+        return false;
+    else if( property.equals("boundaryways") )
+        return true;
+    else if( property.equals("tags") )
+        return true;
+    else if( property.equals("alltags") )
+        return false;
+    else if( property.equals("single") )
+        return true;
+    else if( property.equals("allowsplit") )
+        return false;
+    throw new IllegalArgumentException(property);
     }
 
     private boolean getPref( String property ) {
-	return Main.pref.getBoolean(PREF_MULTIPOLY + property, getDefaultPropertyValue(property));
+    return Main.pref.getBoolean(PREF_MULTIPOLY + property, getDefaultPropertyValue(property));
     }
 
     public void actionPerformed( ActionEvent e ) {
-	boolean isBoundary = getPref("boundary");
-	Collection<Way> selectedWays = getCurrentDataSet().getSelectedWays();
-	if( !isBoundary && getPref("tags") ) {
-	    List<Relation> rels = null;
-	    if( getPref("allowsplit") || selectedWays.size() == 1 ) {
-		if( SplittingMultipolygons.canProcess(selectedWays) )
-		    rels = SplittingMultipolygons.process(getCurrentDataSet().getSelectedWays());
-	    } else {
-		if( TheRing.areAllOfThoseRings(selectedWays) ) {
-		    List<Command> commands = new ArrayList<>();
-		    rels = TheRing.makeManySimpleMultipolygons(getCurrentDataSet().getSelectedWays(), commands);
-		    if( !commands.isEmpty() )
-			Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygons from rings"), commands));
-		}
-	    }
-	    if( rels != null && !rels.isEmpty() ) {
-		if( chRel != null )
-		    chRel.set(rels.size() == 1 ? rels.get(0) : null);
-		if( rels.size() == 1 )
-		    getCurrentDataSet().setSelected(rels);
-		else
-		    getCurrentDataSet().clearSelection();
-		return;
-	    }
-	}
-
-	// for now, just copying standard action
-	MultipolygonBuilder mpc = new MultipolygonBuilder();
-	String error = mpc.makeFromWays(getCurrentDataSet().getSelectedWays());
-	if( error != null ) {
-	    JOptionPane.showMessageDialog(Main.parent, error);
-	    return;
-	}
-	Relation rel = new Relation();
-	if( isBoundary ) {
-	    rel.put("type", "boundary");
-	    rel.put("boundary", "administrative");
-	} else
-	    rel.put("type", "multipolygon");
-	for( MultipolygonBuilder.JoinedPolygon poly : mpc.outerWays )
-	    for( Way w : poly.ways )
-		rel.addMember(new RelationMember("outer", w));
-	for( MultipolygonBuilder.JoinedPolygon poly : mpc.innerWays )
-	    for( Way w : poly.ways )
-		rel.addMember(new RelationMember("inner", w));
-	List<Command> list = removeTagsFromInnerWays(rel);
-	if( !list.isEmpty() && isBoundary ) {
-	    Main.main.undoRedo.add(new SequenceCommand(tr("Move tags from ways to relation"), list));
-	    list = new ArrayList<>();
-	}
-	if( isBoundary ) {
-	    if( !askForAdminLevelAndName(rel) )
-		return;
-	    addBoundaryMembers(rel);
-	    if( getPref("boundaryways") )
-		list.addAll(fixWayTagsForBoundary(rel));
-	}
-	list.add(new AddCommand(rel));
-	Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygon"), list));
-
-	if( chRel != null )
-	    chRel.set(rel);
-
-	getCurrentDataSet().setSelected(rel);
+    boolean isBoundary = getPref("boundary");
+    Collection<Way> selectedWays = getCurrentDataSet().getSelectedWays();
+    if( !isBoundary && getPref("tags") ) {
+        List<Relation> rels = null;
+        if( getPref("allowsplit") || selectedWays.size() == 1 ) {
+        if( SplittingMultipolygons.canProcess(selectedWays) )
+            rels = SplittingMultipolygons.process(getCurrentDataSet().getSelectedWays());
+        } else {
+        if( TheRing.areAllOfThoseRings(selectedWays) ) {
+            List<Command> commands = new ArrayList<>();
+            rels = TheRing.makeManySimpleMultipolygons(getCurrentDataSet().getSelectedWays(), commands);
+            if( !commands.isEmpty() )
+            Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygons from rings"), commands));
+        }
+        }
+        if( rels != null && !rels.isEmpty() ) {
+        if( chRel != null )
+            chRel.set(rels.size() == 1 ? rels.get(0) : null);
+        if( rels.size() == 1 )
+            getCurrentDataSet().setSelected(rels);
+        else
+            getCurrentDataSet().clearSelection();
+        return;
+        }
+    }
+
+    // for now, just copying standard action
+    MultipolygonBuilder mpc = new MultipolygonBuilder();
+    String error = mpc.makeFromWays(getCurrentDataSet().getSelectedWays());
+    if( error != null ) {
+        JOptionPane.showMessageDialog(Main.parent, error);
+        return;
+    }
+    Relation rel = new Relation();
+    if( isBoundary ) {
+        rel.put("type", "boundary");
+        rel.put("boundary", "administrative");
+    } else
+        rel.put("type", "multipolygon");
+    for( MultipolygonBuilder.JoinedPolygon poly : mpc.outerWays )
+        for( Way w : poly.ways )
+        rel.addMember(new RelationMember("outer", w));
+    for( MultipolygonBuilder.JoinedPolygon poly : mpc.innerWays )
+        for( Way w : poly.ways )
+        rel.addMember(new RelationMember("inner", w));
+    List<Command> list = removeTagsFromInnerWays(rel);
+    if( !list.isEmpty() && isBoundary ) {
+        Main.main.undoRedo.add(new SequenceCommand(tr("Move tags from ways to relation"), list));
+        list = new ArrayList<>();
+    }
+    if( isBoundary ) {
+        if( !askForAdminLevelAndName(rel) )
+        return;
+        addBoundaryMembers(rel);
+        if( getPref("boundaryways") )
+        list.addAll(fixWayTagsForBoundary(rel));
+    }
+    list.add(new AddCommand(rel));
+    Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygon"), list));
+
+    if( chRel != null )
+        chRel.set(rel);
+
+    getCurrentDataSet().setSelected(rel);
     }
 
     @Override
     protected void updateEnabledState() {
-	if( getCurrentDataSet() == null ) {
-	    setEnabled(false);
-	} else {
-	    updateEnabledState(getCurrentDataSet().getSelected());
-	}
+    if( getCurrentDataSet() == null ) {
+        setEnabled(false);
+    } else {
+        updateEnabledState(getCurrentDataSet().getSelected());
+    }
     }
 
     @Override
     protected void updateEnabledState( Collection<? extends OsmPrimitive> selection ) {
-	boolean isEnabled = true;
-	if( selection == null || selection.isEmpty() )
-	    isEnabled = false;
-	else {
-	    if( !getPref("boundary") ) {
-		for( OsmPrimitive p : selection ) {
-		    if( !(p instanceof Way) ) {
-			isEnabled = false;
-			break;
-		    }
-		}
-	    }
-	}
-	setEnabled(isEnabled);
+    boolean isEnabled = true;
+    if( selection == null || selection.isEmpty() )
+        isEnabled = false;
+    else {
+        if( !getPref("boundary") ) {
+        for( OsmPrimitive p : selection ) {
+            if( !(p instanceof Way) ) {
+            isEnabled = false;
+            break;
+            }
+        }
+        }
+    }
+    setEnabled(isEnabled);
     }
 
@@ -157,20 +157,20 @@
      */
     private void addBoundaryMembers( Relation rel ) {
-	for( OsmPrimitive p : getCurrentDataSet().getSelected() ) {
-	    String role = null;
-	    if( p.getType().equals(OsmPrimitiveType.RELATION) ) {
-		role = "subarea";
-	    } else if( p.getType().equals(OsmPrimitiveType.NODE) ) {
-		Node n = (Node)p;
-		if( !n.isIncomplete() ) {
-		    if( n.hasKey("place") )
-			role = "admin_centre";
-		    else
-			role = "label";
-		}
-	    }
-	    if( role != null )
-		rel.addMember(new RelationMember(role, p));
-	}
+    for( OsmPrimitive p : getCurrentDataSet().getSelected() ) {
+        String role = null;
+        if( p.getType().equals(OsmPrimitiveType.RELATION) ) {
+        role = "subarea";
+        } else if( p.getType().equals(OsmPrimitiveType.NODE) ) {
+        Node n = (Node)p;
+        if( !n.isIncomplete() ) {
+            if( n.hasKey("place") )
+            role = "admin_centre";
+            else
+            role = "label";
+        }
+        }
+        if( role != null )
+        rel.addMember(new RelationMember(role, p));
+    }
     }
 
@@ -179,50 +179,50 @@
      */
     private List<Command> fixWayTagsForBoundary( Relation rel ) {
-	List<Command> commands = new ArrayList<>();
-	if( !rel.hasKey("boundary") || !rel.hasKey("admin_level") )
-	    return commands;
-	String adminLevelStr = rel.get("admin_level");
-	int adminLevel = 0;
-	try {
-	    adminLevel = Integer.parseInt(adminLevelStr);
-	} catch( NumberFormatException e ) {
-	    return commands;
-	}
-	Set<OsmPrimitive> waysBoundary = new HashSet<>();
-	Set<OsmPrimitive> waysAdminLevel = new HashSet<>();
-	for( OsmPrimitive p : rel.getMemberPrimitives() ) {
-	    if( p instanceof Way ) {
-		int count = 0;
-		if( p.hasKey("boundary") && p.get("boundary").equals("administrative") )
-		    count++;
-		if( p.hasKey("admin_level") )
-		    count++;
-		if( p.keySet().size() - count == 0 ) {
-		    if( !p.hasKey("boundary") )
-			waysBoundary.add(p);
-		    if( !p.hasKey("admin_level") ) {
-			waysAdminLevel.add(p);
-		    } else {
-			try {
-			    int oldAdminLevel = Integer.parseInt(p.get("admin_level"));
-			    if( oldAdminLevel > adminLevel )
-				waysAdminLevel.add(p);
-			} catch( NumberFormatException e ) {
-			    waysAdminLevel.add(p); // some garbage, replace it
-			}
-		    }
-		}
-	    }
-	}
-	if( !waysBoundary.isEmpty() )
-	    commands.add(new ChangePropertyCommand(waysBoundary, "boundary", "administrative"));
-	if( !waysAdminLevel.isEmpty() )
-	    commands.add(new ChangePropertyCommand(waysAdminLevel, "admin_level", adminLevelStr));
-	return commands;
+    List<Command> commands = new ArrayList<>();
+    if( !rel.hasKey("boundary") || !rel.hasKey("admin_level") )
+        return commands;
+    String adminLevelStr = rel.get("admin_level");
+    int adminLevel = 0;
+    try {
+        adminLevel = Integer.parseInt(adminLevelStr);
+    } catch( NumberFormatException e ) {
+        return commands;
+    }
+    Set<OsmPrimitive> waysBoundary = new HashSet<>();
+    Set<OsmPrimitive> waysAdminLevel = new HashSet<>();
+    for( OsmPrimitive p : rel.getMemberPrimitives() ) {
+        if( p instanceof Way ) {
+        int count = 0;
+        if( p.hasKey("boundary") && p.get("boundary").equals("administrative") )
+            count++;
+        if( p.hasKey("admin_level") )
+            count++;
+        if( p.keySet().size() - count == 0 ) {
+            if( !p.hasKey("boundary") )
+            waysBoundary.add(p);
+            if( !p.hasKey("admin_level") ) {
+            waysAdminLevel.add(p);
+            } else {
+            try {
+                int oldAdminLevel = Integer.parseInt(p.get("admin_level"));
+                if( oldAdminLevel > adminLevel )
+                waysAdminLevel.add(p);
+            } catch( NumberFormatException e ) {
+                waysAdminLevel.add(p); // some garbage, replace it
+            }
+            }
+        }
+        }
+    }
+    if( !waysBoundary.isEmpty() )
+        commands.add(new ChangePropertyCommand(waysBoundary, "boundary", "administrative"));
+    if( !waysAdminLevel.isEmpty() )
+        commands.add(new ChangePropertyCommand(waysAdminLevel, "admin_level", adminLevelStr));
+    return commands;
     }
     static public final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList(new String[] {"barrier", "source"});
     private static final Set<String> REMOVE_FROM_BOUNDARY_TAGS = new TreeSet<>(Arrays.asList(new String[] {
-		"boundary", "boundary_type", "type", "admin_level"
-	    }));
+        "boundary", "boundary_type", "type", "admin_level"
+        }));
 
     /**
@@ -232,112 +232,112 @@
      */
     private List<Command> removeTagsFromInnerWays( Relation relation ) {
-	Map<String, String> values = new HashMap<>();
-
-	if( relation.hasKeys() ) {
-	    for( String key : relation.keySet() ) {
-		values.put(key, relation.get(key));
-	    }
-	}
-
-	List<Way> innerWays = new ArrayList<>();
-	List<Way> outerWays = new ArrayList<>();
-
-	Set<String> conflictingKeys = new TreeSet<>();
-
-	for( RelationMember m : relation.getMembers() ) {
-
-	    if( m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
-		innerWays.add(m.getWay());
-	    }
-
-	    if( m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
-		Way way = m.getWay();
-		outerWays.add(way);
-		for( String key : way.keySet() ) {
-		    if( !values.containsKey(key) ) { //relation values take precedence
-			values.put(key, way.get(key));
-		    } else if( !relation.hasKey(key) && !values.get(key).equals(way.get(key)) ) {
-			conflictingKeys.add(key);
-		    }
-		}
-	    }
-	}
-
-	// filter out empty key conflicts - we need second iteration
-	boolean isBoundary = getPref("boundary");
-	if( isBoundary || !getPref("alltags") )
-	    for( RelationMember m : relation.getMembers() )
-		if( m.hasRole() && m.getRole().equals("outer") && m.isWay() )
-		    for( String key : values.keySet() )
-			if( !m.getWay().hasKey(key) && !relation.hasKey(key) )
-			    conflictingKeys.add(key);
-
-	for( String key : conflictingKeys )
-	    values.remove(key);
-
-	for( String linearTag : Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", DEFAULT_LINEAR_TAGS) )
-	    values.remove(linearTag);
-
-	if( values.containsKey("natural") && values.get("natural").equals("coastline") )
-	    values.remove("natural");
-
-	String name = values.get("name");
-	if( isBoundary ) {
-	    Set<String> keySet = new TreeSet<>(values.keySet());
-	    for( String key : keySet )
-		if( !REMOVE_FROM_BOUNDARY_TAGS.contains(key) )
-		    values.remove(key);
-	}
-
-	values.put("area", "yes");
-
-	List<Command> commands = new ArrayList<>();
-	boolean moveTags = getPref("tags");
-
-	for( String key : values.keySet() ) {
-	    List<OsmPrimitive> affectedWays = new ArrayList<>();
-	    String value = values.get(key);
-
-	    for( Way way : innerWays ) {
-		if( way.hasKey(key) && (isBoundary || value.equals(way.get(key))) ) {
-		    affectedWays.add(way);
-		}
-	    }
-
-	    if( moveTags ) {
-		// remove duplicated tags from outer ways
-		for( Way way : outerWays ) {
-		    if( way.hasKey(key) ) {
-			affectedWays.add(way);
-		    }
-		}
-	    }
-
-	    if( affectedWays.size() > 0 ) {
-		commands.add(new ChangePropertyCommand(affectedWays, key, null));
-	    }
-	}
-
-	if( moveTags ) {
-	    // add those tag values to the relation
-	    if( isBoundary )
-		values.put("name", name);
-	    boolean fixed = false;
-	    Relation r2 = new Relation(relation);
-	    for( String key : values.keySet() ) {
-		if( !r2.hasKey(key) && !key.equals("area")
-			&& (!isBoundary || key.equals("admin_level") || key.equals("name")) ) {
-		    if( relation.isNew() )
-			relation.put(key, values.get(key));
-		    else
-			r2.put(key, values.get(key));
-		    fixed = true;
-		}
-	    }
-	    if( fixed && !relation.isNew() )
-		commands.add(new ChangeCommand(relation, r2));
-	}
-
-	return commands;
+    Map<String, String> values = new HashMap<>();
+
+    if( relation.hasKeys() ) {
+        for( String key : relation.keySet() ) {
+        values.put(key, relation.get(key));
+        }
+    }
+
+    List<Way> innerWays = new ArrayList<>();
+    List<Way> outerWays = new ArrayList<>();
+
+    Set<String> conflictingKeys = new TreeSet<>();
+
+    for( RelationMember m : relation.getMembers() ) {
+
+        if( m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
+        innerWays.add(m.getWay());
+        }
+
+        if( m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
+        Way way = m.getWay();
+        outerWays.add(way);
+        for( String key : way.keySet() ) {
+            if( !values.containsKey(key) ) { //relation values take precedence
+            values.put(key, way.get(key));
+            } else if( !relation.hasKey(key) && !values.get(key).equals(way.get(key)) ) {
+            conflictingKeys.add(key);
+            }
+        }
+        }
+    }
+
+    // filter out empty key conflicts - we need second iteration
+    boolean isBoundary = getPref("boundary");
+    if( isBoundary || !getPref("alltags") )
+        for( RelationMember m : relation.getMembers() )
+        if( m.hasRole() && m.getRole().equals("outer") && m.isWay() )
+            for( String key : values.keySet() )
+            if( !m.getWay().hasKey(key) && !relation.hasKey(key) )
+                conflictingKeys.add(key);
+
+    for( String key : conflictingKeys )
+        values.remove(key);
+
+    for( String linearTag : Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", DEFAULT_LINEAR_TAGS) )
+        values.remove(linearTag);
+
+    if( values.containsKey("natural") && values.get("natural").equals("coastline") )
+        values.remove("natural");
+
+    String name = values.get("name");
+    if( isBoundary ) {
+        Set<String> keySet = new TreeSet<>(values.keySet());
+        for( String key : keySet )
+        if( !REMOVE_FROM_BOUNDARY_TAGS.contains(key) )
+            values.remove(key);
+    }
+
+    values.put("area", "yes");
+
+    List<Command> commands = new ArrayList<>();
+    boolean moveTags = getPref("tags");
+
+    for( String key : values.keySet() ) {
+        List<OsmPrimitive> affectedWays = new ArrayList<>();
+        String value = values.get(key);
+
+        for( Way way : innerWays ) {
+        if( way.hasKey(key) && (isBoundary || value.equals(way.get(key))) ) {
+            affectedWays.add(way);
+        }
+        }
+
+        if( moveTags ) {
+        // remove duplicated tags from outer ways
+        for( Way way : outerWays ) {
+            if( way.hasKey(key) ) {
+            affectedWays.add(way);
+            }
+        }
+        }
+
+        if( affectedWays.size() > 0 ) {
+        commands.add(new ChangePropertyCommand(affectedWays, key, null));
+        }
+    }
+
+    if( moveTags ) {
+        // add those tag values to the relation
+        if( isBoundary )
+        values.put("name", name);
+        boolean fixed = false;
+        Relation r2 = new Relation(relation);
+        for( String key : values.keySet() ) {
+        if( !r2.hasKey(key) && !key.equals("area")
+            && (!isBoundary || key.equals("admin_level") || key.equals("name")) ) {
+            if( relation.isNew() )
+            relation.put(key, values.get(key));
+            else
+            r2.put(key, values.get(key));
+            fixed = true;
+        }
+        }
+        if( fixed && !relation.isNew() )
+        commands.add(new ChangeCommand(relation, r2));
+    }
+
+    return commands;
     }
 
@@ -348,59 +348,59 @@
      */
     private boolean askForAdminLevelAndName( Relation rel ) {
-	String relAL = rel.get("admin_level");
-	String relName = rel.get("name");
-	if( relAL != null && relName != null )
-	    return true;
-
-	JPanel panel = new JPanel(new GridBagLayout());
-	panel.add(new JLabel(tr("Enter admin level and name for the border relation:")), GBC.eol().insets(0, 0, 0, 5));
-
-	final JTextField admin = new JTextField();
-	admin.setText(relAL != null ? relAL : Main.pref.get(PREF_MULTIPOLY + "lastadmin", ""));
-	panel.add(new JLabel(tr("Admin level")), GBC.std());
-	panel.add(Box.createHorizontalStrut(10), GBC.std());
-	panel.add(admin, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 5));
-
-	final JTextField name = new JTextField();
-	if( relName != null )
-	    name.setText(relName);
-	panel.add(new JLabel(tr("Name")), GBC.std());
-	panel.add(Box.createHorizontalStrut(10), GBC.std());
-	panel.add(name, GBC.eol().fill(GBC.HORIZONTAL));
-
-	final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
-	    @Override
-	    public void selectInitialValue() {
-		admin.requestFocusInWindow();
-		admin.selectAll();
-	    }
-	};
-	final JDialog dlg = optionPane.createDialog(Main.parent, tr("Create a new relation"));
-	dlg.setModalityType(ModalityType.DOCUMENT_MODAL);
-
-	name.addActionListener(new ActionListener() {
-	    public void actionPerformed( ActionEvent e ) {
-		dlg.setVisible(false);
-		optionPane.setValue(JOptionPane.OK_OPTION);
-	    }
-	});
-
-	dlg.setVisible(true);
-
-	Object answer = optionPane.getValue();
-	if( answer == null || answer == JOptionPane.UNINITIALIZED_VALUE
-		|| (answer instanceof Integer && (Integer)answer != JOptionPane.OK_OPTION) ) {
-	    return false;
-	}
-
-	String admin_level = admin.getText().trim();
-	String new_name = name.getText().trim();
-	if( admin_level.equals("10") || (admin_level.length() == 1 && Character.isDigit(admin_level.charAt(0))) ) {
-	    rel.put("admin_level", admin_level);
-	    Main.pref.put(PREF_MULTIPOLY + "lastadmin", admin_level);
-	}
-	if( new_name.length() > 0 )
-	    rel.put("name", new_name);
-	return true;
+    String relAL = rel.get("admin_level");
+    String relName = rel.get("name");
+    if( relAL != null && relName != null )
+        return true;
+
+    JPanel panel = new JPanel(new GridBagLayout());
+    panel.add(new JLabel(tr("Enter admin level and name for the border relation:")), GBC.eol().insets(0, 0, 0, 5));
+
+    final JTextField admin = new JTextField();
+    admin.setText(relAL != null ? relAL : Main.pref.get(PREF_MULTIPOLY + "lastadmin", ""));
+    panel.add(new JLabel(tr("Admin level")), GBC.std());
+    panel.add(Box.createHorizontalStrut(10), GBC.std());
+    panel.add(admin, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 5));
+
+    final JTextField name = new JTextField();
+    if( relName != null )
+        name.setText(relName);
+    panel.add(new JLabel(tr("Name")), GBC.std());
+    panel.add(Box.createHorizontalStrut(10), GBC.std());
+    panel.add(name, GBC.eol().fill(GBC.HORIZONTAL));
+
+    final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
+        @Override
+        public void selectInitialValue() {
+        admin.requestFocusInWindow();
+        admin.selectAll();
+        }
+    };
+    final JDialog dlg = optionPane.createDialog(Main.parent, tr("Create a new relation"));
+    dlg.setModalityType(ModalityType.DOCUMENT_MODAL);
+
+    name.addActionListener(new ActionListener() {
+        public void actionPerformed( ActionEvent e ) {
+        dlg.setVisible(false);
+        optionPane.setValue(JOptionPane.OK_OPTION);
+        }
+    });
+
+    dlg.setVisible(true);
+
+    Object answer = optionPane.getValue();
+    if( answer == null || answer == JOptionPane.UNINITIALIZED_VALUE
+        || (answer instanceof Integer && (Integer)answer != JOptionPane.OK_OPTION) ) {
+        return false;
+    }
+
+    String admin_level = admin.getText().trim();
+    String new_name = name.getText().trim();
+    if( admin_level.equals("10") || (admin_level.length() == 1 && Character.isDigit(admin_level.charAt(0))) ) {
+        rel.put("admin_level", admin_level);
+        Main.pref.put(PREF_MULTIPOLY + "lastadmin", admin_level);
+    }
+    if( new_name.length() > 0 )
+        rel.put("name", new_name);
+    return true;
     }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/ReconstructPolygonAction.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/ReconstructPolygonAction.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/ReconstructPolygonAction.java	(revision 30738)
@@ -42,10 +42,10 @@
     
     private static final List<String> IRRELEVANT_KEYS = Arrays.asList(new String[] {
-	"source", "created_by", "note"});
+    "source", "created_by", "note"});
 
     public ReconstructPolygonAction( ChosenRelation rel ) {
         super(tr("Reconstruct polygon"));
         putValue(SMALL_ICON, ImageProvider.get("dialogs", "filter"));
-	putValue(LONG_DESCRIPTION, "Reconstruct polygon from multipolygon relation");
+    putValue(LONG_DESCRIPTION, "Reconstruct polygon from multipolygon relation");
         this.rel = rel;
         rel.addChosenRelationListener(this);
@@ -55,110 +55,110 @@
     public void actionPerformed( ActionEvent e ) {
         Relation r = rel.get();
-	List<Way> ways = new ArrayList<>();
-	boolean wont = false;
-	for( RelationMember m : r.getMembers() ) {
-	    if( m.isWay() )
-		ways.add(m.getWay());
-	    else
-		wont = true;
-	}
-	if( wont ) {
-	    JOptionPane.showMessageDialog(Main.parent, tr("Multipolygon must consist only of ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
-	    return;
-	}
-	
-	MultipolygonBuilder mpc = new MultipolygonBuilder();
-	String error = mpc.makeFromWays(ways);
-	if( error != null ) {
-	    JOptionPane.showMessageDialog(Main.parent, error);
-	    return;
-	}
-	
-	if( !mpc.innerWays.isEmpty() ) {
-	    JOptionPane.showMessageDialog(Main.parent, tr("Reconstruction of polygons can be done only from outer ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
-	    return;
-	}
-	
-	rel.clear();
-	List<Way> newSelection = new ArrayList<>();
-	List<Command> commands = new ArrayList<>();
+    List<Way> ways = new ArrayList<>();
+    boolean wont = false;
+    for( RelationMember m : r.getMembers() ) {
+        if( m.isWay() )
+        ways.add(m.getWay());
+        else
+        wont = true;
+    }
+    if( wont ) {
+        JOptionPane.showMessageDialog(Main.parent, tr("Multipolygon must consist only of ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
+        return;
+    }
+    
+    MultipolygonBuilder mpc = new MultipolygonBuilder();
+    String error = mpc.makeFromWays(ways);
+    if( error != null ) {
+        JOptionPane.showMessageDialog(Main.parent, error);
+        return;
+    }
+    
+    if( !mpc.innerWays.isEmpty() ) {
+        JOptionPane.showMessageDialog(Main.parent, tr("Reconstruction of polygons can be done only from outer ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
+        return;
+    }
+    
+    rel.clear();
+    List<Way> newSelection = new ArrayList<>();
+    List<Command> commands = new ArrayList<>();
         Command c = DeleteCommand.delete(Main.main.getEditLayer(), Collections.singleton(r), true, true);
         if( c == null )
             return;
-	commands.add(c);
-	
-	for( JoinedPolygon p : mpc.outerWays ) {
-	    // move all tags from relation and common tags from ways
-	    Map<String, String> tags = p.ways.get(0).getKeys();
-	    List<OsmPrimitive> relations = p.ways.get(0).getReferrers();
-	    Set<String> noTags = new HashSet<>(r.keySet());
-	    for( int i = 1; i < p.ways.size(); i++ ) {
-		Way w = p.ways.get(i);
-		for( String key : w.keySet() ) {
-		    String value = w.get(key);
-		    if( !noTags.contains(key) && tags.containsKey(key) && !tags.get(key).equals(value) ) {
-			tags.remove(key);
-			noTags.add(key);
-		    }
-		}
-		List<OsmPrimitive> referrers = w.getReferrers();
-		for( Iterator<OsmPrimitive> ref1 = relations.iterator(); ref1.hasNext(); )
-		    if( !referrers.contains(ref1.next()) )
-			ref1.remove();
-	    }
-	    tags.putAll(r.getKeys());
-	    tags.remove("type");
-	    
-	    // then delete ways that are not relevant (do not take part in other relations of have strange tags)
-	    Way candidateWay = null;
-	    for( Way w : p.ways ) {
-		if( w.getReferrers().equals(relations) ) {
-		    // check tags that remain
-		    Set<String> keys = new HashSet<>(w.keySet());
-		    keys.removeAll(tags.keySet());
-		    keys.removeAll(IRRELEVANT_KEYS);
-		    if( keys.isEmpty() ) {
-			if( candidateWay == null )
-			    candidateWay = w;
-			else {
-			    if( candidateWay.isNew() && !w.isNew() ) {
-				// prefer ways that are already in the database
-				Way tmp = w;
-				w = candidateWay;
-				candidateWay = tmp;
-			    }
-			    commands.add(new DeleteCommand(w));
-			}
-		    }
-		}
-	    }
-	    
-	    // take the first way, put all nodes into it, making it a closed polygon
-	    Way result = candidateWay == null ? new Way() : new Way(candidateWay);
-	    result.setNodes(p.nodes);
-	    result.addNode(result.firstNode());
-	    result.setKeys(tags);
-	    newSelection.add(candidateWay == null ? result : candidateWay);
-	    commands.add(candidateWay == null ? new AddCommand(result) : new ChangeCommand(candidateWay, result));
-	}
-	
+    commands.add(c);
+    
+    for( JoinedPolygon p : mpc.outerWays ) {
+        // move all tags from relation and common tags from ways
+        Map<String, String> tags = p.ways.get(0).getKeys();
+        List<OsmPrimitive> relations = p.ways.get(0).getReferrers();
+        Set<String> noTags = new HashSet<>(r.keySet());
+        for( int i = 1; i < p.ways.size(); i++ ) {
+        Way w = p.ways.get(i);
+        for( String key : w.keySet() ) {
+            String value = w.get(key);
+            if( !noTags.contains(key) && tags.containsKey(key) && !tags.get(key).equals(value) ) {
+            tags.remove(key);
+            noTags.add(key);
+            }
+        }
+        List<OsmPrimitive> referrers = w.getReferrers();
+        for( Iterator<OsmPrimitive> ref1 = relations.iterator(); ref1.hasNext(); )
+            if( !referrers.contains(ref1.next()) )
+            ref1.remove();
+        }
+        tags.putAll(r.getKeys());
+        tags.remove("type");
+        
+        // then delete ways that are not relevant (do not take part in other relations of have strange tags)
+        Way candidateWay = null;
+        for( Way w : p.ways ) {
+        if( w.getReferrers().equals(relations) ) {
+            // check tags that remain
+            Set<String> keys = new HashSet<>(w.keySet());
+            keys.removeAll(tags.keySet());
+            keys.removeAll(IRRELEVANT_KEYS);
+            if( keys.isEmpty() ) {
+            if( candidateWay == null )
+                candidateWay = w;
+            else {
+                if( candidateWay.isNew() && !w.isNew() ) {
+                // prefer ways that are already in the database
+                Way tmp = w;
+                w = candidateWay;
+                candidateWay = tmp;
+                }
+                commands.add(new DeleteCommand(w));
+            }
+            }
+        }
+        }
+        
+        // take the first way, put all nodes into it, making it a closed polygon
+        Way result = candidateWay == null ? new Way() : new Way(candidateWay);
+        result.setNodes(p.nodes);
+        result.addNode(result.firstNode());
+        result.setKeys(tags);
+        newSelection.add(candidateWay == null ? result : candidateWay);
+        commands.add(candidateWay == null ? new AddCommand(result) : new ChangeCommand(candidateWay, result));
+    }
+    
         Main.main.undoRedo.add(new SequenceCommand(tr("Reconstruct polygons from relation {0}",
-		r.getDisplayName(DefaultNameFormatter.getInstance())), commands));
-	Main.main.getCurrentDataSet().setSelected(newSelection);
+        r.getDisplayName(DefaultNameFormatter.getInstance())), commands));
+    Main.main.getCurrentDataSet().setSelected(newSelection);
     }
 
     public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
-	setEnabled(isSuitableRelation(newRelation));
+    setEnabled(isSuitableRelation(newRelation));
     }
     
     private boolean isSuitableRelation( Relation newRelation ) {
-	if( newRelation == null || !"multipolygon".equals(newRelation.get("type")) || newRelation.getMembersCount() == 0 )
-	    return false;
-	else {
-	    for( RelationMember m : newRelation.getMembers() )
-		if( "inner".equals(m.getRole()) )
-		    return false;
-	    return true;
-	}
+    if( newRelation == null || !"multipolygon".equals(newRelation.get("type")) || newRelation.getMembersCount() == 0 )
+        return false;
+    else {
+        for( RelationMember m : newRelation.getMembers() )
+        if( "inner".equals(m.getRole()) )
+            return false;
+        return true;
+    }
     }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SortAndFixAction.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SortAndFixAction.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SortAndFixAction.java	(revision 30738)
@@ -25,6 +25,6 @@
 
 public class SortAndFixAction extends AbstractAction implements ChosenRelationListener {
-	private static final long serialVersionUID = 1L;
-	private ChosenRelation rel;
+    private static final long serialVersionUID = 1L;
+    private ChosenRelation rel;
     private List<RelationFixer> fixers;
 
@@ -67,8 +67,8 @@
 
     private RelationFixer getFixer( Relation rel ) {
-    	for(RelationFixer fixer : fixers)
-    		if (fixer.isFixerApplicable(rel))
-    			return fixer;
-    	return new NothingFixer();
+        for(RelationFixer fixer : fixers)
+            if (fixer.isFixerApplicable(rel))
+                return fixer;
+        return new NothingFixer();
     }
 
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SplittingMultipolygons.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SplittingMultipolygons.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SplittingMultipolygons.java	(revision 30738)
@@ -24,78 +24,78 @@
 
     public static boolean canProcess( Collection<Way> ways ) {
-	List<Way> rings = new ArrayList<>();
-	List<Way> arcs = new ArrayList<>();
-	Area a = Main.main.getCurrentDataSet().getDataSourceArea();
-	for( Way way : ways ) {
-	    if( way.isDeleted() )
-		return false;
-	    for( Node n : way.getNodes() ) {
-	        LatLon ll = n.getCoor();
-    		if( n.isIncomplete() || (a != null && !a.contains(ll.getX(), ll.getY())) )
-    		    return false;
-	    }
-	    if( way.isClosed() )
-		rings.add(way);
-	    else
-		arcs.add(way);
-	}
-	
-	// If there are more that one segment, check that they touch rings
-	if( arcs.size() > 1 ) {
-	    for( Way segment : arcs ) {
-		boolean found = false;
-		for( Way ring : rings )
-		    if( ring.containsNode(segment.firstNode()) && ring.containsNode(segment.lastNode()) )
-			found = true;
-		if( !found )
-		    return false;
-	    }
-	}
-
-	if( rings.isEmpty() && arcs.isEmpty() )
-	    return false;
-
-	// check for non-containment of rings
-	for( int i = 0; i < rings.size() - 1; i++ ) {
-	    for( int j = i + 1; j < rings.size(); j++ ) {
-		PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
-		if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
-		    return false;
-	    }
-	}
-
-	return true;
+    List<Way> rings = new ArrayList<>();
+    List<Way> arcs = new ArrayList<>();
+    Area a = Main.main.getCurrentDataSet().getDataSourceArea();
+    for( Way way : ways ) {
+        if( way.isDeleted() )
+        return false;
+        for( Node n : way.getNodes() ) {
+            LatLon ll = n.getCoor();
+            if( n.isIncomplete() || (a != null && !a.contains(ll.getX(), ll.getY())) )
+                return false;
+        }
+        if( way.isClosed() )
+        rings.add(way);
+        else
+        arcs.add(way);
+    }
+    
+    // If there are more that one segment, check that they touch rings
+    if( arcs.size() > 1 ) {
+        for( Way segment : arcs ) {
+        boolean found = false;
+        for( Way ring : rings )
+            if( ring.containsNode(segment.firstNode()) && ring.containsNode(segment.lastNode()) )
+            found = true;
+        if( !found )
+            return false;
+        }
+    }
+
+    if( rings.isEmpty() && arcs.isEmpty() )
+        return false;
+
+    // check for non-containment of rings
+    for( int i = 0; i < rings.size() - 1; i++ ) {
+        for( int j = i + 1; j < rings.size(); j++ ) {
+        PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
+        if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
+            return false;
+        }
+    }
+
+    return true;
     }
     
     public static List<Relation> process( Collection<Way> selectedWays ) {
-//	System.out.println("---------------------------------------");
-	List<Relation> result = new ArrayList<>();
-	List<Way> rings = new ArrayList<>();
-	List<Way> arcs = new ArrayList<>();
-	for( Way way : selectedWays ) {
-	    if( way.isClosed() )
-		rings.add(way);
-	    else
-		arcs.add(way);
-	}
-
-	for( Way ring : rings ) {
-	    List<Command> commands = new ArrayList<>();
-	    Relation newRelation = SplittingMultipolygons.attachRingToNeighbours(ring, commands);
-	    if( newRelation != null && !commands.isEmpty() ) {
-		Main.main.undoRedo.add(commands.get(0));
-		result.add(newRelation);
-	    }
-	}
-
-	for( Way arc : arcs) {
-	    List<Command> commands = new ArrayList<>();
-	    Relation newRelation = SplittingMultipolygons.tryToCloseOneWay(arc, commands);
-	    if( newRelation != null && !commands.isEmpty() ) {
-		Main.main.undoRedo.add(commands.get(0));
-		result.add(newRelation);
-	    }
-	}
-	return result;
+//    System.out.println("---------------------------------------");
+    List<Relation> result = new ArrayList<>();
+    List<Way> rings = new ArrayList<>();
+    List<Way> arcs = new ArrayList<>();
+    for( Way way : selectedWays ) {
+        if( way.isClosed() )
+        rings.add(way);
+        else
+        arcs.add(way);
+    }
+
+    for( Way ring : rings ) {
+        List<Command> commands = new ArrayList<>();
+        Relation newRelation = SplittingMultipolygons.attachRingToNeighbours(ring, commands);
+        if( newRelation != null && !commands.isEmpty() ) {
+        Main.main.undoRedo.add(commands.get(0));
+        result.add(newRelation);
+        }
+    }
+
+    for( Way arc : arcs) {
+        List<Command> commands = new ArrayList<>();
+        Relation newRelation = SplittingMultipolygons.tryToCloseOneWay(arc, commands);
+        if( newRelation != null && !commands.isEmpty() ) {
+        Main.main.undoRedo.add(commands.get(0));
+        result.add(newRelation);
+        }
+    }
+    return result;
     }
 
@@ -104,11 +104,11 @@
      */
     private static void closePolygon( List<Node> base, List<Node> append ) {
-	if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
-	    List<Node> ap2 = new ArrayList<>(append);
-	    Collections.reverse(ap2);
-	    append = ap2;
-	}
-	base.remove(base.size() - 1);
-	base.addAll(append);
+    if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
+        List<Node> ap2 = new ArrayList<>(append);
+        Collections.reverse(ap2);
+        append = ap2;
+    }
+    base.remove(base.size() - 1);
+    base.addAll(append);
     }
 
@@ -117,8 +117,8 @@
      */
     private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
-	EastNorth en1 = n1.getEastNorth();
-	EastNorth en2 = n2.getEastNorth();
-	Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
-	return Geometry.nodeInsidePolygon(testNode, polygon);
+    EastNorth en1 = n1.getEastNorth();
+    EastNorth en2 = n2.getEastNorth();
+    Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
+    return Geometry.nodeInsidePolygon(testNode, polygon);
     }
 
@@ -131,92 +131,92 @@
      */
     public static List<Way> splitWay( Way w, Node n1, Node n2, List<Command> commands ) {
-	List<Node> nodes = new ArrayList<>(w.getNodes());
-	if( w.isClosed() )
-	    nodes.remove(nodes.size() - 1);
-	int index1 = nodes.indexOf(n1);
-	int index2 = n2 == null ? -1 : nodes.indexOf(n2);
-	if( index1 > index2 ) {
-	    int tmp = index1;
-	    index1 = index2;
-	    index2 = tmp;
-	}
-	// right now index2 >= index1
-	if( index2 < 1 || index1 >= w.getNodesCount() - 1 || index2 >= w.getNodesCount() )
-	    return Collections.emptyList();
-	if( w.isClosed() && (index1 < 0 || index1 == index2 || index1 + w.getNodesCount() == index2) )
-	    return Collections.emptyList();
-	
-	// todo: download parent relations!
-
-	// make a list of segments
-	List<List<Node>> chunks = new ArrayList<>(2);
-	List<Node> chunk = new ArrayList<>();
-	for( int i = 0; i < nodes.size(); i++ ) {
-	    chunk.add(nodes.get(i));
-	    if( (w.isClosed() || chunk.size() > 1) && (i == index1 || i == index2) ) {
-		chunks.add(chunk);
-		chunk = new ArrayList<>();
-		chunk.add(nodes.get(i));
-	    }
-	}
-	chunks.add(chunk);
-
-	// for closed way ignore the way boundary
-	if( w.isClosed() ) {
-	    chunks.get(chunks.size() - 1).addAll(chunks.get(0));
-	    chunks.remove(0);
-	} else if( chunks.get(chunks.size() - 1).size() < 2 )
-	    chunks.remove(chunks.size() - 1);
-
-	// todo remove debug: show chunks array contents
-	/*for( List<Node> c1 : chunks ) {
-	for( Node cn1 : c1 )
-	System.out.print(cn1.getId() + ",");
-	System.out.println();
-	}*/
-
-	// build a map of referencing relations
-	Map<Relation, Integer> references = new HashMap<>();
-	List<Command> relationCommands = new ArrayList<>();
-	for( OsmPrimitive p : w.getReferrers() ) {
-	    if( p instanceof Relation ) {
-		Relation rel = commands == null ? (Relation)p : new Relation((Relation)p);
-		if( commands != null )
-		    relationCommands.add(new ChangeCommand((Relation)p, rel));
-		for( int i = 0; i < rel.getMembersCount(); i++ )
-		    if( rel.getMember(i).getMember().equals(w) )
-			references.put(rel, Integer.valueOf(i));
-	    }
-	}
-
-	// build ways
-	List<Way> result = new ArrayList<>();
-	Way updatedWay = commands == null ? w : new Way(w);
-	updatedWay.setNodes(chunks.get(0));
-	if( commands != null ) {
-	    commands.add(new ChangeCommand(w, updatedWay));
-	    result.add(updatedWay);
-	}
-
-	for( int i = 1; i < chunks.size(); i++ ) {
-	    List<Node> achunk = chunks.get(i);
-	    Way newWay = new Way();
-	    newWay.setKeys(w.getKeys());
-	    result.add(newWay);
-	    for( Relation rel : references.keySet() ) {
-		int relIndex = references.get(rel);
-		rel.addMember(relIndex + 1, new RelationMember(rel.getMember(relIndex).getRole(), newWay));
-	    }
-	    newWay.setNodes(achunk);
-	    if( commands != null )
-		commands.add(new AddCommand(newWay));
-	}
-	if( commands != null )
-	    commands.addAll(relationCommands);
-	return result;
+    List<Node> nodes = new ArrayList<>(w.getNodes());
+    if( w.isClosed() )
+        nodes.remove(nodes.size() - 1);
+    int index1 = nodes.indexOf(n1);
+    int index2 = n2 == null ? -1 : nodes.indexOf(n2);
+    if( index1 > index2 ) {
+        int tmp = index1;
+        index1 = index2;
+        index2 = tmp;
+    }
+    // right now index2 >= index1
+    if( index2 < 1 || index1 >= w.getNodesCount() - 1 || index2 >= w.getNodesCount() )
+        return Collections.emptyList();
+    if( w.isClosed() && (index1 < 0 || index1 == index2 || index1 + w.getNodesCount() == index2) )
+        return Collections.emptyList();
+    
+    // todo: download parent relations!
+
+    // make a list of segments
+    List<List<Node>> chunks = new ArrayList<>(2);
+    List<Node> chunk = new ArrayList<>();
+    for( int i = 0; i < nodes.size(); i++ ) {
+        chunk.add(nodes.get(i));
+        if( (w.isClosed() || chunk.size() > 1) && (i == index1 || i == index2) ) {
+        chunks.add(chunk);
+        chunk = new ArrayList<>();
+        chunk.add(nodes.get(i));
+        }
+    }
+    chunks.add(chunk);
+
+    // for closed way ignore the way boundary
+    if( w.isClosed() ) {
+        chunks.get(chunks.size() - 1).addAll(chunks.get(0));
+        chunks.remove(0);
+    } else if( chunks.get(chunks.size() - 1).size() < 2 )
+        chunks.remove(chunks.size() - 1);
+
+    // todo remove debug: show chunks array contents
+    /*for( List<Node> c1 : chunks ) {
+    for( Node cn1 : c1 )
+    System.out.print(cn1.getId() + ",");
+    System.out.println();
+    }*/
+
+    // build a map of referencing relations
+    Map<Relation, Integer> references = new HashMap<>();
+    List<Command> relationCommands = new ArrayList<>();
+    for( OsmPrimitive p : w.getReferrers() ) {
+        if( p instanceof Relation ) {
+        Relation rel = commands == null ? (Relation)p : new Relation((Relation)p);
+        if( commands != null )
+            relationCommands.add(new ChangeCommand((Relation)p, rel));
+        for( int i = 0; i < rel.getMembersCount(); i++ )
+            if( rel.getMember(i).getMember().equals(w) )
+            references.put(rel, Integer.valueOf(i));
+        }
+    }
+
+    // build ways
+    List<Way> result = new ArrayList<>();
+    Way updatedWay = commands == null ? w : new Way(w);
+    updatedWay.setNodes(chunks.get(0));
+    if( commands != null ) {
+        commands.add(new ChangeCommand(w, updatedWay));
+        result.add(updatedWay);
+    }
+
+    for( int i = 1; i < chunks.size(); i++ ) {
+        List<Node> achunk = chunks.get(i);
+        Way newWay = new Way();
+        newWay.setKeys(w.getKeys());
+        result.add(newWay);
+        for( Relation rel : references.keySet() ) {
+        int relIndex = references.get(rel);
+        rel.addMember(relIndex + 1, new RelationMember(rel.getMember(relIndex).getRole(), newWay));
+        }
+        newWay.setNodes(achunk);
+        if( commands != null )
+        commands.add(new AddCommand(newWay));
+    }
+    if( commands != null )
+        commands.addAll(relationCommands);
+    return result;
     }
 
     public static List<Way> splitWay( Way w, Node n1, Node n2 ) {
-	return splitWay(w, n1, n2, null);
+    return splitWay(w, n1, n2, null);
     }
 
@@ -225,65 +225,65 @@
      */
     public static Relation tryToCloseOneWay( Way segment, List<Command> resultingCommands ) {
-	if( segment.isClosed() || segment.isIncomplete() )
-	    return null;
-
-	List<Way> ways = intersection(
-		OsmPrimitive.getFilteredList(segment.firstNode().getReferrers(), Way.class),
-		OsmPrimitive.getFilteredList(segment.lastNode().getReferrers(), Way.class));
-	ways.remove(segment);
-	for( Iterator<Way> iter = ways.iterator(); iter.hasNext(); ) {
-	    boolean save = false;
-	    for( OsmPrimitive ref : iter.next().getReferrers() )
-		if( ref instanceof Relation && ((Relation)ref).isMultipolygon() && !ref.isDeleted() )
-		    save = true;
-	    if( !save )
-		iter.remove();
-	}
-	if( ways.isEmpty() )
-	    return null; // well...
-	Way target = ways.get(0);
-
-	// time to create a new multipolygon relation and a command stack
-	List<Command> commands = new ArrayList<>();
-	Relation newRelation = new Relation();
-	newRelation.put("type", "multipolygon");
-	newRelation.addMember(new RelationMember("outer", segment));
-	Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
-	Way segmentCopy = new Way(segment);
-	boolean changed = false;
-	for( String key : segmentCopy.keySet() ) {
-	    if( !linearTags.contains(key) ) {
-		newRelation.put(key, segmentCopy.get(key));
-		segmentCopy.remove(key);
-		changed = true;
-	    }
-	}
-	if( changed )
-	    commands.add(new ChangeCommand(segment, segmentCopy));
-
-	// now split the way, at last
-	List<Way> newWays = new ArrayList<>(splitWay(target, segment.firstNode(), segment.lastNode(), commands));
-
-	Way addingWay = null;
-	if( target.isClosed() ) {
-	    Way utarget = newWays.get(1);
-	    Way alternate = newWays.get(0);
-	    List<Node> testRing = new ArrayList<>(segment.getNodes());
-	    closePolygon(testRing, utarget.getNodes());
-	    addingWay = segmentInsidePolygon(alternate.getNode(0), alternate.getNode(1), testRing) ? alternate : utarget;
-	} else {
-	    for( Way w : newWays ) {
-		if( (w.firstNode().equals(segment.firstNode()) && w.lastNode().equals(segment.lastNode()))
-			|| (w.firstNode().equals(segment.lastNode()) && w.lastNode().equals(segment.firstNode())) ) {
-		    addingWay = w;
-		    break;
-		}
-	    }
-	}
-	newRelation.addMember(new RelationMember("outer", addingWay.getUniqueId() == target.getUniqueId() ? target : addingWay));
-	commands.add(new AddCommand(newRelation));
-	resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
-		DefaultNameFormatter.getInstance().format(segment)), commands));
-	return newRelation;
+    if( segment.isClosed() || segment.isIncomplete() )
+        return null;
+
+    List<Way> ways = intersection(
+        OsmPrimitive.getFilteredList(segment.firstNode().getReferrers(), Way.class),
+        OsmPrimitive.getFilteredList(segment.lastNode().getReferrers(), Way.class));
+    ways.remove(segment);
+    for( Iterator<Way> iter = ways.iterator(); iter.hasNext(); ) {
+        boolean save = false;
+        for( OsmPrimitive ref : iter.next().getReferrers() )
+        if( ref instanceof Relation && ((Relation)ref).isMultipolygon() && !ref.isDeleted() )
+            save = true;
+        if( !save )
+        iter.remove();
+    }
+    if( ways.isEmpty() )
+        return null; // well...
+    Way target = ways.get(0);
+
+    // time to create a new multipolygon relation and a command stack
+    List<Command> commands = new ArrayList<>();
+    Relation newRelation = new Relation();
+    newRelation.put("type", "multipolygon");
+    newRelation.addMember(new RelationMember("outer", segment));
+    Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
+    Way segmentCopy = new Way(segment);
+    boolean changed = false;
+    for( String key : segmentCopy.keySet() ) {
+        if( !linearTags.contains(key) ) {
+        newRelation.put(key, segmentCopy.get(key));
+        segmentCopy.remove(key);
+        changed = true;
+        }
+    }
+    if( changed )
+        commands.add(new ChangeCommand(segment, segmentCopy));
+
+    // now split the way, at last
+    List<Way> newWays = new ArrayList<>(splitWay(target, segment.firstNode(), segment.lastNode(), commands));
+
+    Way addingWay = null;
+    if( target.isClosed() ) {
+        Way utarget = newWays.get(1);
+        Way alternate = newWays.get(0);
+        List<Node> testRing = new ArrayList<>(segment.getNodes());
+        closePolygon(testRing, utarget.getNodes());
+        addingWay = segmentInsidePolygon(alternate.getNode(0), alternate.getNode(1), testRing) ? alternate : utarget;
+    } else {
+        for( Way w : newWays ) {
+        if( (w.firstNode().equals(segment.firstNode()) && w.lastNode().equals(segment.lastNode()))
+            || (w.firstNode().equals(segment.lastNode()) && w.lastNode().equals(segment.firstNode())) ) {
+            addingWay = w;
+            break;
+        }
+        }
+    }
+    newRelation.addMember(new RelationMember("outer", addingWay.getUniqueId() == target.getUniqueId() ? target : addingWay));
+    commands.add(new AddCommand(newRelation));
+    resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
+        DefaultNameFormatter.getInstance().format(segment)), commands));
+    return newRelation;
     }
 
@@ -292,9 +292,9 @@
      */
     private static <T> List<T> intersection( Collection<T> list1, Collection<T> list2 ) {
-	List<T> result = new ArrayList<>();
-	for( T item : list1 )
-	    if( list2.contains(item) )
-		result.add(item);
-	return result;
+    List<T> result = new ArrayList<>();
+    for( T item : list1 )
+        if( list2.contains(item) )
+        result.add(item);
+    return result;
     }
     
@@ -303,54 +303,54 @@
      */
     public static Relation attachRingToNeighbours( Way ring, List<Command> resultingCommands ) {
-	if( !ring.isClosed() || ring.isIncomplete() )
-	    return null;
-	Map<Way, Boolean> touchingWays = new HashMap<>();
-	for( Node n : ring.getNodes() ) {
-	    for( OsmPrimitive p : n.getReferrers() ) {
-		if( p instanceof Way && !p.equals(ring) ) {
-		    for( OsmPrimitive r : p.getReferrers() ) {
-			if( r instanceof Relation && ((Relation)r).hasKey("type") && ((Relation)r).get("type").equals("multipolygon") ) {
-			    if( touchingWays.containsKey((Way)p) )
-				touchingWays.put((Way)p, Boolean.TRUE);
-			    else
-				touchingWays.put((Way)p, Boolean.FALSE);
-			    break;
-			}
-		    }
-		}
-	    }
-	}
-	
-	List<TheRing> otherWays = new ArrayList<>();
-	for( Way w : touchingWays.keySet() )
-	    if( touchingWays.get(w) ) {
-		otherWays.add(new TheRing(w));
-//		System.out.println("Touching ring: " + otherWays.get(otherWays.size()-1));
-	    }
-	
-//	for( Iterator<Way> keys = touchingWays.keySet().iterator(); keys.hasNext(); ) {
-//	    if( !touchingWays.get(keys.next()) )
-//		keys.remove();
-//	}
-	
-	// now touchingWays has only ways that touch the ring twice
-	List<Command> commands = new ArrayList<>();
-	TheRing theRing = new TheRing(ring); // this is actually useful
-	
-	for( TheRing otherRing : otherWays )
-	    theRing.collide(otherRing);
-	
-	theRing.putSourceWayFirst();
-	for( TheRing otherRing : otherWays )
-	    otherRing.putSourceWayFirst();
-	
-	Map<Relation, Relation> relationCache = new HashMap<>();
-	for( TheRing otherRing : otherWays )
-	    commands.addAll(otherRing.getCommands(false, relationCache));
-	commands.addAll(theRing.getCommands(relationCache));
-	TheRing.updateCommandsWithRelations(commands, relationCache);
-	resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
-		DefaultNameFormatter.getInstance().format(ring)), commands));
-	return theRing.getRelation();
+    if( !ring.isClosed() || ring.isIncomplete() )
+        return null;
+    Map<Way, Boolean> touchingWays = new HashMap<>();
+    for( Node n : ring.getNodes() ) {
+        for( OsmPrimitive p : n.getReferrers() ) {
+        if( p instanceof Way && !p.equals(ring) ) {
+            for( OsmPrimitive r : p.getReferrers() ) {
+            if( r instanceof Relation && ((Relation)r).hasKey("type") && ((Relation)r).get("type").equals("multipolygon") ) {
+                if( touchingWays.containsKey((Way)p) )
+                touchingWays.put((Way)p, Boolean.TRUE);
+                else
+                touchingWays.put((Way)p, Boolean.FALSE);
+                break;
+            }
+            }
+        }
+        }
+    }
+    
+    List<TheRing> otherWays = new ArrayList<>();
+    for( Way w : touchingWays.keySet() )
+        if( touchingWays.get(w) ) {
+        otherWays.add(new TheRing(w));
+//        System.out.println("Touching ring: " + otherWays.get(otherWays.size()-1));
+        }
+    
+//    for( Iterator<Way> keys = touchingWays.keySet().iterator(); keys.hasNext(); ) {
+//        if( !touchingWays.get(keys.next()) )
+//        keys.remove();
+//    }
+    
+    // now touchingWays has only ways that touch the ring twice
+    List<Command> commands = new ArrayList<>();
+    TheRing theRing = new TheRing(ring); // this is actually useful
+    
+    for( TheRing otherRing : otherWays )
+        theRing.collide(otherRing);
+    
+    theRing.putSourceWayFirst();
+    for( TheRing otherRing : otherWays )
+        otherRing.putSourceWayFirst();
+    
+    Map<Relation, Relation> relationCache = new HashMap<>();
+    for( TheRing otherRing : otherWays )
+        commands.addAll(otherRing.getCommands(false, relationCache));
+    commands.addAll(theRing.getCommands(relationCache));
+    TheRing.updateCommandsWithRelations(commands, relationCache);
+    resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
+        DefaultNameFormatter.getInstance().format(ring)), commands));
+    return theRing.getRelation();
     }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java	(revision 30738)
@@ -36,30 +36,30 @@
 
     public TheRing( Way source ) {
-	this.source = source;
-	segments = new ArrayList<>(1);
-	segments.add(new RingSegment(source));
+    this.source = source;
+    segments = new ArrayList<>(1);
+    segments.add(new RingSegment(source));
     }
     
     public static boolean areAllOfThoseRings( Collection<Way> ways ) {
-	List<Way> rings = new ArrayList<>();
-	for( Way way : ways ) {
-	    if( way.isClosed() )
-		rings.add(way);
-	    else
-		return false;
-	}
-	if( rings.isEmpty() || ways.size() == 1 )
-	    return false;
-
-	// check for non-containment of rings
-	for( int i = 0; i < rings.size() - 1; i++ ) {
-	    for( int j = i + 1; j < rings.size(); j++ ) {
-		PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
-		if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
-		    return false;
-	    }
-	}
-
-	return true;
+    List<Way> rings = new ArrayList<>();
+    for( Way way : ways ) {
+        if( way.isClosed() )
+        rings.add(way);
+        else
+        return false;
+    }
+    if( rings.isEmpty() || ways.size() == 1 )
+        return false;
+
+    // check for non-containment of rings
+    for( int i = 0; i < rings.size() - 1; i++ ) {
+        for( int j = i + 1; j < rings.size(); j++ ) {
+        PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
+        if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
+            return false;
+        }
+    }
+
+    return true;
     }
 
@@ -69,49 +69,49 @@
      */
     public static List<Relation> makeManySimpleMultipolygons( Collection<Way> selection, List<Command> commands ) {
-	log("---------------------------------------");
-	List<TheRing> rings = new ArrayList<>(selection.size());
-	for( Way w : selection )
-	    rings.add(new TheRing(w));
-	for( int i = 0; i < rings.size() - 1; i++ )
-	    for( int j = i + 1; j < rings.size(); j++ )
-		rings.get(i).collide(rings.get(j));
-	redistributeSegments(rings);
-	List<Relation> relations = new ArrayList<>();
-	Map<Relation, Relation> relationCache = new HashMap<>();
-	for( TheRing r : rings ) {
-	    commands.addAll(r.getCommands(relationCache));
-	    relations.add(r.getRelation());
-	}
-	updateCommandsWithRelations(commands, relationCache);
-	return relations;
+    log("---------------------------------------");
+    List<TheRing> rings = new ArrayList<>(selection.size());
+    for( Way w : selection )
+        rings.add(new TheRing(w));
+    for( int i = 0; i < rings.size() - 1; i++ )
+        for( int j = i + 1; j < rings.size(); j++ )
+        rings.get(i).collide(rings.get(j));
+    redistributeSegments(rings);
+    List<Relation> relations = new ArrayList<>();
+    Map<Relation, Relation> relationCache = new HashMap<>();
+    for( TheRing r : rings ) {
+        commands.addAll(r.getCommands(relationCache));
+        relations.add(r.getRelation());
+    }
+    updateCommandsWithRelations(commands, relationCache);
+    return relations;
     }
 
     public void collide( TheRing other ) {
-	boolean collideNoted = false;
-	for( int i = 0; i < segments.size(); i++ ) {
-	    RingSegment segment1 = segments.get(i);
-	    if( !segment1.isReference() ) {
-		for( int j = 0; j < other.segments.size(); j++ ) {
-		    RingSegment segment2 = other.segments.get(j);
-		    if( !segment2.isReference() ) {
-			log("Comparing " + segment1 + " and " + segment2);
-			Node[] split = getSplitNodes(segment1.getNodes(), segment2.getNodes(), segment1.isRing(), segment2.isRing());
-			if( split != null ) {
-			    if( !collideNoted ) {
-				log("Rings for ways " + source.getUniqueId() + " and " + other.source.getUniqueId() + " collide.");
-				collideNoted = true;
-			    }
-			    RingSegment segment = splitRingAt(i, split[0], split[1]);
-			    RingSegment otherSegment = other.splitRingAt(j, split[2], split[3]);
-			    if( !areSegmentsEqual(segment, otherSegment) )
-				throw new IllegalArgumentException("Error: algorithm gave incorrect segments: " + segment + " and " + otherSegment);
-			    segment.makeReference(otherSegment);
-			}
-		    }
-		    if( segment1.isReference() )
-			break;
-		}
-	    }
-	}
+    boolean collideNoted = false;
+    for( int i = 0; i < segments.size(); i++ ) {
+        RingSegment segment1 = segments.get(i);
+        if( !segment1.isReference() ) {
+        for( int j = 0; j < other.segments.size(); j++ ) {
+            RingSegment segment2 = other.segments.get(j);
+            if( !segment2.isReference() ) {
+            log("Comparing " + segment1 + " and " + segment2);
+            Node[] split = getSplitNodes(segment1.getNodes(), segment2.getNodes(), segment1.isRing(), segment2.isRing());
+            if( split != null ) {
+                if( !collideNoted ) {
+                log("Rings for ways " + source.getUniqueId() + " and " + other.source.getUniqueId() + " collide.");
+                collideNoted = true;
+                }
+                RingSegment segment = splitRingAt(i, split[0], split[1]);
+                RingSegment otherSegment = other.splitRingAt(j, split[2], split[3]);
+                if( !areSegmentsEqual(segment, otherSegment) )
+                throw new IllegalArgumentException("Error: algorithm gave incorrect segments: " + segment + " and " + otherSegment);
+                segment.makeReference(otherSegment);
+            }
+            }
+            if( segment1.isReference() )
+            break;
+        }
+        }
+    }
     }
     
@@ -120,90 +120,90 @@
      */
     public static Node[] getSplitNodes( List<Node> nodes1, List<Node> nodes2, boolean isRing1, boolean isRing2 ) {
-	int pos = 0;
-	while( pos < nodes1.size() && !nodes2.contains(nodes1.get(pos)) )
-	    pos++;
-	boolean collideFound = pos == nodes1.size();
-	if( pos == 0 && isRing1 ) {
-	    // rewind a bit
-	    pos = nodes1.size() - 1;
-	    while( pos > 0 && nodes2.contains(nodes1.get(pos)) )
-		pos--;
-	    if( pos == 0 && nodes1.size() == nodes2.size() ) {
-		JOptionPane.showMessageDialog(Main.parent, "Two rings are equal, and this must not be.", "Multipolygon from rings", JOptionPane.ERROR_MESSAGE);
-		return null;
-	    }
-	    pos = pos == nodes1.size() - 1 ? 0 : pos + 1;
-	}
-	int firstPos = isRing1 ? pos : nodes1.size();
-	while( !collideFound ) {
-	    log("pos=" + pos);
-	    int start1 = pos;
-	    int start2 = nodes2.indexOf(nodes1.get(start1));
-	    int last1 = incrementBy(start1, 1, nodes1.size(), isRing1);
-	    int last2 = start2;
-	    int increment2 = 0;
-	    if( last1 >= 0 ) {
-		last2 = incrementBy(start2, -1, nodes2.size(), isRing2);
-		if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
-		    increment2 = -1;
-		else {
-		    last2 = incrementBy(start2, 1, nodes2.size(), isRing2);
-		    if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
-			increment2 = 1;
-		}
-	    }
-	    log("last1=" + last1 + " last2=" + last2 + " increment2=" + increment2);
-	    if( increment2 != 0 ) {
-		// find the first nodes
-		boolean reachedEnd = false;
-		while( !reachedEnd ) {
-		    int newLast1 = incrementBy(last1, 1, nodes1.size(), isRing1);
-		    int newLast2 = incrementBy(last2, increment2, nodes2.size(), isRing2);
-		    if( newLast1 < 0 || newLast2 < 0 || !nodes1.get(newLast1).equals(nodes2.get(newLast2)) )
-			reachedEnd = true;
-		    else {
-			last1 = newLast1;
-			last2 = newLast2;
-		    }
-		}
-		log("last1=" + last1 + " last2=" + last2);
-		if( increment2 < 0 ) {
-		    int tmp = start2;
-		    start2 = last2;
-		    last2 = tmp;
-		}
-		return new Node[] {nodes1.get(start1), nodes1.get(last1), nodes2.get(start2), nodes2.get(last2)};
-	    } else {
-		pos = last1;
-		while( pos != firstPos && pos >= 0 && !nodes2.contains(nodes1.get(pos)) )
-		    pos = incrementBy(pos, 1, nodes1.size(), isRing1);
-		if( pos < 0 || pos == firstPos || !nodes2.contains(nodes1.get(pos)) )
-		    collideFound = true;
-	    }
-	}
-	return null;
+    int pos = 0;
+    while( pos < nodes1.size() && !nodes2.contains(nodes1.get(pos)) )
+        pos++;
+    boolean collideFound = pos == nodes1.size();
+    if( pos == 0 && isRing1 ) {
+        // rewind a bit
+        pos = nodes1.size() - 1;
+        while( pos > 0 && nodes2.contains(nodes1.get(pos)) )
+        pos--;
+        if( pos == 0 && nodes1.size() == nodes2.size() ) {
+        JOptionPane.showMessageDialog(Main.parent, "Two rings are equal, and this must not be.", "Multipolygon from rings", JOptionPane.ERROR_MESSAGE);
+        return null;
+        }
+        pos = pos == nodes1.size() - 1 ? 0 : pos + 1;
+    }
+    int firstPos = isRing1 ? pos : nodes1.size();
+    while( !collideFound ) {
+        log("pos=" + pos);
+        int start1 = pos;
+        int start2 = nodes2.indexOf(nodes1.get(start1));
+        int last1 = incrementBy(start1, 1, nodes1.size(), isRing1);
+        int last2 = start2;
+        int increment2 = 0;
+        if( last1 >= 0 ) {
+        last2 = incrementBy(start2, -1, nodes2.size(), isRing2);
+        if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
+            increment2 = -1;
+        else {
+            last2 = incrementBy(start2, 1, nodes2.size(), isRing2);
+            if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
+            increment2 = 1;
+        }
+        }
+        log("last1=" + last1 + " last2=" + last2 + " increment2=" + increment2);
+        if( increment2 != 0 ) {
+        // find the first nodes
+        boolean reachedEnd = false;
+        while( !reachedEnd ) {
+            int newLast1 = incrementBy(last1, 1, nodes1.size(), isRing1);
+            int newLast2 = incrementBy(last2, increment2, nodes2.size(), isRing2);
+            if( newLast1 < 0 || newLast2 < 0 || !nodes1.get(newLast1).equals(nodes2.get(newLast2)) )
+            reachedEnd = true;
+            else {
+            last1 = newLast1;
+            last2 = newLast2;
+            }
+        }
+        log("last1=" + last1 + " last2=" + last2);
+        if( increment2 < 0 ) {
+            int tmp = start2;
+            start2 = last2;
+            last2 = tmp;
+        }
+        return new Node[] {nodes1.get(start1), nodes1.get(last1), nodes2.get(start2), nodes2.get(last2)};
+        } else {
+        pos = last1;
+        while( pos != firstPos && pos >= 0 && !nodes2.contains(nodes1.get(pos)) )
+            pos = incrementBy(pos, 1, nodes1.size(), isRing1);
+        if( pos < 0 || pos == firstPos || !nodes2.contains(nodes1.get(pos)) )
+            collideFound = true;
+        }
+    }
+    return null;
     }
     
     private static int incrementBy( int value, int increment, int limit1, boolean isRing ) {
-	int result = value + increment;
-	if( result < 0 )
-	    return isRing ? result + limit1 : -1;
-	else if( result >= limit1 )
-	    return isRing ? result - limit1 : -1;
-	else
-	    return result;
+    int result = value + increment;
+    if( result < 0 )
+        return isRing ? result + limit1 : -1;
+    else if( result >= limit1 )
+        return isRing ? result - limit1 : -1;
+    else
+        return result;
     }
     
     private boolean areSegmentsEqual( RingSegment seg1, RingSegment seg2 ) {
-	List<Node> nodes1 = seg1.getNodes();
-	List<Node> nodes2 = seg2.getNodes();
-	int size = nodes1.size();
-	if( size != nodes2.size() )
-	    return false;
-	boolean reverse = size > 1 && !nodes1.get(0).equals(nodes2.get(0));
-	for( int i = 0; i < size; i++ )
-	    if( !nodes1.get(i).equals(nodes2.get(reverse ? size-1-i : i)) )
-		return false;
-	return true;
+    List<Node> nodes1 = seg1.getNodes();
+    List<Node> nodes2 = seg2.getNodes();
+    int size = nodes1.size();
+    if( size != nodes2.size() )
+        return false;
+    boolean reverse = size > 1 && !nodes1.get(0).equals(nodes2.get(0));
+    for( int i = 0; i < size; i++ )
+        if( !nodes1.get(i).equals(nodes2.get(reverse ? size-1-i : i)) )
+        return false;
+    return true;
     }
 
@@ -213,28 +213,28 @@
      */
     private RingSegment splitRingAt( int segmentIndex, Node n1, Node n2 ) {
-	if( n1.equals(n2) )
-	    throw new IllegalArgumentException("Both nodes are equal, id=" + n1.getUniqueId());
-	RingSegment segment = segments.get(segmentIndex);
-	boolean isRing = segment.isRing();
-	log("Split segment " + segment + " at nodes " + n1.getUniqueId() + " and " + n2.getUniqueId());
-	boolean reversed = segment.getNodes().indexOf(n2) < segment.getNodes().indexOf(n1);
-	if( reversed && !isRing ) {
-	    // order nodes
-	    Node tmp = n1;
-	    n1 = n2;
-	    n2 = tmp;
-	}
-	RingSegment secondPart = isRing ? segment.split(n1, n2) : segment.split(n1);
-	// if secondPart == null, then n1 == firstNode
-	RingSegment thirdPart = isRing ? null : secondPart == null ? segment.split(n2) : secondPart.split(n2);
-	// if secondPart == null, then thirdPart is between n1 and n2
-	// otherwise, thirdPart is between n2 and lastNode
-	// if thirdPart == null, then n2 == lastNode
-	int pos = segmentIndex + 1;
-	if( secondPart != null )
-	    segments.add(pos++, secondPart);
-	if( thirdPart != null )
-	    segments.add(pos++, thirdPart);
-	return isRing || secondPart == null ? segment : secondPart;
+    if( n1.equals(n2) )
+        throw new IllegalArgumentException("Both nodes are equal, id=" + n1.getUniqueId());
+    RingSegment segment = segments.get(segmentIndex);
+    boolean isRing = segment.isRing();
+    log("Split segment " + segment + " at nodes " + n1.getUniqueId() + " and " + n2.getUniqueId());
+    boolean reversed = segment.getNodes().indexOf(n2) < segment.getNodes().indexOf(n1);
+    if( reversed && !isRing ) {
+        // order nodes
+        Node tmp = n1;
+        n1 = n2;
+        n2 = tmp;
+    }
+    RingSegment secondPart = isRing ? segment.split(n1, n2) : segment.split(n1);
+    // if secondPart == null, then n1 == firstNode
+    RingSegment thirdPart = isRing ? null : secondPart == null ? segment.split(n2) : secondPart.split(n2);
+    // if secondPart == null, then thirdPart is between n1 and n2
+    // otherwise, thirdPart is between n2 and lastNode
+    // if thirdPart == null, then n2 == lastNode
+    int pos = segmentIndex + 1;
+    if( secondPart != null )
+        segments.add(pos++, secondPart);
+    if( thirdPart != null )
+        segments.add(pos++, thirdPart);
+    return isRing || secondPart == null ? segment : secondPart;
     }
 
@@ -246,54 +246,54 @@
      */
     public static void redistributeSegments( List<TheRing> rings ) {
-	// build segments map
-	Map<RingSegment, TheRing> segmentMap = new HashMap<>();
-	for( TheRing ring : rings )
-	    for( RingSegment seg : ring.segments )
-		if( !seg.isReference() )
-		    segmentMap.put(seg, ring);
-
-	// rearrange references
-	for( int i = 0; i < rings.size(); i++ ) {
-	    TheRing ring = rings.get(i);
-	    if( ring.countNonReferenceSegments() == 0 ) {
-		// need to find one non-reference segment
-		for( RingSegment seg : ring.segments ) {
-		    TheRing otherRing = segmentMap.get(seg.references);
-		    if( otherRing.countNonReferenceSegments() > 1 ) {
-			// we could check for >0, but it is prone to deadlocking
-			seg.swapReference();
-		    }
-		}
-	    }
-	}
-
-	// initializing source way for each ring
-	for( TheRing ring : rings )
-	    ring.putSourceWayFirst();
+    // build segments map
+    Map<RingSegment, TheRing> segmentMap = new HashMap<>();
+    for( TheRing ring : rings )
+        for( RingSegment seg : ring.segments )
+        if( !seg.isReference() )
+            segmentMap.put(seg, ring);
+
+    // rearrange references
+    for( int i = 0; i < rings.size(); i++ ) {
+        TheRing ring = rings.get(i);
+        if( ring.countNonReferenceSegments() == 0 ) {
+        // need to find one non-reference segment
+        for( RingSegment seg : ring.segments ) {
+            TheRing otherRing = segmentMap.get(seg.references);
+            if( otherRing.countNonReferenceSegments() > 1 ) {
+            // we could check for >0, but it is prone to deadlocking
+            seg.swapReference();
+            }
+        }
+        }
+    }
+
+    // initializing source way for each ring
+    for( TheRing ring : rings )
+        ring.putSourceWayFirst();
     }
 
     private int countNonReferenceSegments() {
-	int count = 0;
-	for( RingSegment seg : segments )
-	    if( !seg.isReference() )
-		count++;
-	return count;
+    int count = 0;
+    for( RingSegment seg : segments )
+        if( !seg.isReference() )
+        count++;
+    return count;
     }
 
     public void putSourceWayFirst() {
-	for( RingSegment seg : segments ) {
-	    if( !seg.isReference() ) {
-		seg.overrideWay(source);
-		return;
-	    }
-	}
+    for( RingSegment seg : segments ) {
+        if( !seg.isReference() ) {
+        seg.overrideWay(source);
+        return;
+        }
+    }
     }
     
     public List<Command> getCommands() {
-	return getCommands(true, null);
+    return getCommands(true, null);
     }
     
     public List<Command> getCommands( Map<Relation, Relation> relationChangeMap ) {
-	return getCommands(true, relationChangeMap);
+    return getCommands(true, relationChangeMap);
     }
     
@@ -303,76 +303,76 @@
      */
     public List<Command> getCommands( boolean createMultipolygon, Map<Relation, Relation> relationChangeMap ) {
-	Way sourceCopy = new Way(source);
-	if( createMultipolygon ) {
-	    Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
-	    relation = new Relation();
-	    relation.put("type", "multipolygon");
-	    for( String key : sourceCopy.keySet() ) {
+    Way sourceCopy = new Way(source);
+    if( createMultipolygon ) {
+        Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
+        relation = new Relation();
+        relation.put("type", "multipolygon");
+        for( String key : sourceCopy.keySet() ) {
                 if( linearTags.contains(key) ) continue;
                 if( key.equals("natural") && sourceCopy.get("natural").equals("coastline") ) continue;
                 relation.put(key, sourceCopy.get(key));
                 sourceCopy.remove(key);
-	    }
-	}
-
-	// build a map of referencing relations
-	Map<Relation, Integer> referencingRelations = new HashMap<>();
-	List<Command> relationCommands = new ArrayList<>();
-	for( OsmPrimitive p : source.getReferrers() ) {
-	    if( p instanceof Relation ) {
-		Relation rel = null;
-		if( relationChangeMap != null ) {
-		    if( relationChangeMap.containsKey((Relation)p) )
-			rel = relationChangeMap.get((Relation)p);
-		    else {
-			rel = new Relation((Relation)p);
-			relationChangeMap.put((Relation)p, rel);
-		    }
-		} else {		    
-		    rel = new Relation((Relation)p);
-		    relationCommands.add(new ChangeCommand((Relation)p, rel));
-		}
-		for( int i = 0; i < rel.getMembersCount(); i++ )
-		    if( rel.getMember(i).getMember().equals(source) )
-			referencingRelations.put(rel, Integer.valueOf(i));
-	    }
-	}
-	// todo: ÐºÐ¾Ð³Ð´Ð° Ð´Ð²Ð° ÐºÐ¾Ð»ÑŒÑ†Ð° Ð¼ÐµÐ½Ñ�ÑŽÑ‚ Ð¾Ð´Ð½Ð¾ Ð¸ Ñ‚Ð¾ Ð¶Ðµ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ðµ, Ð² Ñ�Ð¿Ð¸Ñ�Ð¾Ðº ÐºÐ¾Ð¼Ð°Ð½Ð´ Ð´Ð¾Ð±Ð°Ð²Ð»Ñ�ÐµÑ‚Ñ�Ñ�
-	// Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ Ð±Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ñ� Ð½Ð° Ð½Ð¾Ð²Ð¾Ðµ, Ð° Ð½Ðµ Ð¿Ñ€ÐµÐ´Ñ‹Ð´ÑƒÑ‰ÐµÐ³Ð¾
-	// Ð¿Ð¾Ñ�Ñ‚Ð¾Ð¼Ñƒ Ñ�Ð¾Ñ…Ñ€Ð°Ð½Ñ�ÐµÑ‚Ñ�Ñ� Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¿ÐµÑ€Ð²Ð¾Ðµ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ
-
-	List<Command> commands = new ArrayList<>();
-	boolean foundOwnWay = false;
-	for( RingSegment seg : segments ) {
-	    boolean needAdding = !seg.isWayConstructed();
-	    Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
-	    if( needAdding )
-		commands.add(new AddCommand(w));
-	    if( w.equals(source) ) {
-		if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
-		    sourceCopy.setNodes(seg.getWayNodes());
-		    commands.add(new ChangeCommand(source, sourceCopy));
-		}
-		foundOwnWay = true;
-	    } else {
-		for( Relation rel : referencingRelations.keySet() ) {
-		    int relIndex = referencingRelations.get(rel);
-		    rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
-		}
-	    }
-	    if( createMultipolygon )
-		relation.addMember(new RelationMember("outer", w));
-	}
-	if( !foundOwnWay )
-	    commands.add(new DeleteCommand(source));
-	commands.addAll(relationCommands);
-	if( createMultipolygon )
-	    commands.add(new AddCommand(relation));
-	return commands;
+        }
+    }
+
+    // build a map of referencing relations
+    Map<Relation, Integer> referencingRelations = new HashMap<>();
+    List<Command> relationCommands = new ArrayList<>();
+    for( OsmPrimitive p : source.getReferrers() ) {
+        if( p instanceof Relation ) {
+        Relation rel = null;
+        if( relationChangeMap != null ) {
+            if( relationChangeMap.containsKey((Relation)p) )
+            rel = relationChangeMap.get((Relation)p);
+            else {
+            rel = new Relation((Relation)p);
+            relationChangeMap.put((Relation)p, rel);
+            }
+        } else {            
+            rel = new Relation((Relation)p);
+            relationCommands.add(new ChangeCommand((Relation)p, rel));
+        }
+        for( int i = 0; i < rel.getMembersCount(); i++ )
+            if( rel.getMember(i).getMember().equals(source) )
+            referencingRelations.put(rel, Integer.valueOf(i));
+        }
+    }
+    // todo: ÐºÐ¾Ð³Ð´Ð° Ð´Ð²Ð° ÐºÐ¾Ð»ÑŒÑ†Ð° Ð¼ÐµÐ½Ñ�ÑŽÑ‚ Ð¾Ð´Ð½Ð¾ Ð¸ Ñ‚Ð¾ Ð¶Ðµ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ðµ, Ð² Ñ�Ð¿Ð¸Ñ�Ð¾Ðº ÐºÐ¾Ð¼Ð°Ð½Ð´ Ð´Ð¾Ð±Ð°Ð²Ð»Ñ�ÐµÑ‚Ñ�Ñ�
+    // Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ Ð±Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ñ� Ð½Ð° Ð½Ð¾Ð²Ð¾Ðµ, Ð° Ð½Ðµ Ð¿Ñ€ÐµÐ´Ñ‹Ð´ÑƒÑ‰ÐµÐ³Ð¾
+    // Ð¿Ð¾Ñ�Ñ‚Ð¾Ð¼Ñƒ Ñ�Ð¾Ñ…Ñ€Ð°Ð½Ñ�ÐµÑ‚Ñ�Ñ� Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¿ÐµÑ€Ð²Ð¾Ðµ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ
+
+    List<Command> commands = new ArrayList<>();
+    boolean foundOwnWay = false;
+    for( RingSegment seg : segments ) {
+        boolean needAdding = !seg.isWayConstructed();
+        Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
+        if( needAdding )
+        commands.add(new AddCommand(w));
+        if( w.equals(source) ) {
+        if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
+            sourceCopy.setNodes(seg.getWayNodes());
+            commands.add(new ChangeCommand(source, sourceCopy));
+        }
+        foundOwnWay = true;
+        } else {
+        for( Relation rel : referencingRelations.keySet() ) {
+            int relIndex = referencingRelations.get(rel);
+            rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
+        }
+        }
+        if( createMultipolygon )
+        relation.addMember(new RelationMember("outer", w));
+    }
+    if( !foundOwnWay )
+        commands.add(new DeleteCommand(source));
+    commands.addAll(relationCommands);
+    if( createMultipolygon )
+        commands.add(new AddCommand(relation));
+    return commands;
     }
     
     public static void updateCommandsWithRelations( List<Command> commands, Map<Relation, Relation> relationCache ) {
-	for( Relation src : relationCache.keySet() )
-	    commands.add(new ChangeCommand(src, relationCache.get(src)));
+    for( Relation src : relationCache.keySet() )
+        commands.add(new ChangeCommand(src, relationCache.get(src)));
     }
 
@@ -381,19 +381,19 @@
      */
     public Relation getRelation() {
-	return relation;
+    return relation;
     }
 
     @Override
     public String toString() {
-	StringBuilder sb = new StringBuilder("TheRing@");
-	sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
-	if( segments.isEmpty() )
-	    sb.append("empty");
-	else {
-	    sb.append(segments.get(0));
-	    for( int i = 1; i < segments.size(); i++ )
-		sb.append(", ").append(segments.get(i));
-	}
-	return sb.append(']').toString();
+    StringBuilder sb = new StringBuilder("TheRing@");
+    sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
+    if( segments.isEmpty() )
+        sb.append("empty");
+    else {
+        sb.append(segments.get(0));
+        for( int i = 1; i < segments.size(); i++ )
+        sb.append(", ").append(segments.get(i));
+    }
+    return sb.append(']').toString();
     }
 
@@ -402,11 +402,11 @@
      */
     /*private static void closePolygon( List<Node> base, List<Node> append ) {
-	if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
-	    List<Node> ap2 = new ArrayList<Node>(append);
-	    Collections.reverse(ap2);
-	    append = ap2;
-	}
-	base.remove(base.size() - 1);
-	base.addAll(append);
+    if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
+        List<Node> ap2 = new ArrayList<Node>(append);
+        Collections.reverse(ap2);
+        append = ap2;
+    }
+    base.remove(base.size() - 1);
+    base.addAll(append);
     }*/
 
@@ -415,181 +415,181 @@
      */
     /*private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
-	EastNorth en1 = n1.getEastNorth();
-	EastNorth en2 = n2.getEastNorth();
-	Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
-	return Geometry.nodeInsidePolygon(testNode, polygon);
+    EastNorth en1 = n1.getEastNorth();
+    EastNorth en2 = n2.getEastNorth();
+    Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
+    return Geometry.nodeInsidePolygon(testNode, polygon);
     }*/
     
     private static void log( String s ) {
-//	System.out.println(s);
+//    System.out.println(s);
     }
     
     private static class RingSegment {
-	private List<Node> nodes;
-	private RingSegment references;
-	private Way resultingWay = null;
-	private boolean wasTemplateApplied = false;
-	private boolean isRing;
-
-	/*private RingSegment() {
-	}*/
-
-	public RingSegment( Way w ) {
-	    this(w.getNodes());
-	}
-
-	public RingSegment( List<Node> nodes ) {
-	    this.nodes = nodes;
-	    isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
-	    if( isRing )
-		nodes.remove(nodes.size() - 1);
-	    references = null;
-	}
-
-	/*public RingSegment( RingSegment ref ) {
-	    this.nodes = null;
-	    this.references = ref;
-	}*/
-
-	/**
-	 * Splits this segment at node n. Retains nodes 0..n and moves
-	 * nodes n..N to a separate segment that is returned.
-	 * @param n node at which to split.
-	 * @return new segment, {@code null} if splitting is unnecessary.
-	 */
-	public RingSegment split( Node n ) {
-	    if( nodes == null )
-		throw new IllegalArgumentException("Cannot split segment: it is a reference");
-	    int pos = nodes.indexOf(n);
-	    if( pos <= 0 || pos >= nodes.size() - 1 )
-		return null;
-	    List<Node> newNodes = new ArrayList<>(nodes.subList(pos, nodes.size()));
-	    nodes.subList(pos + 1, nodes.size()).clear();
-	    return new RingSegment(newNodes);
-	}
-
-	/**
-	 * Split this segment as a way at two nodes. If one of them is null or at the end,
-	 * split as an arc. Note: order of nodes is important.
-	 * @return A new segment from n2 to n1.
-	 */
-	public RingSegment split( Node n1, Node n2 ) {
-	    if( nodes == null )
-		throw new IllegalArgumentException("Cannot split segment: it is a reference");
-	    if( !isRing ) {
-		if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
-		    return split(n2);
-		if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
-		    return split(n1);
-		throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
-	    }
-	    int pos1 = nodes.indexOf(n1);
-	    int pos2 = nodes.indexOf(n2);
-	    if( pos1 == pos2 )
-		return null;
-
-	    List<Node> newNodes = new ArrayList<>();
-	    if( pos2 > pos1 ) {
-		newNodes.addAll(nodes.subList(pos2, nodes.size()));
-		newNodes.addAll(nodes.subList(0, pos1 + 1));
-		if( pos2 + 1 < nodes.size() )
-		    nodes.subList(pos2 + 1, nodes.size()).clear();
-		if( pos1 > 0 )
-		    nodes.subList(0, pos1).clear();
-	    } else {
-		newNodes.addAll(nodes.subList(pos2, pos1 + 1));
-		nodes.addAll(new ArrayList<>(nodes.subList(0, pos2 + 1)));
-		nodes.subList(0, pos1).clear();
-	    }
-	    isRing = false;
-	    return new RingSegment(newNodes);
-	}
-
-	public List<Node> getNodes() {
-	    return nodes == null ? references.nodes : nodes;
-	}
-
-	public List<Node> getWayNodes() {
-	    if( nodes == null )
-		throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
-	    List<Node> wayNodes = new ArrayList<>(nodes);
-	    if( isRing )
-		wayNodes.add(wayNodes.get(0));
-	    return wayNodes;
-	}
-
-	public boolean isReference() {
-	    return nodes == null;
-	}
-
-	public boolean isRing() {
-	    return isRing;
-	}
-
-	public void makeReference( RingSegment segment ) {
-	    log(this + " was made a reference to " + segment);
-	    this.nodes = null;
-	    this.references = segment;
-	}
-
-	public void swapReference() {
-	    this.nodes = references.nodes;
-	    references.nodes = null;
-	    references.references = this;
-	    this.references = null;
-	}
-
-	public boolean isWayConstructed() {
-	    return isReference() ? references.isWayConstructed() : resultingWay != null;
-	}
-
-	public Way constructWay( Way template ) {
-	    if( isReference() )
-		return references.constructWay(template);
-	    if( resultingWay == null ) {
-		resultingWay = new Way();
-		resultingWay.setNodes(getWayNodes());
-	    }
-	    if( template != null && !wasTemplateApplied ) {
-		resultingWay.setKeys(template.getKeys());
-		wasTemplateApplied = true;
-	    }
-	    return resultingWay;
-	}
-
-	public void overrideWay( Way source ) {
-	    if( isReference() )
-		references.overrideWay(source);
-	    else {
-		resultingWay = source;
-		wasTemplateApplied = true;
-	    }
-	}
-
-	/**
-	 * Compares two segments with respect to referencing.
-	 * @return true if ways are equals, or one references another.
-	 */
-	/*public boolean isReferencingEqual( RingSegment other ) {
-	    return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
-	}*/
-
-	@Override
-	public String toString() {
-	    StringBuilder sb = new StringBuilder("RingSegment@");
-	    sb.append(this.hashCode()).append('[');
-	    if( isReference() )
-		sb.append("references ").append(references.hashCode());
-	    else if( nodes.isEmpty() )
-		sb.append("empty");
-	    else {
-		if( isRing )
-		    sb.append("ring:");
-		sb.append(nodes.get(0).getUniqueId());
-		for( int i = 1; i < nodes.size(); i++ )
-		    sb.append(',').append(nodes.get(i).getUniqueId());
-	    }
-	    return sb.append(']').toString();
-	}
+    private List<Node> nodes;
+    private RingSegment references;
+    private Way resultingWay = null;
+    private boolean wasTemplateApplied = false;
+    private boolean isRing;
+
+    /*private RingSegment() {
+    }*/
+
+    public RingSegment( Way w ) {
+        this(w.getNodes());
+    }
+
+    public RingSegment( List<Node> nodes ) {
+        this.nodes = nodes;
+        isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
+        if( isRing )
+        nodes.remove(nodes.size() - 1);
+        references = null;
+    }
+
+    /*public RingSegment( RingSegment ref ) {
+        this.nodes = null;
+        this.references = ref;
+    }*/
+
+    /**
+     * Splits this segment at node n. Retains nodes 0..n and moves
+     * nodes n..N to a separate segment that is returned.
+     * @param n node at which to split.
+     * @return new segment, {@code null} if splitting is unnecessary.
+     */
+    public RingSegment split( Node n ) {
+        if( nodes == null )
+        throw new IllegalArgumentException("Cannot split segment: it is a reference");
+        int pos = nodes.indexOf(n);
+        if( pos <= 0 || pos >= nodes.size() - 1 )
+        return null;
+        List<Node> newNodes = new ArrayList<>(nodes.subList(pos, nodes.size()));
+        nodes.subList(pos + 1, nodes.size()).clear();
+        return new RingSegment(newNodes);
+    }
+
+    /**
+     * Split this segment as a way at two nodes. If one of them is null or at the end,
+     * split as an arc. Note: order of nodes is important.
+     * @return A new segment from n2 to n1.
+     */
+    public RingSegment split( Node n1, Node n2 ) {
+        if( nodes == null )
+        throw new IllegalArgumentException("Cannot split segment: it is a reference");
+        if( !isRing ) {
+        if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
+            return split(n2);
+        if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
+            return split(n1);
+        throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
+        }
+        int pos1 = nodes.indexOf(n1);
+        int pos2 = nodes.indexOf(n2);
+        if( pos1 == pos2 )
+        return null;
+
+        List<Node> newNodes = new ArrayList<>();
+        if( pos2 > pos1 ) {
+        newNodes.addAll(nodes.subList(pos2, nodes.size()));
+        newNodes.addAll(nodes.subList(0, pos1 + 1));
+        if( pos2 + 1 < nodes.size() )
+            nodes.subList(pos2 + 1, nodes.size()).clear();
+        if( pos1 > 0 )
+            nodes.subList(0, pos1).clear();
+        } else {
+        newNodes.addAll(nodes.subList(pos2, pos1 + 1));
+        nodes.addAll(new ArrayList<>(nodes.subList(0, pos2 + 1)));
+        nodes.subList(0, pos1).clear();
+        }
+        isRing = false;
+        return new RingSegment(newNodes);
+    }
+
+    public List<Node> getNodes() {
+        return nodes == null ? references.nodes : nodes;
+    }
+
+    public List<Node> getWayNodes() {
+        if( nodes == null )
+        throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
+        List<Node> wayNodes = new ArrayList<>(nodes);
+        if( isRing )
+        wayNodes.add(wayNodes.get(0));
+        return wayNodes;
+    }
+
+    public boolean isReference() {
+        return nodes == null;
+    }
+
+    public boolean isRing() {
+        return isRing;
+    }
+
+    public void makeReference( RingSegment segment ) {
+        log(this + " was made a reference to " + segment);
+        this.nodes = null;
+        this.references = segment;
+    }
+
+    public void swapReference() {
+        this.nodes = references.nodes;
+        references.nodes = null;
+        references.references = this;
+        this.references = null;
+    }
+
+    public boolean isWayConstructed() {
+        return isReference() ? references.isWayConstructed() : resultingWay != null;
+    }
+
+    public Way constructWay( Way template ) {
+        if( isReference() )
+        return references.constructWay(template);
+        if( resultingWay == null ) {
+        resultingWay = new Way();
+        resultingWay.setNodes(getWayNodes());
+        }
+        if( template != null && !wasTemplateApplied ) {
+        resultingWay.setKeys(template.getKeys());
+        wasTemplateApplied = true;
+        }
+        return resultingWay;
+    }
+
+    public void overrideWay( Way source ) {
+        if( isReference() )
+        references.overrideWay(source);
+        else {
+        resultingWay = source;
+        wasTemplateApplied = true;
+        }
+    }
+
+    /**
+     * Compares two segments with respect to referencing.
+     * @return true if ways are equals, or one references another.
+     */
+    /*public boolean isReferencingEqual( RingSegment other ) {
+        return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
+    }*/
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder("RingSegment@");
+        sb.append(this.hashCode()).append('[');
+        if( isReference() )
+        sb.append("references ").append(references.hashCode());
+        else if( nodes.isEmpty() )
+        sb.append("empty");
+        else {
+        if( isRing )
+            sb.append("ring:");
+        sb.append(nodes.get(0).getUniqueId());
+        for( int i = 1; i < nodes.size(); i++ )
+            sb.append(',').append(nodes.get(i).getUniqueId());
+        }
+        return sb.append(']').toString();
+    }
     }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/AssociatedStreetFixer.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/AssociatedStreetFixer.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/AssociatedStreetFixer.java	(revision 30738)
@@ -19,138 +19,138 @@
 public class AssociatedStreetFixer extends RelationFixer {
 
-	public AssociatedStreetFixer() {
-		super("associatedStreet");
-	}
-
-	@Override
-	public boolean isRelationGood(Relation rel) {
-		for (RelationMember m : rel.getMembers()) {
-    		if (m.getType().equals(OsmPrimitiveType.NODE) && !"house".equals(m.getRole())) {
-    		    setWarningMessage(tr("Node without ''house'' role found"));
-    			return false;
-    		}
-    		if (m.getType().equals(OsmPrimitiveType.WAY) && !("house".equals(m.getRole()) || "street".equals(m.getRole()))) {
-    		    setWarningMessage(tr("Way without ''house'' or ''street'' role found"));
-    		    return false;
-    		}
-    		if (m.getType().equals(OsmPrimitiveType.RELATION) && !"house".equals(m.getRole())) {
-    		    setWarningMessage(tr("Relation without ''house'' role found"));
-    			return false;
-    		}
-    	}
-		// relation should have name
-		if (!rel.hasKey("name")) {
-		    setWarningMessage(tr("Relation does not have name"));
-			return false;
-		}
-		// check that all street members have same name as relation (???)
-		String streetName = rel.get("name");
-		if (streetName == null) streetName = "";
-		for (RelationMember m : rel.getMembers()) {
-			if ("street".equals(m.getRole()) && !streetName.equals(m.getWay().get("name"))) {
-			    String anotherName = m.getWay().get("name");
-			    if (anotherName != null && !anotherName.isEmpty()) {
-    			    setWarningMessage(tr("Relation has streets with different names"));
-    			    return false;
-			    }
-			}
-		}
-		clearWarningMessage();
-		return true;
-	}
+    public AssociatedStreetFixer() {
+        super("associatedStreet");
+    }
 
     @Override
-	public Command fixRelation(Relation source) {
-		// any way with highway tag -> street
-		// any way/point/relation with addr:housenumber=* or building=* or type=multipolygon -> house
-		// name - check which name is most used in street members and add to relation
-		// copy this name to the other street members (???)
-		Relation rel = new Relation(source);
-		boolean fixed = false;
+    public boolean isRelationGood(Relation rel) {
+        for (RelationMember m : rel.getMembers()) {
+            if (m.getType().equals(OsmPrimitiveType.NODE) && !"house".equals(m.getRole())) {
+                setWarningMessage(tr("Node without ''house'' role found"));
+                return false;
+            }
+            if (m.getType().equals(OsmPrimitiveType.WAY) && !("house".equals(m.getRole()) || "street".equals(m.getRole()))) {
+                setWarningMessage(tr("Way without ''house'' or ''street'' role found"));
+                return false;
+            }
+            if (m.getType().equals(OsmPrimitiveType.RELATION) && !"house".equals(m.getRole())) {
+                setWarningMessage(tr("Relation without ''house'' role found"));
+                return false;
+            }
+        }
+        // relation should have name
+        if (!rel.hasKey("name")) {
+            setWarningMessage(tr("Relation does not have name"));
+            return false;
+        }
+        // check that all street members have same name as relation (???)
+        String streetName = rel.get("name");
+        if (streetName == null) streetName = "";
+        for (RelationMember m : rel.getMembers()) {
+            if ("street".equals(m.getRole()) && !streetName.equals(m.getWay().get("name"))) {
+                String anotherName = m.getWay().get("name");
+                if (anotherName != null && !anotherName.isEmpty()) {
+                    setWarningMessage(tr("Relation has streets with different names"));
+                    return false;
+                }
+            }
+        }
+        clearWarningMessage();
+        return true;
+    }
 
-		for (int i = 0; i < rel.getMembersCount(); i++) {
-			RelationMember m = rel.getMember(i);
+    @Override
+    public Command fixRelation(Relation source) {
+        // any way with highway tag -> street
+        // any way/point/relation with addr:housenumber=* or building=* or type=multipolygon -> house
+        // name - check which name is most used in street members and add to relation
+        // copy this name to the other street members (???)
+        Relation rel = new Relation(source);
+        boolean fixed = false;
 
-			if (m.isNode()) {
-				Node node = m.getNode();
-				if (!"house".equals(m.getRole()) &&
-						(node.hasKey("building") || node.hasKey("addr:housenumber"))) {
-					fixed = true;
-					rel.setMember(i, new RelationMember("house", node));
-				}
-			} else if (m.isWay()) {
-				Way way = m.getWay();
-				if (!"street".equals(m.getRole()) && way.hasKey("highway")) {
-					fixed = true;
-					rel.setMember(i, new RelationMember("street", way));
-				} else if (!"house".equals(m.getRole()) &&
-						(way.hasKey("building") || way.hasKey("addr:housenumber"))) {
-					fixed = true;
-					rel.setMember(i,  new RelationMember("house", way));
-				}
-			} else if (m.isRelation()) {
-				Relation relation = m.getRelation();
-				if (!"house".equals(m.getRole()) &&
-						(relation.hasKey("building") || relation.hasKey("addr:housenumber") || "multipolygon".equals(relation.get("type")))) {
-					fixed = true;
-					rel.setMember(i, new RelationMember("house", relation));
-				}
-			}
-		}
+        for (int i = 0; i < rel.getMembersCount(); i++) {
+            RelationMember m = rel.getMember(i);
 
-		// fill relation name
-		Map<String, Integer> streetNames = new HashMap<>();
-		for (RelationMember m : rel.getMembers())
-			if ("street".equals(m.getRole()) && m.isWay()) {
-				String name = m.getWay().get("name");
-				if (name == null || name.isEmpty()) continue;
+            if (m.isNode()) {
+                Node node = m.getNode();
+                if (!"house".equals(m.getRole()) &&
+                        (node.hasKey("building") || node.hasKey("addr:housenumber"))) {
+                    fixed = true;
+                    rel.setMember(i, new RelationMember("house", node));
+                }
+            } else if (m.isWay()) {
+                Way way = m.getWay();
+                if (!"street".equals(m.getRole()) && way.hasKey("highway")) {
+                    fixed = true;
+                    rel.setMember(i, new RelationMember("street", way));
+                } else if (!"house".equals(m.getRole()) &&
+                        (way.hasKey("building") || way.hasKey("addr:housenumber"))) {
+                    fixed = true;
+                    rel.setMember(i,  new RelationMember("house", way));
+                }
+            } else if (m.isRelation()) {
+                Relation relation = m.getRelation();
+                if (!"house".equals(m.getRole()) &&
+                        (relation.hasKey("building") || relation.hasKey("addr:housenumber") || "multipolygon".equals(relation.get("type")))) {
+                    fixed = true;
+                    rel.setMember(i, new RelationMember("house", relation));
+                }
+            }
+        }
 
-				Integer count = streetNames.get(name);
+        // fill relation name
+        Map<String, Integer> streetNames = new HashMap<>();
+        for (RelationMember m : rel.getMembers())
+            if ("street".equals(m.getRole()) && m.isWay()) {
+                String name = m.getWay().get("name");
+                if (name == null || name.isEmpty()) continue;
 
-				streetNames.put(name, count != null? count + 1 : 1);
-			}
-		String commonName = "";
-		Integer commonCount = 0;
-		for (Map.Entry<String, Integer> entry : streetNames.entrySet()) {
-			if (entry.getValue() > commonCount) {
-				commonCount = entry.getValue();
-				commonName = entry.getKey();
-			}
-		}
+                Integer count = streetNames.get(name);
 
-		if (!rel.hasKey("name") && !commonName.isEmpty()) {
-			fixed = true;
-			rel.put("name", commonName);
-		} else {
-			commonName = ""; // set empty common name - if we already have name on relation, do not overwrite it
-		}
+                streetNames.put(name, count != null? count + 1 : 1);
+            }
+        String commonName = "";
+        Integer commonCount = 0;
+        for (Map.Entry<String, Integer> entry : streetNames.entrySet()) {
+            if (entry.getValue() > commonCount) {
+                commonCount = entry.getValue();
+                commonName = entry.getKey();
+            }
+        }
 
-		List<Command> commandList = new ArrayList<>();
-		if (fixed) {
-			commandList.add(new ChangeCommand(source, rel));
-		}
+        if (!rel.hasKey("name") && !commonName.isEmpty()) {
+            fixed = true;
+            rel.put("name", commonName);
+        } else {
+            commonName = ""; // set empty common name - if we already have name on relation, do not overwrite it
+        }
 
-		/*if (!commonName.isEmpty())
-		// fill common name to streets
-		for (RelationMember m : rel.getMembers())
-			if ("street".equals(m.getRole()) && m.isWay()) {
-				String name = m.getWay().get("name");
-				if (commonName.equals(name)) continue;
+        List<Command> commandList = new ArrayList<>();
+        if (fixed) {
+            commandList.add(new ChangeCommand(source, rel));
+        }
 
-				// TODO: ask user if he really wants to overwrite street name??
+        /*if (!commonName.isEmpty())
+        // fill common name to streets
+        for (RelationMember m : rel.getMembers())
+            if ("street".equals(m.getRole()) && m.isWay()) {
+                String name = m.getWay().get("name");
+                if (commonName.equals(name)) continue;
 
-				Way oldWay = m.getWay();
-				Way newWay = new Way(oldWay);
-				newWay.put("name", commonName);
+                // TODO: ask user if he really wants to overwrite street name??
 
-				commandList.add(new ChangeCommand(oldWay, newWay));
-			}
-		*/
-		// return results
-		if (commandList.size() == 0)
-			return null;
-		if (commandList.size() == 1)
-			return commandList.get(0);
-		return new SequenceCommand(tr("fix associatedStreet relation"), commandList);
-	}
+                Way oldWay = m.getWay();
+                Way newWay = new Way(oldWay);
+                newWay.put("name", commonName);
+
+                commandList.add(new ChangeCommand(oldWay, newWay));
+            }
+        */
+        // return results
+        if (commandList.size() == 0)
+            return null;
+        if (commandList.size() == 1)
+            return commandList.get(0);
+        return new SequenceCommand(tr("fix associatedStreet relation"), commandList);
+    }
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/BoundaryFixer.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/BoundaryFixer.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/BoundaryFixer.java	(revision 30738)
@@ -16,21 +16,21 @@
 public class BoundaryFixer extends MultipolygonFixer {
 
-	public BoundaryFixer() {
-		super("boundary", "multipolygon");
-	}
+    public BoundaryFixer() {
+        super("boundary", "multipolygon");
+    }
 
-	/**
-	 * For boundary relations both "boundary" and "multipolygon" types are applicable, but
-	 * it should also have key boundary=administrative to be fully boundary.
-	 * @see http://wiki.openstreetmap.org/wiki/Relation:boundary
-	 */
-	@Override
-	public boolean isFixerApplicable(Relation rel) {
-		return super.isFixerApplicable(rel) && "administrative".equals(rel.get("boundary"));
-	}
+    /**
+     * For boundary relations both "boundary" and "multipolygon" types are applicable, but
+     * it should also have key boundary=administrative to be fully boundary.
+     * @see http://wiki.openstreetmap.org/wiki/Relation:boundary
+     */
+    @Override
+    public boolean isFixerApplicable(Relation rel) {
+        return super.isFixerApplicable(rel) && "administrative".equals(rel.get("boundary"));
+    }
 
-	@Override
-	public boolean isRelationGood(Relation rel) {
-		for( RelationMember m : rel.getMembers() ) {
+    @Override
+    public boolean isRelationGood(Relation rel) {
+        for( RelationMember m : rel.getMembers() ) {
             if (m.getType().equals(OsmPrimitiveType.RELATION) && !"subarea".equals(m.getRole())) {
                 setWarningMessage(tr("Relation without ''subarea'' role found"));
@@ -43,29 +43,29 @@
             if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
                 setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
-				return false;
+                return false;
             }
         }
-		clearWarningMessage();
-		return true;
-	}
+        clearWarningMessage();
+        return true;
+    }
 
-	@Override
-	public Command fixRelation(Relation rel) {
-		Relation r = rel;
-		Relation rr = fixMultipolygonRoles(r);
-		boolean fixed = false;
-		if (rr != null) {
-			fixed = true;
-			r = rr;
-		}
-		rr = fixBoundaryRoles(r);
-		if (rr != null) {
-			fixed = true;
-			r = rr;
-		}
-		return fixed ? new ChangeCommand(rel, r) : null;
-	}
+    @Override
+    public Command fixRelation(Relation rel) {
+        Relation r = rel;
+        Relation rr = fixMultipolygonRoles(r);
+        boolean fixed = false;
+        if (rr != null) {
+            fixed = true;
+            r = rr;
+        }
+        rr = fixBoundaryRoles(r);
+        if (rr != null) {
+            fixed = true;
+            r = rr;
+        }
+        return fixed ? new ChangeCommand(rel, r) : null;
+    }
 
-	private Relation fixBoundaryRoles( Relation source ) {
+    private Relation fixBoundaryRoles( Relation source ) {
         Relation r = new Relation(source);
         boolean fixed = false;
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/MultipolygonFixer.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/MultipolygonFixer.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/MultipolygonFixer.java	(revision 30738)
@@ -22,31 +22,31 @@
 public class MultipolygonFixer extends RelationFixer {
 
-	public MultipolygonFixer() {
-		super("multipolygon");
-	}
+    public MultipolygonFixer() {
+        super("multipolygon");
+    }
 
-	protected MultipolygonFixer(String...types) {
-		super(types);
-	}
+    protected MultipolygonFixer(String...types) {
+        super(types);
+    }
 
 
-	@Override
-	public boolean isRelationGood(Relation rel) {
-		for (RelationMember m : rel.getMembers())
-			if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
-			    setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
-			    return false;
-			}
-		clearWarningMessage();
-		return true;
-	}
+    @Override
+    public boolean isRelationGood(Relation rel) {
+        for (RelationMember m : rel.getMembers())
+            if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
+                setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
+                return false;
+            }
+        clearWarningMessage();
+        return true;
+    }
 
-	@Override
-	public Command fixRelation(Relation rel) {
-		Relation rr = fixMultipolygonRoles(rel);
-		return rr != null? new ChangeCommand(rel, rr) : null;
-	}
+    @Override
+    public Command fixRelation(Relation rel) {
+        Relation rr = fixMultipolygonRoles(rel);
+        return rr != null? new ChangeCommand(rel, rr) : null;
+    }
 
-	/**
+    /**
      * Basically, created multipolygon from scratch, and if successful, replace roles with new ones.
      */
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/NothingFixer.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/NothingFixer.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/NothingFixer.java	(revision 30738)
@@ -9,20 +9,20 @@
 public class NothingFixer extends RelationFixer {
 
-	public NothingFixer() {
-		super("");
-	}
-	@Override
-	public boolean isFixerApplicable(Relation rel) {
-		return true;
-	}
-	@Override
-	public boolean isRelationGood(Relation rel) {
-		return true;
-	}
+    public NothingFixer() {
+        super("");
+    }
+    @Override
+    public boolean isFixerApplicable(Relation rel) {
+        return true;
+    }
+    @Override
+    public boolean isRelationGood(Relation rel) {
+        return true;
+    }
 
-	@Override
-	public Command fixRelation(Relation rel) {
-		return null;
-	}
+    @Override
+    public Command fixRelation(Relation rel) {
+        return null;
+    }
 
 }
Index: applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/RelationFixer.java
===================================================================
--- applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/RelationFixer.java	(revision 30737)
+++ applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/RelationFixer.java	(revision 30738)
@@ -15,58 +15,58 @@
 public abstract class RelationFixer {
 
-	private List<String> applicableTypes;
-	private SortAndFixAction sortAndFixAction;
+    private List<String> applicableTypes;
+    private SortAndFixAction sortAndFixAction;
 
-	/**
-	 * Construct new RelationFixer by a list of applicable types
-	 * @param types
-	 */
-	public RelationFixer(String... types) {
-	    applicableTypes = new ArrayList<>();
-		for(String type: types) {
-			applicableTypes.add(type);
-		}
-	}
+    /**
+     * Construct new RelationFixer by a list of applicable types
+     * @param types
+     */
+    public RelationFixer(String... types) {
+        applicableTypes = new ArrayList<>();
+        for(String type: types) {
+            applicableTypes.add(type);
+        }
+    }
 
-	/**
-	 * Check if given relation is of needed type. You may override this method to check first type
-	 * and then check desired relation properties.
-	 * Note that this only verifies if current RelationFixer can be used to check and fix given relation
-	 * Deeper relation checking is at {@link isRelationGood}
-	 *
-	 * @param rel Relation to check
-	 * @return true if relation can be verified by current RelationFixer
-	 */
-	public boolean isFixerApplicable(Relation rel) {
-		if (rel == null)
-			return false;
-		if (!rel.hasKey("type"))
-			return false;
+    /**
+     * Check if given relation is of needed type. You may override this method to check first type
+     * and then check desired relation properties.
+     * Note that this only verifies if current RelationFixer can be used to check and fix given relation
+     * Deeper relation checking is at {@link isRelationGood}
+     *
+     * @param rel Relation to check
+     * @return true if relation can be verified by current RelationFixer
+     */
+    public boolean isFixerApplicable(Relation rel) {
+        if (rel == null)
+            return false;
+        if (!rel.hasKey("type"))
+            return false;
 
-		String type = rel.get("type");
-		for(String oktype: applicableTypes)
-			if (oktype.equals(type))
-				return true;
+        String type = rel.get("type");
+        for(String oktype: applicableTypes)
+            if (oktype.equals(type))
+                return true;
 
-		return false;
-	}
+        return false;
+    }
 
-	/**
-	 * Check if given relation is OK. That means if all roles are given properly, all tags exist as expected etc.
-	 * Should be written in children classes.
-	 *
-	 * @param rel Relation to verify
-	 * @return true if given relation is OK
-	 */
-	public abstract boolean isRelationGood(Relation rel);
+    /**
+     * Check if given relation is OK. That means if all roles are given properly, all tags exist as expected etc.
+     * Should be written in children classes.
+     *
+     * @param rel Relation to verify
+     * @return true if given relation is OK
+     */
+    public abstract boolean isRelationGood(Relation rel);
 
-	/**
-	 * Fix relation and return new relation with fixed tags, roles etc.
-	 * Note that is not obligatory to return true for isRelationGood for new relation
-	 *
-	 * @param rel Relation to fix
-	 * @return command that fixes the relation {@code null} if it cannot be fixed or is already OK
-	 */
-	public abstract Command fixRelation(Relation rel);
+    /**
+     * Fix relation and return new relation with fixed tags, roles etc.
+     * Note that is not obligatory to return true for isRelationGood for new relation
+     *
+     * @param rel Relation to fix
+     * @return command that fixes the relation {@code null} if it cannot be fixed or is already OK
+     */
+    public abstract Command fixRelation(Relation rel);
 
     public void setFixAction(SortAndFixAction sortAndFixAction) {
Index: applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java
===================================================================
--- applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java	(revision 30738)
@@ -68,6 +68,6 @@
 import org.openstreetmap.josm.gui.ExtendedDialog;
 import org.openstreetmap.josm.gui.widgets.MultiSplitLayout;
+import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node;
 import org.openstreetmap.josm.gui.widgets.MultiSplitPane;
-import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node;
 import org.openstreetmap.josm.plugins.roadsigns.RoadSignsPlugin.PresetMetaData;
 import org.openstreetmap.josm.plugins.roadsigns.Sign.SignParameter;
@@ -103,5 +103,5 @@
     protected JEditorPane info;
     protected JScrollPane scrollInfo;
-    
+
     private MultiSplitPane multiSplitPane;
 
@@ -150,10 +150,9 @@
                 Node model = multiSplitPane.getMultiSplitLayout().getModel();
                 File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
-                try {
+                try (
                     XMLEncoder xmlenc = new XMLEncoder(
                             new BufferedOutputStream(new FileOutputStream(f))
-                    );
+                    )) {
                     xmlenc.writeObject(model);
-                    xmlenc.close();
                 } catch (FileNotFoundException ex) {
                     Main.warn("unable to write dialog layout: "+ex);
@@ -163,5 +162,4 @@
         super.setVisible(visible);
     }
-
 
     private Command createCommand(Collection<OsmPrimitive> selPrim) {
@@ -198,13 +196,10 @@
 
         multiSplitPane = new MultiSplitPane();
-        try {
-            File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
-            XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(f)));
+        File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
+        try (XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(f)))) {
             Node model = (Node) decoder.readObject();
-            decoder.close();
             multiSplitPane.getMultiSplitLayout().setModel(model);
             multiSplitPane.getMultiSplitLayout().setFloatingDividers(false);
-        }
-        catch (Exception ex) {
+        } catch (Exception ex) {
             Node modelRoot = MultiSplitLayout.parseModel(layoutDef);
             multiSplitPane.getMultiSplitLayout().setModel(modelRoot);
@@ -225,8 +220,8 @@
         info.setBackground(this.getBackground());
         info.addHyperlinkListener(new HyperlinkListener() {
-            public void hyperlinkUpdate(HyperlinkEvent e) {
+            @Override
+			public void hyperlinkUpdate(HyperlinkEvent e) {
                 if (e == null || e.getURL() == null)
                     return;
-                System.out.println(e.getURL());
                 if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                     OpenBrowser.displayUrl(e.getURL().toString());
@@ -472,13 +467,16 @@
                         }
                         class TFDocumentListener implements DocumentListener {
-                            public void insertUpdate(DocumentEvent e) {
+                            @Override
+							public void insertUpdate(DocumentEvent e) {
                                 update();
                             }
 
-                            public void removeUpdate(DocumentEvent e) {
+                            @Override
+							public void removeUpdate(DocumentEvent e) {
                                 update();
                             }
 
-                            public void changedUpdate(DocumentEvent e) {
+                            @Override
+							public void changedUpdate(DocumentEvent e) {
                                 update();
                             }
@@ -540,5 +538,6 @@
         String[][] data = {{}};
         previewTable = new JTable(data, columnNames) {
-            public String getToolTipText(MouseEvent e) {
+            @Override
+			public String getToolTipText(MouseEvent e) {
                 int rowIndex = rowAtPoint(e.getPoint());
                 int colIndex = columnAtPoint(e.getPoint());
@@ -564,5 +563,6 @@
         addTrafficSignTag.setSelected(Main.pref.getBoolean("plugin.roadsigns.addTrafficSignTag"));
         addTrafficSignTag.addActionListener(new ActionListener() {
-            public void actionPerformed(ActionEvent e) {
+            @Override
+			public void actionPerformed(ActionEvent e) {
                 previewModel.update();
             }
@@ -581,13 +581,16 @@
         String[] header = {tr("Key"), tr("Value")};
 
-        public int getRowCount() {
+        @Override
+		public int getRowCount() {
             return keys.size();
         }
 
-        public int getColumnCount() {
+        @Override
+		public int getColumnCount() {
             return 2;
         }
 
-        public Object getValueAt(int rowIndex, int columnIndex) {
+        @Override
+		public Object getValueAt(int rowIndex, int columnIndex) {
             if (columnIndex == 0) {
                 return keys.get(rowIndex);
@@ -758,5 +761,6 @@
             /* scroll up again */
             SwingUtilities.invokeLater(new Runnable(){
-                public void run() {
+                @Override
+				public void run() {
                     scrollInfo.getVerticalScrollBar().setValue(0);
                 }
@@ -818,9 +822,11 @@
         }
 
-        public Dimension getPreferredScrollableViewportSize() {
+        @Override
+		public Dimension getPreferredScrollableViewportSize() {
             return super.getPreferredSize();
         }
 
-        public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) {
+        @Override
+		public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) {
             final int FRAC = 20;
             int inc = (orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth()) / FRAC;
@@ -828,13 +834,16 @@
         }
 
-        public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) {
+        @Override
+		public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) {
             return orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth();
         }
 
-        public boolean getScrollableTracksViewportWidth() {
+        @Override
+		public boolean getScrollableTracksViewportWidth() {
             return true;
         }
 
-        public boolean getScrollableTracksViewportHeight() {
+        @Override
+		public boolean getScrollableTracksViewportHeight() {
             return false;
         }
Index: applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsPlugin.java
===================================================================
--- applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsPlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsPlugin.java	(revision 30738)
@@ -24,5 +24,4 @@
 import javax.swing.JOptionPane;
 
-import org.xml.sax.SAXException;
 import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.actions.JosmAction;
@@ -36,4 +35,5 @@
 import org.openstreetmap.josm.tools.Shortcut;
 import org.openstreetmap.josm.tools.Utils;
+import org.xml.sax.SAXException;
 
 public class RoadSignsPlugin extends Plugin {
@@ -79,5 +79,6 @@
         }
 
-        public void actionPerformed(ActionEvent e) {
+        @Override
+		public void actionPerformed(ActionEvent e) {
             String code = Main.pref.get("plugin.roadsigns.preset.selection", null);
             if (code == null) {
@@ -241,5 +242,6 @@
      * Returns an inputstream from urls, files and classloaders, depending on the name.
      */
-    public static InputStream getInputStream(String source) throws IOException {
+    @SuppressWarnings("resource")
+	public static InputStream getInputStream(String source) throws IOException {
         InputStream in = null;
         if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://")) {
Index: applications/editors/josm/plugins/routes/.settings/org.eclipse.jdt.ui.prefs
===================================================================
--- applications/editors/josm/plugins/routes/.settings/org.eclipse.jdt.ui.prefs	(revision 30737)
+++ applications/editors/josm/plugins/routes/.settings/org.eclipse.jdt.ui.prefs	(revision 30738)
@@ -1,3 +1,2 @@
-#Fri Jan 15 16:11:57 CET 2010
 eclipse.preferences.version=1
 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
@@ -9,4 +8,5 @@
 sp_cleanup.add_missing_nls_tags=false
 sp_cleanup.add_missing_override_annotations=false
+sp_cleanup.add_missing_override_annotations_interface_methods=false
 sp_cleanup.add_serial_version_id=false
 sp_cleanup.always_use_blocks=true
@@ -14,8 +14,10 @@
 sp_cleanup.always_use_this_for_non_static_field_access=false
 sp_cleanup.always_use_this_for_non_static_method_access=false
+sp_cleanup.convert_functional_interfaces=false
 sp_cleanup.convert_to_enhanced_for_loop=false
-sp_cleanup.correct_indentation=true
+sp_cleanup.correct_indentation=false
 sp_cleanup.format_source_code=false
 sp_cleanup.format_source_code_changes_only=false
+sp_cleanup.insert_inferred_type_arguments=false
 sp_cleanup.make_local_variable_final=false
 sp_cleanup.make_parameters_final=false
@@ -33,4 +35,5 @@
 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
 sp_cleanup.remove_private_constructors=true
+sp_cleanup.remove_redundant_type_arguments=false
 sp_cleanup.remove_trailing_whitespaces=true
 sp_cleanup.remove_trailing_whitespaces_all=true
@@ -46,6 +49,8 @@
 sp_cleanup.sort_members=false
 sp_cleanup.sort_members_all=false
+sp_cleanup.use_anonymous_class_creation=false
 sp_cleanup.use_blocks=false
 sp_cleanup.use_blocks_only_for_return_and_throw=false
+sp_cleanup.use_lambda=false
 sp_cleanup.use_parentheses_in_expressions=false
 sp_cleanup.use_this_for_non_static_field_access=false
@@ -53,2 +58,3 @@
 sp_cleanup.use_this_for_non_static_method_access=false
 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
+sp_cleanup.use_type_arguments=false
Index: applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/RoutesPlugin.java
===================================================================
--- applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/RoutesPlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/RoutesPlugin.java	(revision 30738)
@@ -19,5 +19,4 @@
 import org.openstreetmap.josm.gui.layer.Layer;
 import org.openstreetmap.josm.gui.layer.OsmDataLayer;
-
 import org.openstreetmap.josm.plugins.Plugin;
 import org.openstreetmap.josm.plugins.PluginInformation;
@@ -36,22 +35,20 @@
         File routesFile = new File(getPluginDir() + File.separator + "routes.xml");
         if (!routesFile.exists()) {
-            System.out.println("File with route definitions doesn't exist, using default");
+            Main.info("File with route definitions doesn't exist, using default");
 
             try {
                 routesFile.getParentFile().mkdir();
-                OutputStream outputStream = new FileOutputStream(routesFile);
-                InputStream inputStream = Routes.class.getResourceAsStream("routes.xml");
-
-                byte[] b = new byte[512];
-                int read;
-                while ((read = inputStream.read(b)) != -1) {
-                    outputStream.write(b, 0, read);
+                try (
+                    OutputStream outputStream = new FileOutputStream(routesFile);
+                    InputStream inputStream = Routes.class.getResourceAsStream("routes.xml");
+                ) {
+                    byte[] b = new byte[512];
+                    int read;
+                    while ((read = inputStream.read(b)) != -1) {
+                        outputStream.write(b, 0, read);
+                    }
                 }
-
-                outputStream.close();
-                inputStream.close();
-
             } catch (IOException e) {
-                e.printStackTrace();
+                Main.error(e);
             }
         }
@@ -62,5 +59,5 @@
             Unmarshaller unmarshaller = context.createUnmarshaller();
             Routes routes = (Routes)unmarshaller.unmarshal(
-                new FileInputStream(getPluginDir() + File.separator + "routes.xml"));
+                    new FileInputStream(getPluginDir() + File.separator + "routes.xml"));
             for (RoutesXMLLayer layer:routes.getLayer()) {
                 if (layer.isEnabled()) {
@@ -77,5 +74,5 @@
 
     public void activeLayerChange(Layer oldLayer, Layer newLayer) {
-        // TODO Auto-generated method stub
+        // Do nothing
     }
 
@@ -117,4 +114,3 @@
         checkLayers();
     }
-
 }
Index: applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/paint/AbstractLinePainter.java
===================================================================
--- applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/paint/AbstractLinePainter.java	(revision 30737)
+++ applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/paint/AbstractLinePainter.java	(revision 30738)
@@ -17,164 +17,164 @@
 public abstract class AbstractLinePainter implements PathPainter {
 
-	// Following two method copied from http://blog.persistent.info/2004/03/java-lineline-intersections.html
-	protected boolean getLineLineIntersection(Line2D.Double l1,
-			Line2D.Double l2,
-			Point intersection)
-	{
-		double  x1 = l1.getX1(), y1 = l1.getY1(),
-		x2 = l1.getX2(), y2 = l1.getY2(),
-		x3 = l2.getX1(), y3 = l2.getY1(),
-		x4 = l2.getX2(), y4 = l2.getY2();
-		double dx1 = x2 - x1;
-		double dx2 = x4 - x3;
-		double dy1 = y2 - y1;
-		double dy2 = y4 - y3;
+    // Following two method copied from http://blog.persistent.info/2004/03/java-lineline-intersections.html
+    protected boolean getLineLineIntersection(Line2D.Double l1,
+            Line2D.Double l2,
+            Point intersection)
+    {
+        double  x1 = l1.getX1(), y1 = l1.getY1(),
+        x2 = l1.getX2(), y2 = l1.getY2(),
+        x3 = l2.getX1(), y3 = l2.getY1(),
+        x4 = l2.getX2(), y4 = l2.getY2();
+        double dx1 = x2 - x1;
+        double dx2 = x4 - x3;
+        double dy1 = y2 - y1;
+        double dy2 = y4 - y3;
 
-		double ua = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dy2 * dx1 - dx2 * dy1);
+        double ua = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dy2 * dx1 - dx2 * dy1);
 
-		if (Math.abs(dy2 * dx1 - dx2 * dy1) < 0.0001) {
-			intersection.x = (int)l1.x2;
-			intersection.y = (int)l1.y2;
-			return false;
-		} else {
-			intersection.x = (int)(x1 + ua * (x2 - x1));
-			intersection.y = (int)(y1 + ua * (y2 - y1));
-		}
+        if (Math.abs(dy2 * dx1 - dx2 * dy1) < 0.0001) {
+            intersection.x = (int)l1.x2;
+            intersection.y = (int)l1.y2;
+            return false;
+        } else {
+            intersection.x = (int)(x1 + ua * (x2 - x1));
+            intersection.y = (int)(y1 + ua * (y2 - y1));
+        }
 
-		return true;
-	}
+        return true;
+    }
 
-	protected double det(double a, double b, double c, double d)
-	{
-		return a * d - b * c;
-	}
+    protected double det(double a, double b, double c, double d)
+    {
+        return a * d - b * c;
+    }
 
-	protected Point shiftPoint(Point2D p1, Point2D p2, double shift) {
-		double dx = p2.getX() - p1.getX();
-		double dy = p2.getY() - p1.getY();
+    protected Point shiftPoint(Point2D p1, Point2D p2, double shift) {
+        double dx = p2.getX() - p1.getX();
+        double dy = p2.getY() - p1.getY();
 
-		// Perpendicular vector
-		double ndx = -dy;
-		double ndy = dx;
+        // Perpendicular vector
+        double ndx = -dy;
+        double ndy = dx;
 
-		// Normalize
-		double length = Math.sqrt(ndx * ndx + ndy * ndy);
-		ndx = ndx / length;
-		ndy = ndy / length;
+        // Normalize
+        double length = Math.sqrt(ndx * ndx + ndy * ndy);
+        ndx = ndx / length;
+        ndy = ndy / length;
 
-		return new Point((int)(p1.getX() + shift * ndx), (int)(p1.getY() + shift * ndy));
-	}
+        return new Point((int)(p1.getX() + shift * ndx), (int)(p1.getY() + shift * ndy));
+    }
 
-	protected Line2D.Double shiftLine(Point2D p1, Point2D p2, double shift) {
-		double dx = p2.getX() - p1.getX();
-		double dy = p2.getY() - p1.getY();
+    protected Line2D.Double shiftLine(Point2D p1, Point2D p2, double shift) {
+        double dx = p2.getX() - p1.getX();
+        double dy = p2.getY() - p1.getY();
 
-		Point2D point1 = shiftPoint(p1, p2, shift);
-		Point2D point2 = new Point2D.Double(point1.getX() + dx, point1.getY() + dy);
+        Point2D point1 = shiftPoint(p1, p2, shift);
+        Point2D point2 = new Point2D.Double(point1.getX() + dx, point1.getY() + dy);
 
-		return new Line2D.Double(
-				point1, point2);
-	}
+        return new Line2D.Double(
+                point1, point2);
+    }
 
-	protected GeneralPath getPath(Graphics2D g, MapView mapView, List<Node> nodes, double shift) {
+    protected GeneralPath getPath(Graphics2D g, MapView mapView, List<Node> nodes, double shift) {
 
-		GeneralPath path = new GeneralPath();
+        GeneralPath path = new GeneralPath();
 
-		if (nodes.size() < 2) {
-			return path;
-		}
+        if (nodes.size() < 2) {
+            return path;
+        }
 
-		Point p1 = null;
-		Point p2 = null;
-		Point p3 = null;
-		Point lastPoint = null;
+        Point p1 = null;
+        Point p2 = null;
+        Point p3 = null;
+        Point lastPoint = null;
 
-		for (Node n: nodes) {
-			Point p = mapView.getPoint(n);
+        for (Node n: nodes) {
+            Point p = mapView.getPoint(n);
 
-			if (!p.equals(p3)) {
-				p1 = p2;
-				p2 = p3;
-				p3 = p;
-			} else {
-				continue;
-			}
+            if (!p.equals(p3)) {
+                p1 = p2;
+                p2 = p3;
+                p3 = p;
+            } else {
+                continue;
+            }
 
-			p = null;
-			if (p2 != null) {
-				if (p1 == null) {
-					p = shiftPoint(p2, p3, shift);
-				} else {
-					Line2D.Double line1 = shiftLine(p1, p2, shift);
-					Line2D.Double line2 = shiftLine(p2, p3, shift);
+            p = null;
+            if (p2 != null) {
+                if (p1 == null) {
+                    p = shiftPoint(p2, p3, shift);
+                } else {
+                    Line2D.Double line1 = shiftLine(p1, p2, shift);
+                    Line2D.Double line2 = shiftLine(p2, p3, shift);
 
-					/*path.moveTo((float)line1.x1, (float)line1.y1);
+                    /*path.moveTo((float)line1.x1, (float)line1.y1);
                     path.lineTo((float)line1.x2, (float)line1.y2);
                     path.moveTo((float)line2.x1, (float)line2.y1);
                     path.lineTo((float)line2.x2, (float)line2.y2);*/
 
-					p = new Point();
-					if (!getLineLineIntersection(line1, line2, p)) {
-						p = null;
-					} else {
-						int dx = p.x - p2.x;
-						int dy = p.y - p2.y;
-						int distance = (int)Math.sqrt(dx * dx + dy * dy);
-						if (distance > 10) {
-							p.x = p2.x + dx / (distance / 10);
-							p.y = p2.y + dy / (distance / 10);
-						}
-					}
-				}
-			}
+                    p = new Point();
+                    if (!getLineLineIntersection(line1, line2, p)) {
+                        p = null;
+                    } else {
+                        int dx = p.x - p2.x;
+                        int dy = p.y - p2.y;
+                        int distance = (int)Math.sqrt(dx * dx + dy * dy);
+                        if (distance > 10) {
+                            p.x = p2.x + dx / (distance / 10);
+                            p.y = p2.y + dy / (distance / 10);
+                        }
+                    }
+                }
+            }
 
-			if (p != null && lastPoint != null) {
-				drawSegment(g, mapView, path, lastPoint, p);
-			}
-			if (p != null) {
-				lastPoint = p;
-			}
-		}
+            if (p != null && lastPoint != null) {
+                drawSegment(g, mapView, path, lastPoint, p);
+            }
+            if (p != null) {
+                lastPoint = p;
+            }
+        }
 
-		if (p2 != null && p3 != null && lastPoint != null) {
-			p3 = shiftPoint(p3, p2, -shift);
-			drawSegment(g, mapView, path, lastPoint, p3);
-		}
+        if (p2 != null && p3 != null && lastPoint != null) {
+            p3 = shiftPoint(p3, p2, -shift);
+            drawSegment(g, mapView, path, lastPoint, p3);
+        }
 
-		return path;
-	}
+        return path;
+    }
 
-	private void drawSegment(Graphics2D g, NavigatableComponent nc, GeneralPath path, Point p1, Point p2) {
-		boolean drawIt = false;
-		if (Main.isOpenjdk) {
-			/**
-			 * Work around openjdk bug. It leads to drawing artefacts when zooming in a lot. (#4289, #4424)
-			 * (It looks like int overflow when clipping.) We do custom clipping.
-			 */
-			Rectangle bounds = g.getClipBounds();
-			bounds.grow(100, 100);                  // avoid arrow heads at the border
-			LineClip clip = new LineClip(p1, p2, bounds);
-			drawIt = clip.execute();
-			if (drawIt) {
-				p1 = clip.getP1();
-				p2 = clip.getP2();
-			}
-		} else {
-			drawIt = isSegmentVisible(nc, p1, p2);
-		}
-		if (drawIt) {
-			/* draw segment line */
-			path.moveTo(p1.x, p1.y);
-			path.lineTo(p2.x, p2.y);
-		}
-	}
+    private void drawSegment(Graphics2D g, NavigatableComponent nc, GeneralPath path, Point p1, Point p2) {
+        boolean drawIt = false;
+        if (Main.isOpenjdk) {
+            /**
+             * Work around openjdk bug. It leads to drawing artefacts when zooming in a lot. (#4289, #4424)
+             * (It looks like int overflow when clipping.) We do custom clipping.
+             */
+            Rectangle bounds = g.getClipBounds();
+            bounds.grow(100, 100);                  // avoid arrow heads at the border
+            LineClip clip = new LineClip(p1, p2, bounds);
+            drawIt = clip.execute();
+            if (drawIt) {
+                p1 = clip.getP1();
+                p2 = clip.getP2();
+            }
+        } else {
+            drawIt = isSegmentVisible(nc, p1, p2);
+        }
+        if (drawIt) {
+            /* draw segment line */
+            path.moveTo(p1.x, p1.y);
+            path.lineTo(p2.x, p2.y);
+        }
+    }
 
-	private boolean isSegmentVisible(NavigatableComponent nc, Point p1, Point p2) {
-		if ((p1.x < 0) && (p2.x < 0)) return false;
-		if ((p1.y < 0) && (p2.y < 0)) return false;
-		if ((p1.x > nc.getWidth()) && (p2.x > nc.getWidth())) return false;
-		if ((p1.y > nc.getHeight()) && (p2.y > nc.getHeight())) return false;
-		return true;
-	}
+    private boolean isSegmentVisible(NavigatableComponent nc, Point p1, Point p2) {
+        if ((p1.x < 0) && (p2.x < 0)) return false;
+        if ((p1.y < 0) && (p2.y < 0)) return false;
+        if ((p1.x > nc.getWidth()) && (p2.x > nc.getWidth())) return false;
+        if ((p1.y > nc.getHeight()) && (p2.y > nc.getHeight())) return false;
+        return true;
+    }
 
 
Index: applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xml
===================================================================
--- applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xml	(revision 30737)
+++ applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xml	(revision 30738)
@@ -2,32 +2,32 @@
 <routes xmlns="http://www.example.org/routes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/routes routes.xsd ">
 <!-- pattern is the same pattern as used in SearchAction -->
-	<layer name="Czech hiking trails">
-		<route color="#FF0000">
-			<pattern>
-			((type:relation | type:way) kct_red=*) | (color=red type=route route=hiking network="cz:kct")
-			</pattern>
-		</route>
-		<route color="#FFFF00">
-			<pattern>
-			((type:relation | type:way) kct_yellow=*) | (color=yellow type=route route=hiking network="cz:kct")
-			</pattern>			
-		</route>
-		<route color="#0000FF">
-			<pattern>
-			((type:relation | type:way) kct_blue=*) | (color=blue type=route route=hiking network="cz:kct")
-			</pattern>
-		</route>
-		<route color="#00FF00">
-			<pattern>
-			((type:relation | type:way) kct_green=*) | (color=green type=route route=hiking network="cz:kct")
-			</pattern>		
-		</route>
-	</layer>
-	<layer name="Cycle routes">
-		<route color="#FF00FF">
-			<pattern>
-			(type:way (ncn=* | (lcn=* | rcn=* ))) | (type:relation type=route route=bicycle)
-			</pattern>
-		</route>
-	</layer>
+    <layer name="Czech hiking trails">
+        <route color="#FF0000">
+            <pattern>
+            ((type:relation | type:way) kct_red=*) | (color=red type=route route=hiking network="cz:kct")
+            </pattern>
+        </route>
+        <route color="#FFFF00">
+            <pattern>
+            ((type:relation | type:way) kct_yellow=*) | (color=yellow type=route route=hiking network="cz:kct")
+            </pattern>            
+        </route>
+        <route color="#0000FF">
+            <pattern>
+            ((type:relation | type:way) kct_blue=*) | (color=blue type=route route=hiking network="cz:kct")
+            </pattern>
+        </route>
+        <route color="#00FF00">
+            <pattern>
+            ((type:relation | type:way) kct_green=*) | (color=green type=route route=hiking network="cz:kct")
+            </pattern>        
+        </route>
+    </layer>
+    <layer name="Cycle routes">
+        <route color="#FF00FF">
+            <pattern>
+            (type:way (ncn=* | (lcn=* | rcn=* ))) | (type:relation type=route route=bicycle)
+            </pattern>
+        </route>
+    </layer>
 </routes>
Index: applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xsd
===================================================================
--- applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xsd	(revision 30737)
+++ applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xsd	(revision 30738)
@@ -11,35 +11,35 @@
 
 <annotation>
-	<appinfo>
-		<jxb:schemaBindings>	
-			<jxb:nameXmlTransform>
-				<jxb:typeName prefix="RoutesXML"/>
-			</jxb:nameXmlTransform>
-		</jxb:schemaBindings>
-	</appinfo>
+    <appinfo>
+        <jxb:schemaBindings>    
+            <jxb:nameXmlTransform>
+                <jxb:typeName prefix="RoutesXML"/>
+            </jxb:nameXmlTransform>
+        </jxb:schemaBindings>
+    </appinfo>
 </annotation>
 
 <element name="routes">
-	<complexType>
-		<sequence>
-			<element name="layer" type="tns:layer" minOccurs="0" maxOccurs="unbounded"/>
-		</sequence>
-	</complexType>
+    <complexType>
+        <sequence>
+            <element name="layer" type="tns:layer" minOccurs="0" maxOccurs="unbounded"/>
+        </sequence>
+    </complexType>
 </element>
 
 <complexType name="layer">
-	<sequence>
-		<element name="route" type="tns:route" minOccurs="0" maxOccurs="unbounded"/>
-	</sequence>
-	<attribute name="name" type="string"/>
-	<attribute name="enabled" type="boolean" default="true"/>
+    <sequence>
+        <element name="route" type="tns:route" minOccurs="0" maxOccurs="unbounded"/>
+    </sequence>
+    <attribute name="name" type="string"/>
+    <attribute name="enabled" type="boolean" default="true"/>
 </complexType>
 
 <complexType name="route">
-	<sequence>
-		<element name="pattern" type="string"/>		
-	</sequence>
-	<attribute name="color" type="string"/>
-	<attribute name="enabled" type="boolean" default="true"/>
+    <sequence>
+        <element name="pattern" type="string"/>        
+    </sequence>
+    <attribute name="color" type="string"/>
+    <attribute name="enabled" type="boolean" default="true"/>
 </complexType>
 
Index: applications/editors/josm/plugins/sds/.settings/org.eclipse.jdt.core.prefs
===================================================================
--- applications/editors/josm/plugins/sds/.settings/org.eclipse.jdt.core.prefs	(revision 30737)
+++ applications/editors/josm/plugins/sds/.settings/org.eclipse.jdt.core.prefs	(revision 30738)
@@ -40,5 +40,5 @@
 org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
 org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
+org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
 org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
 org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/DetermineSdsModificationsUploadHook.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/DetermineSdsModificationsUploadHook.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/DetermineSdsModificationsUploadHook.java	(revision 30738)
@@ -32,144 +32,144 @@
 public class DetermineSdsModificationsUploadHook implements UploadHook
 {
-	private SeparateDataStorePlugin plugin;
+    private SeparateDataStorePlugin plugin;
 
-	DetermineSdsModificationsUploadHook(SeparateDataStorePlugin plugin)	{
-		this.plugin = plugin;
-	}
-	
+    DetermineSdsModificationsUploadHook(SeparateDataStorePlugin plugin)    {
+        this.plugin = plugin;
+    }
+    
     public boolean checkUpload(APIDataSet apiDataSet) {
-    	
-    	ArrayList<OsmPrimitive> droplist = new ArrayList<>();
-    	
-    	// check deleted primitives for special tags.
-    	for (OsmPrimitive del : apiDataSet.getPrimitivesToDelete()) {
-    		IPrimitive old = plugin.getOriginalPrimitive(del);
-    		if (hasSpecialTags(old)) {
-    			// request deletion of all tags for this object on special server.
-    			plugin.enqueueForUpload(del, new HashMap<String, String>(), false);
-    		}
-    	}
+        
+        ArrayList<OsmPrimitive> droplist = new ArrayList<>();
+        
+        // check deleted primitives for special tags.
+        for (OsmPrimitive del : apiDataSet.getPrimitivesToDelete()) {
+            IPrimitive old = plugin.getOriginalPrimitive(del);
+            if (hasSpecialTags(old)) {
+                // request deletion of all tags for this object on special server.
+                plugin.enqueueForUpload(del, new HashMap<String, String>(), false);
+            }
+        }
 
-    	// check modified primitives.
-       	for (OsmPrimitive upd : apiDataSet.getPrimitivesToUpdate()) {
-       		
-       		HashSet<String> allKeys = new HashSet<>();
-       		boolean specialTags = false;
-       		
-       		// process tags of new object
-       		for (String key : upd.keySet()) {
-       			allKeys.add(key);
-       			if (!specialTags && isSpecialKey(key)) specialTags = true;
-       		}
-       		
-       		// process tags of old object
-       		IPrimitive old = plugin.getOriginalPrimitive(upd);
-       		for (String key : old.keySet()) {
-       			allKeys.add(key);
-      			if (!specialTags && isSpecialKey(key)) specialTags = true;
-       		}
+        // check modified primitives.
+           for (OsmPrimitive upd : apiDataSet.getPrimitivesToUpdate()) {
+               
+               HashSet<String> allKeys = new HashSet<>();
+               boolean specialTags = false;
+               
+               // process tags of new object
+               for (String key : upd.keySet()) {
+                   allKeys.add(key);
+                   if (!specialTags && isSpecialKey(key)) specialTags = true;
+               }
+               
+               // process tags of old object
+               IPrimitive old = plugin.getOriginalPrimitive(upd);
+               for (String key : old.keySet()) {
+                   allKeys.add(key);
+                  if (!specialTags && isSpecialKey(key)) specialTags = true;
+               }
 
-       		// if neither has special tags, done with this object.
-       		if (!specialTags) continue;
-       		
-       		// special tags are involved. find out what, exactly, has changed.
-       		boolean changeInSpecialTags = false;
-       		boolean changeInOtherTags = false;
-       		for (String key : allKeys) {
-       			if (old.get(key) == null || upd.get(key) == null || !old.get(key).equals(upd.get(key))) {
-       				if (isSpecialKey(key)) changeInSpecialTags = true; else changeInOtherTags = true;
-       				if (changeInSpecialTags && changeInOtherTags) break;
-       			}
-       		}
-       		
-       		// change *only* in standard tags - done with this object.
-       		if (!changeInSpecialTags) continue;
-       		
-       		// assemble new set of special tags. might turn out to be empty.
-       		HashMap<String, String> newSpecialTags = new HashMap<>();
-       		for (String key : upd.keySet()) {
-       			if (isSpecialKey(key)) newSpecialTags.put(key, upd.get(key));
-       		}
-       		
-       		boolean uploadToOsm = changeInOtherTags;
-       		
-       		// not done yet: if no changes in standard tags, we need to find out if 
-       		// there were changes in the other properties (node: lat/lon, way/relation:
-       		// member list). If the answer is no, then the object must be removed from 
-       		// JOSM's normal upload queue, else we would be uploading a non-edit.
-       		if (!changeInOtherTags) {
-       			switch(old.getType()) {
-       			case NODE:
-       				INode nold = (INode) old;
-       				INode nupd = (INode) upd;
-       				uploadToOsm = !(nold.getCoor().equals(nupd.getCoor()));
-       				break;
-       			case WAY:
-       				IWay wold = (IWay) old;
-       				IWay wupd = (IWay) upd;
-       				if (wold.getNodesCount() != wupd.getNodesCount()) {
-       					uploadToOsm = true;
-       					break;
-       				} 
-       				for (int i = 0; i < wold.getNodesCount(); i++) {
-       					if (wold.getNodeId(i) != wupd.getNodeId(i)) {
-       						uploadToOsm = true;
-       						break;
-       					}
-       				}
-       				break;
-       			case RELATION:
-       				IRelation rold = (IRelation) old;
-       				IRelation rupd = (IRelation) upd;
-       				if (rold.getMembersCount()!= rupd.getMembersCount()) {
-       					uploadToOsm = true;
-       					break;
-       				} 
-       				for (int i = 0; i < rold.getMembersCount(); i++) {
-       					if (rold.getMemberType(i) != rupd.getMemberType(i) ||
-       						rold.getMemberId(i) != rupd.getMemberId(i)) {
-       						uploadToOsm = true;
-       						break;
-       					}
-       				}
-       				break;
-       			}
-       		}
-       		
-       		// request that new set of special tags be uploaded
-       		plugin.enqueueForUpload(upd, newSpecialTags, !uploadToOsm);
-       		
-       		// we cannot remove from getPrimitivesToUpdate, this would result in a 
-       		// ConcurrentModificationException.
-       		if (!uploadToOsm) droplist.add(upd);
-       		
-    	}
-       	
-    	apiDataSet.getPrimitivesToUpdate().removeAll(droplist);
-		       	
-       	// check added primitives. 
-       	for (OsmPrimitive add : apiDataSet.getPrimitivesToAdd()) {
-       		// assemble new set of special tags. might turn out to be empty.
-       		HashMap<String, String> newSpecialTags = new HashMap<>();
-       		for (String key : add.keySet()) {
-       			if (isSpecialKey(key)) newSpecialTags.put(key, add.get(key));
-       		}
-       		if (!newSpecialTags.isEmpty()) plugin.enqueueForUpload(add, newSpecialTags, false);
-    	}
-    	
-       	// FIXME it is possible that the list of OSM edits is totally empty.
-		return true;
+               // if neither has special tags, done with this object.
+               if (!specialTags) continue;
+               
+               // special tags are involved. find out what, exactly, has changed.
+               boolean changeInSpecialTags = false;
+               boolean changeInOtherTags = false;
+               for (String key : allKeys) {
+                   if (old.get(key) == null || upd.get(key) == null || !old.get(key).equals(upd.get(key))) {
+                       if (isSpecialKey(key)) changeInSpecialTags = true; else changeInOtherTags = true;
+                       if (changeInSpecialTags && changeInOtherTags) break;
+                   }
+               }
+               
+               // change *only* in standard tags - done with this object.
+               if (!changeInSpecialTags) continue;
+               
+               // assemble new set of special tags. might turn out to be empty.
+               HashMap<String, String> newSpecialTags = new HashMap<>();
+               for (String key : upd.keySet()) {
+                   if (isSpecialKey(key)) newSpecialTags.put(key, upd.get(key));
+               }
+               
+               boolean uploadToOsm = changeInOtherTags;
+               
+               // not done yet: if no changes in standard tags, we need to find out if 
+               // there were changes in the other properties (node: lat/lon, way/relation:
+               // member list). If the answer is no, then the object must be removed from 
+               // JOSM's normal upload queue, else we would be uploading a non-edit.
+               if (!changeInOtherTags) {
+                   switch(old.getType()) {
+                   case NODE:
+                       INode nold = (INode) old;
+                       INode nupd = (INode) upd;
+                       uploadToOsm = !(nold.getCoor().equals(nupd.getCoor()));
+                       break;
+                   case WAY:
+                       IWay wold = (IWay) old;
+                       IWay wupd = (IWay) upd;
+                       if (wold.getNodesCount() != wupd.getNodesCount()) {
+                           uploadToOsm = true;
+                           break;
+                       } 
+                       for (int i = 0; i < wold.getNodesCount(); i++) {
+                           if (wold.getNodeId(i) != wupd.getNodeId(i)) {
+                               uploadToOsm = true;
+                               break;
+                           }
+                       }
+                       break;
+                   case RELATION:
+                       IRelation rold = (IRelation) old;
+                       IRelation rupd = (IRelation) upd;
+                       if (rold.getMembersCount()!= rupd.getMembersCount()) {
+                           uploadToOsm = true;
+                           break;
+                       } 
+                       for (int i = 0; i < rold.getMembersCount(); i++) {
+                           if (rold.getMemberType(i) != rupd.getMemberType(i) ||
+                               rold.getMemberId(i) != rupd.getMemberId(i)) {
+                               uploadToOsm = true;
+                               break;
+                           }
+                       }
+                       break;
+                   }
+               }
+               
+               // request that new set of special tags be uploaded
+               plugin.enqueueForUpload(upd, newSpecialTags, !uploadToOsm);
+               
+               // we cannot remove from getPrimitivesToUpdate, this would result in a 
+               // ConcurrentModificationException.
+               if (!uploadToOsm) droplist.add(upd);
+               
+        }
+           
+        apiDataSet.getPrimitivesToUpdate().removeAll(droplist);
+                   
+           // check added primitives. 
+           for (OsmPrimitive add : apiDataSet.getPrimitivesToAdd()) {
+               // assemble new set of special tags. might turn out to be empty.
+               HashMap<String, String> newSpecialTags = new HashMap<>();
+               for (String key : add.keySet()) {
+                   if (isSpecialKey(key)) newSpecialTags.put(key, add.get(key));
+               }
+               if (!newSpecialTags.isEmpty()) plugin.enqueueForUpload(add, newSpecialTags, false);
+        }
+        
+           // FIXME it is possible that the list of OSM edits is totally empty.
+        return true;
 
     }
     
     boolean hasSpecialTags(IPrimitive p) {
-    	for (String key : p.keySet()) {
-    		if (isSpecialKey(key)) return true;
-    	}    
-    	return false;
+        for (String key : p.keySet()) {
+            if (isSpecialKey(key)) return true;
+        }    
+        return false;
     }
     
     boolean isSpecialKey(String key) {
-    	return key.startsWith(plugin.getIgnorePrefix());
+        return key.startsWith(plugin.getIgnorePrefix());
     }
 }
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/ReadPostprocessor.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/ReadPostprocessor.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/ReadPostprocessor.java	(revision 30738)
@@ -24,76 +24,76 @@
 
 public class ReadPostprocessor implements OsmServerReadPostprocessor {
-	
-	private ArrayList<Long> nodeList;
-	private ArrayList<Long> wayList;
-	private ArrayList<Long> relationList;
-	
-	private SeparateDataStorePlugin plugin;
+    
+    private ArrayList<Long> nodeList;
+    private ArrayList<Long> wayList;
+    private ArrayList<Long> relationList;
+    
+    private SeparateDataStorePlugin plugin;
 
-	public ReadPostprocessor(SeparateDataStorePlugin plugin) {
-		this.plugin = plugin;
-	}
-	
+    public ReadPostprocessor(SeparateDataStorePlugin plugin) {
+        this.plugin = plugin;
+    }
+    
     @Override
     public void postprocessDataSet(DataSet ds, ProgressMonitor progress) {
         
-		nodeList = new ArrayList<>();
-		wayList = new ArrayList<>();
-		relationList = new ArrayList<>();
+        nodeList = new ArrayList<>();
+        wayList = new ArrayList<>();
+        relationList = new ArrayList<>();
 
-		Visitor adder = new Visitor() {
-			@Override
-			public void visit(Node n) {
-				nodeList.add(n.getId());
-				plugin.originalNodes.put(n.getId(), n.save());
-			}
-			@Override
-			public void visit(Way w) {
-				wayList.add(w.getId());
-				plugin.originalWays.put(w.getId(), w.save());
-			}
-			@Override
-			public void visit(Relation e) {
-				relationList.add(e.getId());
-				plugin.originalNodes.put(e.getId(), e.save());
-			}
-			@Override
-			public void visit(Changeset cs) {}
-		};
-		
-		for (OsmPrimitive p : ds.allPrimitives()) {
-			p.accept(adder);
-		}
-			
-		SdsApi api = SdsApi.getSdsApi();
-		String rv = "";
-		try {
-			rv = api.requestShadowsFromSds(nodeList, wayList, relationList, progress);
-		} catch (SdsTransferException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		
-		// this is slightly inefficient, as we're re-making the string into 
-		// an input stream when there was an input stream to be had inside the
-		// SdsApi already, but this encapsulates things better.
+        Visitor adder = new Visitor() {
+            @Override
+            public void visit(Node n) {
+                nodeList.add(n.getId());
+                plugin.originalNodes.put(n.getId(), n.save());
+            }
+            @Override
+            public void visit(Way w) {
+                wayList.add(w.getId());
+                plugin.originalWays.put(w.getId(), w.save());
+            }
+            @Override
+            public void visit(Relation e) {
+                relationList.add(e.getId());
+                plugin.originalNodes.put(e.getId(), e.save());
+            }
+            @Override
+            public void visit(Changeset cs) {}
+        };
+        
+        for (OsmPrimitive p : ds.allPrimitives()) {
+            p.accept(adder);
+        }
+            
+        SdsApi api = SdsApi.getSdsApi();
+        String rv = "";
+        try {
+            rv = api.requestShadowsFromSds(nodeList, wayList, relationList, progress);
+        } catch (SdsTransferException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        
+        // this is slightly inefficient, as we're re-making the string into 
+        // an input stream when there was an input stream to be had inside the
+        // SdsApi already, but this encapsulates things better.
         InputStream xmlStream;
-		try {
-			xmlStream = new ByteArrayInputStream(rv.getBytes("UTF-8"));
-	        InputSource inputSource = new InputSource(xmlStream);
-			SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new SdsParser(ds, plugin));
-		} catch (UnsupportedEncodingException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		} catch (SAXException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (ParserConfigurationException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
+        try {
+            xmlStream = new ByteArrayInputStream(rv.getBytes("UTF-8"));
+            InputSource inputSource = new InputSource(xmlStream);
+            SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new SdsParser(ds, plugin));
+        } catch (UnsupportedEncodingException e1) {
+            // TODO Auto-generated catch block
+            e1.printStackTrace();
+        } catch (SAXException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (ParserConfigurationException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
 
     }
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsApi.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsApi.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsApi.java	(revision 30738)
@@ -34,5 +34,5 @@
  *
  * This is modeled after JOSM's own OsmAPI class.
- * 
+ *
  */
 public class SdsApi extends SdsConnection {
@@ -42,5 +42,5 @@
     /** the collection of instantiated OSM APIs */
     private static HashMap<String, SdsApi> instances = new HashMap<>();
-    
+
     /**
      * replies the {@see OsmApi} for a given server URL
@@ -123,5 +123,5 @@
      * @param osm the primitive
      * @throws SdsTransferException if something goes wrong
-     
+
     public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
         String ret = "";
@@ -144,5 +144,5 @@
      * @param monitor the progress monitor
      * @throws SdsTransferException if something goes wrong
-     
+
     public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
         String ret = null;
@@ -165,5 +165,5 @@
      * @param osm the primitive
      * @throws SdsTransferException if something goes wrong
-     
+
     public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
         ensureValidChangeset();
@@ -182,9 +182,9 @@
      * @param list the list of changed OSM Primitives
      * @param  monitor the progress monitor
-     * @return 
+     * @return
      * @return list of processed primitives
-     * @throws SdsTransferException 
+     * @throws SdsTransferException
      * @throws SdsTransferException if something is wrong
-     
+
     public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws SdsTransferException {
         try {
@@ -227,47 +227,47 @@
     }
     */
-    
+
     public String requestShadowsFromSds(List<Long> nodes, List<Long> ways, List<Long> relations, ProgressMonitor pm) throws SdsTransferException {
-    	
-    	StringBuilder request = new StringBuilder();
-    	String delim = "";
-    	String comma = "";
-    	
-    	if (nodes != null && !nodes.isEmpty()) {
-    		request.append(delim);
-    		delim = "&";
-    		comma = "";
-    		request.append("nodes=");
-    		for (long i : nodes) {
-    			request.append(comma);
-    			comma = ",";
-    			request.append(i);
-    		}
-    	}
-    	if (ways != null && !ways.isEmpty()) {
-    		request.append(delim);
-    		delim = "&";
-    		comma = "";
-    		request.append("ways=");
-    		for (long i : ways) {
-    			request.append(comma);
-    			comma = ",";
-    			request.append(i);
-    		}
-    	}
-    	if (relations != null && !relations.isEmpty()) {
-    		request.append(delim);
-    		delim = "&";
-    		comma = "";
-    		request.append("relations=");
-    		for (long i : relations) {
-    			request.append(comma);
-    			comma = ",";
-    			request.append(i);
-    		}
-    	}
-    	
-    	return sendRequest("POST", "collectshadows", request.toString(), pm ,true);
-   
+
+        StringBuilder request = new StringBuilder();
+        String delim = "";
+        String comma = "";
+
+        if (nodes != null && !nodes.isEmpty()) {
+            request.append(delim);
+            delim = "&";
+            comma = "";
+            request.append("nodes=");
+            for (long i : nodes) {
+                request.append(comma);
+                comma = ",";
+                request.append(i);
+            }
+        }
+        if (ways != null && !ways.isEmpty()) {
+            request.append(delim);
+            delim = "&";
+            comma = "";
+            request.append("ways=");
+            for (long i : ways) {
+                request.append(comma);
+                comma = ",";
+                request.append(i);
+            }
+        }
+        if (relations != null && !relations.isEmpty()) {
+            request.append(delim);
+            delim = "&";
+            comma = "";
+            request.append("relations=");
+            for (long i : relations) {
+                request.append(comma);
+                comma = ",";
+                request.append(i);
+            }
+        }
+
+        return sendRequest("POST", "collectshadows", request.toString(), pm ,true);
+
     }
 
@@ -304,13 +304,13 @@
         return sendRequest(requestMethod, urlSuffix, requestBody, monitor, doAuth, false);
     }
-    
+
     public boolean updateSds(String message, ProgressMonitor pm) {
-    	try {
-			sendRequest("POST", "createshadows", message, pm);
-		} catch (SdsTransferException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-    	return true;
+        try {
+            sendRequest("POST", "createshadows", message, pm);
+        } catch (SdsTransferException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        return true;
     }
 
@@ -352,18 +352,18 @@
                     activeConnection.setDoOutput(true);
                     activeConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
-                    OutputStream out = activeConnection.getOutputStream();
-
-                    // It seems that certain bits of the Ruby API are very unhappy upon
-                    // receipt of a PUT/POST message without a Content-length header,
-                    // even if the request has no payload.
-                    // Since Java will not generate a Content-length header unless
-                    // we use the output stream, we create an output stream for PUT/POST
-                    // even if there is no payload.
-                    if (requestBody != null) {
-                        BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
-                        bwr.write(requestBody);
-                        bwr.flush();
+                    try (OutputStream out = activeConnection.getOutputStream()) {
+
+                        // It seems that certain bits of the Ruby API are very unhappy upon
+                        // receipt of a PUT/POST message without a Content-length header,
+                        // even if the request has no payload.
+                        // Since Java will not generate a Content-length header unless
+                        // we use the output stream, we create an output stream for PUT/POST
+                        // even if there is no payload.
+                        if (requestBody != null) {
+                            BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
+                            bwr.write(requestBody);
+                            bwr.flush();
+                        }
                     }
-                    out.close();
                 }
 
@@ -442,8 +442,8 @@
         }
     }
-    
+
     protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws SdsTransferException {
         urlStr = getBaseUrl() + urlStr;
-    	try {
+        try {
             URL url = null;
             try {
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsConnection.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsConnection.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsConnection.java	(revision 30738)
@@ -21,5 +21,5 @@
  */
 public class SdsConnection {
-	
+    
     protected boolean cancel = false;
     protected HttpURLConnection activeConnection;
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialAgent.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialAgent.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialAgent.java	(revision 30738)
@@ -120,11 +120,11 @@
     }
 
-	@Override
-	public void storeOAuthAccessToken(OAuthToken accessToken)
-			throws CredentialsAgentException {
-		// no-op
-		
-	}
-	
+    @Override
+    public void storeOAuthAccessToken(OAuthToken accessToken)
+            throws CredentialsAgentException {
+        // no-op
+        
+    }
+    
     @Override
     public CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) throws CredentialsAgentException{
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialDialog.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialDialog.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialDialog.java	(revision 30738)
@@ -11,5 +11,5 @@
 public class SdsCredentialDialog extends CredentialDialog {
 
-	static public SdsCredentialDialog getSdsApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) {
+    static public SdsCredentialDialog getSdsApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) {
         SdsCredentialDialog dialog = new SdsCredentialDialog(saveUsernameAndPasswordCheckboxText);
         dialog.prepareForSdsApiCredentials(username, password);
@@ -21,7 +21,7 @@
 
     public SdsCredentialDialog(String saveUsernameAndPasswordCheckboxText) {
-    	super(saveUsernameAndPasswordCheckboxText);
+        super(saveUsernameAndPasswordCheckboxText);
     }
-    	 
+         
     public void prepareForSdsApiCredentials(String username, String password) {
         setTitle(tr("Enter credentials for Separate Data Store API"));
@@ -33,5 +33,5 @@
     private static class SdsApiCredentialsPanel extends CredentialPanel {
 
-		@Override
+        @Override
         protected void build() {
             super.build();
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsDiskAccessAction.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsDiskAccessAction.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsDiskAccessAction.java	(revision 30738)
@@ -16,11 +16,11 @@
 @SuppressWarnings("serial")
 public abstract class SdsDiskAccessAction extends DiskAccessAction {
-	
+    
     public SdsDiskAccessAction(String name, String iconName, String tooltip,
-			Shortcut shortcut) {
-		super(name, iconName, tooltip, shortcut);
-	}
+            Shortcut shortcut) {
+        super(name, iconName, tooltip, shortcut);
+    }
 
-	public static SwingFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title) {
+    public static SwingFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title) {
         String curDir = Main.pref.get("lastDirectory");
         if (curDir.equals("")) {
@@ -35,8 +35,8 @@
         fc.setMultiSelectionEnabled(multiple);
         fc.setAcceptAllFileFilterUsed(false);
-        		
+                
         fc.setFileFilter(new FileFilter() {
-        	public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
-			public String getDescription() { return (tr("SDS data file")); }
+            public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
+            public String getDescription() { return (tr("SDS data file")); }
         });     
 
@@ -83,6 +83,6 @@
         
         fc.setFileFilter(new FileFilter() {
-        	public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
-			public String getDescription() { return (tr("SDS data file")); }
+            public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
+            public String getDescription() { return (tr("SDS data file")); }
         }); 
         
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsLoadAction.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsLoadAction.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsLoadAction.java	(revision 30738)
@@ -26,10 +26,10 @@
 @SuppressWarnings("serial")
 public class SdsLoadAction extends SdsDiskAccessAction {
-	
-	private SeparateDataStorePlugin plugin;
+    
+    private SeparateDataStorePlugin plugin;
 
     public SdsLoadAction(SeparateDataStorePlugin p) {
         super(tr("Load..."), "sds_load", tr("Load separate data store data from a file."), null);
-    	plugin = p;
+        plugin = p;
     }
     
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsMenu.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsMenu.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsMenu.java	(revision 30738)
@@ -56,83 +56,83 @@
 
     void setEnabledState() {
-    	boolean en = (Main.map != null) && (Main.map.mapView != null) && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer);
-    	loadItem.setEnabled(en);
-    	saveItem.setEnabled(en);
+        boolean en = (Main.map != null) && (Main.map.mapView != null) && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer);
+        loadItem.setEnabled(en);
+        saveItem.setEnabled(en);
     }
   
-	@Override
-	public void activeLayerChange(Layer oldLayer, Layer newLayer) {	setEnabledState(); }
+    @Override
+    public void activeLayerChange(Layer oldLayer, Layer newLayer) {    setEnabledState(); }
 
-	@Override
-	public void layerAdded(Layer newLayer) { setEnabledState(); }
+    @Override
+    public void layerAdded(Layer newLayer) { setEnabledState(); }
 
-	@Override
-	public void layerRemoved(Layer oldLayer) { setEnabledState(); }
+    @Override
+    public void layerRemoved(Layer oldLayer) { setEnabledState(); }
 
-	private class SdsAboutAction extends JosmAction {
+    private class SdsAboutAction extends JosmAction {
 
-	    public SdsAboutAction() {
-	        super(tr("About"), "sds", tr("Information about SDS."), null, true);
-	    }
+        public SdsAboutAction() {
+            super(tr("About"), "sds", tr("Information about SDS."), null, true);
+        }
 
-	    public void actionPerformed(ActionEvent e) {
-	        JPanel about = new JPanel();
+        public void actionPerformed(ActionEvent e) {
+            JPanel about = new JPanel();
 
-	        JTextArea l = new JTextArea();
-	        l.setLineWrap(true);
-	        l.setWrapStyleWord(true);
-	        l.setEditable(false);
-	        l.setText("Separate Data Store\n\nThis plugin provides access to a \"Separate Data Store\" server. " +
-	        		"Whenever data is loaded from the OSM API, it queries the SDS for additional tags that have been stored for the objects just loaded, " +
-	        		"and adds these tags. When you upload data to JOSM, SDS tags will again be separated and, instead of sending them to OSM, they will be uplaoded to SDS." +
-	        		"\n\n" +
-	        		"This depends on SDS tags starting with a special prefix, which can be configured in the SDS preferences." + 
-	        		"\n\n" + 
-	        		"Using the SDS server will usually require an account to be set up there, which is completely independent of your OSM account.");
-	        
-	        l.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
-	        l.setOpaque(false);
-	        l.setPreferredSize(new Dimension(500,300));
-	        JScrollPane sp = new JScrollPane(l);
-	        sp.setBorder(null);
-	        sp.setOpaque(false);
-	        	        
-	        about.add(sp);
-	        
-	        about.setPreferredSize(new Dimension(500,300));
+            JTextArea l = new JTextArea();
+            l.setLineWrap(true);
+            l.setWrapStyleWord(true);
+            l.setEditable(false);
+            l.setText("Separate Data Store\n\nThis plugin provides access to a \"Separate Data Store\" server. " +
+                    "Whenever data is loaded from the OSM API, it queries the SDS for additional tags that have been stored for the objects just loaded, " +
+                    "and adds these tags. When you upload data to JOSM, SDS tags will again be separated and, instead of sending them to OSM, they will be uplaoded to SDS." +
+                    "\n\n" +
+                    "This depends on SDS tags starting with a special prefix, which can be configured in the SDS preferences." + 
+                    "\n\n" + 
+                    "Using the SDS server will usually require an account to be set up there, which is completely independent of your OSM account.");
+            
+            l.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
+            l.setOpaque(false);
+            l.setPreferredSize(new Dimension(500,300));
+            JScrollPane sp = new JScrollPane(l);
+            sp.setBorder(null);
+            sp.setOpaque(false);
+                        
+            about.add(sp);
+            
+            about.setPreferredSize(new Dimension(500,300));
 
-	        JOptionPane.showMessageDialog(Main.parent, about, tr("About SDS..."),
-	                JOptionPane.INFORMATION_MESSAGE, null);
-	    }
-	}
-	
-	private class SdsPreferencesAction extends JosmAction implements Runnable {
+            JOptionPane.showMessageDialog(Main.parent, about, tr("About SDS..."),
+                    JOptionPane.INFORMATION_MESSAGE, null);
+        }
+    }
+    
+    private class SdsPreferencesAction extends JosmAction implements Runnable {
 
-	    private SdsPreferencesAction() {
-	        super(tr("Preferences..."), "preference", tr("Open a preferences dialog for SDS."),
-	                null, true);
-	        putValue("help", ht("/Action/Preferences"));
-	    }
+        private SdsPreferencesAction() {
+            super(tr("Preferences..."), "preference", tr("Open a preferences dialog for SDS."),
+                    null, true);
+            putValue("help", ht("/Action/Preferences"));
+        }
 
-	    /**
-	     * Launch the preferences dialog.
-	     */
-	    public void actionPerformed(ActionEvent e) {
-	        run();
-	    }
+        /**
+         * Launch the preferences dialog.
+         */
+        public void actionPerformed(ActionEvent e) {
+            run();
+        }
 
-	    public void run() {
-	    	PreferenceDialog pd = new PreferenceDialog(Main.parent);
-	    	// unusual reflection mechanism to cater for older JOSM versions where 
-	    	// the selectPreferencesTabByName method was not public
-	    	try {
-	    		Method sptbn = pd.getClass().getMethod("selectPreferencesTabByName", String.class);
-	    		sptbn.invoke(pd, "sds");
-	    	} catch (Exception ex) {
-	    		// ignore
-	    	}
-	    	pd.setVisible(true);
-	    }
-	}
+        public void run() {
+            PreferenceDialog pd = new PreferenceDialog(Main.parent);
+            // unusual reflection mechanism to cater for older JOSM versions where 
+            // the selectPreferencesTabByName method was not public
+            try {
+                Method sptbn = pd.getClass().getMethod("selectPreferencesTabByName", String.class);
+                sptbn.invoke(pd, "sds");
+            } catch (Exception ex) {
+                // ignore
+            }
+            pd.setVisible(true);
+        }
+    }
 
 
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriter.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriter.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriter.java	(revision 30738)
@@ -27,6 +27,6 @@
 public class SdsOsmWriter extends OsmWriter {
 
-	private SeparateDataStorePlugin plugin;
-	
+    private SeparateDataStorePlugin plugin;
+    
     public SdsOsmWriter(SeparateDataStorePlugin plugin, PrintWriter out, boolean osmConform, String version) {
         super(out, osmConform, version);
@@ -43,5 +43,5 @@
             Collections.sort(entries, byKeyComparator);
             for (Entry<String, String> e : entries) {
-            	String key = e.getKey();
+                String key = e.getKey();
                 if (!(osm instanceof Changeset) && ("created_by".equals(key))) continue;
                 if (key.startsWith(plugin.getIgnorePrefix())) continue;          
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriterFactory.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriterFactory.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriterFactory.java	(revision 30738)
@@ -15,11 +15,11 @@
 public class SdsOsmWriterFactory extends OsmWriterFactory {
 
-	SeparateDataStorePlugin plugin;
-	
-	public SdsOsmWriterFactory(SeparateDataStorePlugin plugin) {
-		this.plugin = plugin;
-	}
-	
-	@Override
+    SeparateDataStorePlugin plugin;
+    
+    public SdsOsmWriterFactory(SeparateDataStorePlugin plugin) {
+        this.plugin = plugin;
+    }
+    
+    @Override
     protected OsmWriter createOsmWriterImpl(PrintWriter out, boolean osmConform, String version) {
         return new SdsOsmWriter(plugin, out, osmConform, version);
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsParser.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsParser.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsParser.java	(revision 30738)
@@ -54,5 +54,5 @@
         {
             String type = atts.getValue("osm_type");
-            String id = atts.getValue("osm_id");     	
+            String id = atts.getValue("osm_id");         
             currentPrimitive = dataSet.getPrimitiveById(Long.parseLong(id), OsmPrimitiveType.fromApiTypeName(type));
             if (currentPrimitive == null && ensureMatch) {
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsPluginPreferences.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsPluginPreferences.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsPluginPreferences.java	(revision 30738)
@@ -35,10 +35,10 @@
    
     public SdsPluginPreferences() {
-    	super("sds", tr("Separate Data Store"), tr("Configures access to the Separate Data Store."));
+        super("sds", tr("Separate Data Store"), tr("Configures access to the Separate Data Store."));
     }
     @Override
     public void addGui(final PreferenceTabbedPane gui) {
         final JPanel tab = gui.createPreferenceTab(this);
-        	
+            
         final JPanel access = new JPanel(new GridBagLayout());
         access.setBorder(BorderFactory.createTitledBorder(tr("Server")));
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsSaveAction.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsSaveAction.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsSaveAction.java	(revision 30738)
@@ -6,6 +6,4 @@
 import java.awt.event.ActionEvent;
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -21,6 +19,6 @@
 import org.openstreetmap.josm.gui.layer.Layer;
 import org.openstreetmap.josm.gui.layer.OsmDataLayer;
+import org.openstreetmap.josm.tools.Utils;
 
-@SuppressWarnings("serial")
 public class SdsSaveAction extends SdsDiskAccessAction {
 
@@ -30,4 +28,5 @@
     }
 
+    @Override
     public void actionPerformed(ActionEvent e) {
         if (!isEnabled())
@@ -40,5 +39,5 @@
         if (Main.isDisplayingMapView() && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer))
             layer = Main.map.mapView.getActiveLayer();
-        
+
         if (layer == null)
             return false;
@@ -64,5 +63,5 @@
             if (file.exists()) {
                 tmpFile = new File(file.getPath() + "~");
-                copy(file, tmpFile);
+                Utils.copyFile(file, tmpFile);
             }
 
@@ -70,7 +69,6 @@
             Writer writer = new OutputStreamWriter(out, "UTF-8");
 
-            SdsWriter w = new SdsWriter(new PrintWriter(writer));
             layer.data.getReadLock().lock();
-            try {
+            try (SdsWriter w = new SdsWriter(new PrintWriter(writer))) {
                 w.header();
                 for (IPrimitive p : layer.data.allNonDeletedPrimitives()) {
@@ -78,5 +76,4 @@
                 }
                 w.footer();
-                w.close();
             } finally {
                 layer.data.getReadLock().unlock();
@@ -87,5 +84,5 @@
             }
         } catch (IOException e) {
-            e.printStackTrace();
+            Main.error(e);
             JOptionPane.showMessageDialog(
                     Main.parent,
@@ -99,8 +96,8 @@
                 // be deleted.  So, restore the backup if we made one.
                 if (tmpFile != null && tmpFile.exists()) {
-                    copy(tmpFile, file);
+                    Utils.copyFile(tmpFile, file);
                 }
             } catch (IOException e2) {
-                e2.printStackTrace();
+                Main.error(e2);
                 JOptionPane.showMessageDialog(
                         Main.parent,
@@ -113,23 +110,3 @@
         return true;
     }
-
-    private void copy(File src, File dst) throws IOException {
-        FileInputStream srcStream;
-        FileOutputStream dstStream;
-        try {
-            srcStream = new FileInputStream(src);
-            dstStream = new FileOutputStream(dst);
-        } catch (FileNotFoundException e) {
-            JOptionPane.showMessageDialog(Main.parent, tr("Could not back up file. Exception is: {0}", e
-                    .getMessage()), tr("Error"), JOptionPane.ERROR_MESSAGE);
-            return;
-        }
-        byte buf[] = new byte[1 << 16];
-        int len;
-        while ((len = srcStream.read(buf)) != -1) {
-            dstStream.write(buf, 0, len);
-        }
-        srcStream.close();
-        dstStream.close();
-    }
 }
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsWriter.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsWriter.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsWriter.java	(revision 30738)
@@ -29,18 +29,18 @@
 
     public void write(IPrimitive what, Map<String,String> tags) {
-    	out.print("<osm_shadow osm_type=\"");
-    	out.print(what.getType().getAPIName());
-    	out.print("\" osm_id=\"");
-    	out.print(what.getId());
-    	out.println("\">");
+        out.print("<osm_shadow osm_type=\"");
+        out.print(what.getType().getAPIName());
+        out.print("\" osm_id=\"");
+        out.print(what.getId());
+        out.println("\">");
         
-    	if (tags != null) {
-    		for(Entry<String,String> e : tags.entrySet()) {
-    			out.println("    <tag k='"+ XmlWriter.encode(e.getKey()) +
-    					"' v='"+XmlWriter.encode(e.getValue())+ "' />");
-    		}
-    	}
-    	
-    	out.println("</osm_shadow>");
+        if (tags != null) {
+            for(Entry<String,String> e : tags.entrySet()) {
+                out.println("    <tag k='"+ XmlWriter.encode(e.getKey()) +
+                        "' v='"+XmlWriter.encode(e.getValue())+ "' />");
+            }
+        }
+        
+        out.println("</osm_shadow>");
     }
 
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SeparateDataStorePlugin.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SeparateDataStorePlugin.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SeparateDataStorePlugin.java	(revision 30738)
@@ -29,29 +29,29 @@
 {
 
-	public HashMap<Long, IPrimitive> originalNodes = new HashMap<>();
-	public HashMap<Long, IPrimitive> originalWays = new HashMap<>();
-	public HashMap<Long, IPrimitive> originalRelations = new HashMap<>();
-	
-	public ArrayList<QueueItem> uploadQueue = new ArrayList<>();
-	
-	private PrimitiveVisitor learnVisitor = new PrimitiveVisitor() {
-		public void visit(INode i) { originalNodes.put(i.getId(), i); }
-		public void visit(IWay i) { originalWays.put(i.getId(), i); }
-		public void visit(IRelation i) { originalRelations.put(i.getId(), i); }
-	};
-	
-	class QueueItem {
-		public IPrimitive primitive;
-		public HashMap<String,String> tags;
-		public boolean sdsOnly;
-		public boolean processed;
-		public QueueItem(IPrimitive p, HashMap<String,String> t, boolean s) {
-			primitive = p;
-			tags = t;
-			sdsOnly = s;
-			processed = false;
-		}
-	}
-	
+    public HashMap<Long, IPrimitive> originalNodes = new HashMap<>();
+    public HashMap<Long, IPrimitive> originalWays = new HashMap<>();
+    public HashMap<Long, IPrimitive> originalRelations = new HashMap<>();
+    
+    public ArrayList<QueueItem> uploadQueue = new ArrayList<>();
+    
+    private PrimitiveVisitor learnVisitor = new PrimitiveVisitor() {
+        public void visit(INode i) { originalNodes.put(i.getId(), i); }
+        public void visit(IWay i) { originalWays.put(i.getId(), i); }
+        public void visit(IRelation i) { originalRelations.put(i.getId(), i); }
+    };
+    
+    class QueueItem {
+        public IPrimitive primitive;
+        public HashMap<String,String> tags;
+        public boolean sdsOnly;
+        public boolean processed;
+        public QueueItem(IPrimitive p, HashMap<String,String> t, boolean s) {
+            primitive = p;
+            tags = t;
+            sdsOnly = s;
+            processed = false;
+        }
+    }
+    
     /**
      * Creates the plugin
@@ -60,7 +60,7 @@
     {
         super(info);
-    	System.out.println("initializing SDS plugin");
-    	
-    	// this lets us see what JOSM load from the server, and augment it with our data:
+        System.out.println("initializing SDS plugin");
+        
+        // this lets us see what JOSM load from the server, and augment it with our data:
         OsmReader.registerPostprocessor(new ReadPostprocessor(this));
         
@@ -79,53 +79,53 @@
     }
 
-	public String getIgnorePrefix() {
+    public String getIgnorePrefix() {
         return Main.pref.get("sds-server.tag-prefix", "hot:");
-	}
-	
-	public IPrimitive getOriginalPrimitive(IPrimitive other) {
-		switch (other.getType()) {
-		case NODE: return originalNodes.get(other.getId());
-		case WAY: return originalWays.get(other.getId());
-		case RELATION: return originalRelations.get(other.getId());
-		}
-		return null;	
-	}
-	
-	protected void enqueueForUpload(IPrimitive prim, HashMap<String, String> tags, boolean onlySds) {
-		uploadQueue.add(new QueueItem(prim, tags, onlySds));
-	}
-	
-	/** 
-	 * Stores the given primitive in the plugin's cache in order to
-	 * determine changes later.
-	 * @param prim
-	 */
-	protected void learn(IPrimitive prim) {
-		if (prim instanceof OsmPrimitive) {
-			((OsmPrimitive)prim).save().accept(learnVisitor);
-		} else {
-			prim.accept(learnVisitor);
-		}
-	}
-	
-	/**
-	 * removes all elements from the upload queue that have the processed flag set.
-	 */
-	protected void clearQueue() {
-		ArrayList<QueueItem> newQueue = new ArrayList<>();
-		for (QueueItem q : uploadQueue) {
-			if (!q.processed) newQueue.add(q);
-		}
-		uploadQueue = newQueue;
-	}
-	
-	/**
-	 * reset the processed flag for all elements of the queue.
-	 */
-	protected void resetQueue() {
-		for (QueueItem q : uploadQueue) {
-			q.processed = false;
-		}
-	}
+    }
+    
+    public IPrimitive getOriginalPrimitive(IPrimitive other) {
+        switch (other.getType()) {
+        case NODE: return originalNodes.get(other.getId());
+        case WAY: return originalWays.get(other.getId());
+        case RELATION: return originalRelations.get(other.getId());
+        }
+        return null;    
+    }
+    
+    protected void enqueueForUpload(IPrimitive prim, HashMap<String, String> tags, boolean onlySds) {
+        uploadQueue.add(new QueueItem(prim, tags, onlySds));
+    }
+    
+    /** 
+     * Stores the given primitive in the plugin's cache in order to
+     * determine changes later.
+     * @param prim
+     */
+    protected void learn(IPrimitive prim) {
+        if (prim instanceof OsmPrimitive) {
+            ((OsmPrimitive)prim).save().accept(learnVisitor);
+        } else {
+            prim.accept(learnVisitor);
+        }
+    }
+    
+    /**
+     * removes all elements from the upload queue that have the processed flag set.
+     */
+    protected void clearQueue() {
+        ArrayList<QueueItem> newQueue = new ArrayList<>();
+        for (QueueItem q : uploadQueue) {
+            if (!q.processed) newQueue.add(q);
+        }
+        uploadQueue = newQueue;
+    }
+    
+    /**
+     * reset the processed flag for all elements of the queue.
+     */
+    protected void resetQueue() {
+        for (QueueItem q : uploadQueue) {
+            q.processed = false;
+        }
+    }
 
     public PreferenceSetting getPreferenceSetting() {
Index: applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/WritePostprocessor.java
===================================================================
--- applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/WritePostprocessor.java	(revision 30737)
+++ applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/WritePostprocessor.java	(revision 30738)
@@ -13,62 +13,60 @@
 public class WritePostprocessor implements OsmServerWritePostprocessor {
 
-	SeparateDataStorePlugin plugin;
+    SeparateDataStorePlugin plugin;
 
-	public WritePostprocessor(SeparateDataStorePlugin plugin) {
-		this.plugin = plugin;
-	}	
+    public WritePostprocessor(SeparateDataStorePlugin plugin) {
+        this.plugin = plugin;
+    }
 
-	@Override
-	public void postprocessUploadedPrimitives(Collection<IPrimitive> primitives,
-			ProgressMonitor progress) {
-		
-	    StringWriter swriter = new StringWriter();
-	    SdsWriter sdsWriter = new SdsWriter(new PrintWriter(swriter));
-	    sdsWriter.header();
-	    boolean somethingWritten = false;
-	   
-	    for (IPrimitive p : primitives) {
-			for (QueueItem q : plugin.uploadQueue) {
-				if (q.primitive.equals(p) && !q.sdsOnly) {
-					sdsWriter.write(q.primitive, q.tags);
-					somethingWritten = true;
-					q.processed = true;
-					continue;
-				}
-			}
-	    }
-	    
-		for (QueueItem q : plugin.uploadQueue) {
-			if (q.sdsOnly) {
-				sdsWriter.write(q.primitive, q.tags);
-				somethingWritten = true;
-				q.processed = true;
-			}
-		}
+    @Override
+    public void postprocessUploadedPrimitives(Collection<IPrimitive> primitives, ProgressMonitor progress) {
 
-		if (somethingWritten) {
-			sdsWriter.footer();
+        StringWriter swriter = new StringWriter();
+        try (SdsWriter sdsWriter = new SdsWriter(new PrintWriter(swriter))) {
+            sdsWriter.header();
+            boolean somethingWritten = false;
 
-			SdsApi api = SdsApi.getSdsApi();
-			System.out.println("sending message:\n" + swriter.toString());
-			api.updateSds(swriter.toString(), progress);
-		}
-		
-		sdsWriter.close();
-		
-		for (IPrimitive p : primitives) {
-			plugin.learn(p);
-		}
+            for (IPrimitive p : primitives) {
+                for (QueueItem q : plugin.uploadQueue) {
+                    if (q.primitive.equals(p) && !q.sdsOnly) {
+                        sdsWriter.write(q.primitive, q.tags);
+                        somethingWritten = true;
+                        q.processed = true;
+                        continue;
+                    }
+                }
+            }
 
-		for (QueueItem q : plugin.uploadQueue) {
-			if (q.sdsOnly) {
-				q.primitive.setModified(false);
-				plugin.learn(q.primitive);
-			}
-		}
-		
-		plugin.clearQueue();
-		// TODO: if exception -> resetQueue
-	}
+            for (QueueItem q : plugin.uploadQueue) {
+                if (q.sdsOnly) {
+                    sdsWriter.write(q.primitive, q.tags);
+                    somethingWritten = true;
+                    q.processed = true;
+                }
+            }
+
+            if (somethingWritten) {
+                sdsWriter.footer();
+
+                SdsApi api = SdsApi.getSdsApi();
+                System.out.println("sending message:\n" + swriter.toString());
+                api.updateSds(swriter.toString(), progress);
+            }
+        }
+
+        for (IPrimitive p : primitives) {
+            plugin.learn(p);
+        }
+
+        for (QueueItem q : plugin.uploadQueue) {
+            if (q.sdsOnly) {
+                q.primitive.setModified(false);
+                plugin.learn(q.primitive);
+            }
+        }
+
+        plugin.clearQueue();
+        // TODO: if exception -> resetQueue
+    }
 
 }
Index: applications/editors/josm/plugins/smed/src/panels/PanelChan.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelChan.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelChan.java	(revision 30738)
@@ -28,16 +28,16 @@
 			panelStbd.setVisible(false);
 			panelSaw.setVisible(false);
-			dlg.panelMain.moreButton.setVisible(false);
-			dlg.panelMain.saveButton.setEnabled(false);
+			SmedAction.panelMain.moreButton.setVisible(false);
+			SmedAction.panelMain.saveButton.setEnabled(false);
 			topmarkButton.setVisible(false);
 			lightButton.setVisible(false);
-			Shp shp = dlg.panelMain.mark.getShape();
+			Shp shp = SmedAction.panelMain.mark.getShape();
 			if (portButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.LAM_PORT);
+				SmedAction.panelMain.mark.setCategory(Cat.LAM_PORT);
 				if (panelPort.shapes.containsKey(shp)) {
 					panelPort.shapes.get(shp).setSelected(true);
 				} else {
 					panelPort.shapeButtons.clearSelection();
-					dlg.panelMain.mark.setShape(Shp.UNKSHP);
+					SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 				}
 				panelPort.alShape.actionPerformed(null);
@@ -48,10 +48,10 @@
 			}
 			if (stbdButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.LAM_STBD);
+				SmedAction.panelMain.mark.setCategory(Cat.LAM_STBD);
 				if (panelStbd.shapes.containsKey(shp)) {
 					panelStbd.shapes.get(shp).setSelected(true);
 				} else {
 					panelStbd.shapeButtons.clearSelection();
-					dlg.panelMain.mark.setShape(Shp.UNKSHP);
+					SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 				}
 				panelStbd.alShape.actionPerformed(null);
@@ -62,10 +62,10 @@
 			}
 			if (prefStbdButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.LAM_PSTBD);
+				SmedAction.panelMain.mark.setCategory(Cat.LAM_PSTBD);
 				if (panelPort.shapes.containsKey(shp)) {
 					panelPort.shapes.get(shp).setSelected(true);
 				} else {
 					panelPort.shapeButtons.clearSelection();
-					dlg.panelMain.mark.setShape(Shp.UNKSHP);
+					SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 				}
 				panelPort.alShape.actionPerformed(null);
@@ -76,10 +76,10 @@
 			}
 			if (prefPortButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.LAM_PPORT);
+				SmedAction.panelMain.mark.setCategory(Cat.LAM_PPORT);
 				if (panelStbd.shapes.containsKey(shp)) {
 					panelStbd.shapes.get(shp).setSelected(true);
 				} else {
 					panelStbd.shapeButtons.clearSelection();
-					dlg.panelMain.mark.setShape(Shp.UNKSHP);
+					SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 				}
 				panelStbd.alShape.actionPerformed(null);
@@ -90,5 +90,5 @@
 			}
 			if (safeWaterButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.NOCAT);
+				SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
 				panelSaw.setVisible(true);
 				if (panelSaw.shapes.containsKey(shp)) {
@@ -96,5 +96,5 @@
 				} else {
 					panelSaw.shapeButtons.clearSelection();
-					dlg.panelMain.mark.setShape(Shp.UNKSHP);
+					SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 				}
 				panelSaw.alShape.actionPerformed(null);
@@ -104,7 +104,7 @@
 				safeWaterButton.setBorderPainted(false);
 			}
-			topmarkButton.setVisible(dlg.panelMain.mark.testValid());
-			lightButton.setVisible(dlg.panelMain.mark.testValid());
-			dlg.panelMain.panelMore.syncPanel();
+			topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
+			lightButton.setVisible(SmedAction.panelMain.mark.testValid());
+			SmedAction.panelMain.panelMore.syncPanel();
 		}
 	};
@@ -113,8 +113,8 @@
 		public void actionPerformed(java.awt.event.ActionEvent e) {
 			if (topmarkButton.isSelected()) {
-				if (SeaMark.GrpMAP.get(dlg.panelMain.mark.getObject()) == Grp.SAW) {
-					dlg.panelMain.mark.setTopmark(Top.SPHERE);
-					dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
-					dlg.panelMain.mark.setTopColour(Col.RED);
+				if (SeaMark.GrpMAP.get(SmedAction.panelMain.mark.getObject()) == Grp.SAW) {
+					SmedAction.panelMain.mark.setTopmark(Top.SPHERE);
+					SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
+					SmedAction.panelMain.mark.setTopColour(Col.RED);
 				} else {
 					switch (dlg.panelMain.mark.getCategory()) {
Index: applications/editors/josm/plugins/smed/src/panels/PanelChr.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelChr.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelChr.java	(revision 30738)
@@ -67,10 +67,10 @@
 			}
 			String str = charBox.getText();
-			dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);
+			SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str);
 			if (!str.contains("Al")) {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
-				dlg.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
+				SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
 			} else {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
 			}
 		}
@@ -80,5 +80,5 @@
 			public void focusLost(java.awt.event.FocusEvent e) {
 			String str = charBox.getText();
-			dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);
+			SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str);
 			EnumSet<Chr> set = EnumSet.noneOf(Chr.class);
 			for (EnumSet<Chr> map : SeaMark.ChrMAP.keySet()) {
@@ -99,8 +99,8 @@
 			}
 			if (!str.contains("Al")) {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
-				dlg.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
+				SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
 			} else {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
 			}
 		}
@@ -141,5 +141,5 @@
 
 	public void syncPanel() {
-		String str = (String)dlg.panelMain.mark.getLightAtt(Att.CHR, 0);
+		String str = (String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0);
 		charBox.setText(str);
 		EnumSet<Chr> set = EnumSet.noneOf(Chr.class);
@@ -151,9 +151,9 @@
 		}
 		if (!str.contains("Al")) {
-			col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
+			col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
 		} else {
-			col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
+			col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
 		}
-		col1Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
+		col1Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
 		for (Chr chr : buttons.keySet()) {
 			JToggleButton button = buttons.get(chr);
Index: applications/editors/josm/plugins/smed/src/panels/PanelCol.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelCol.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelCol.java	(revision 30738)
@@ -41,29 +41,29 @@
 				if (button.isSelected()) {
 					if (ent == Ent.LIGHT) {
-						if (((String) dlg.panelMain.mark.getLightAtt(Att.CHR, 0)).contains("Al")) {
-							if (((button == delButton) && (dlg.panelMain.mark.getLightAtt(Att.ALT, 0) == Col.UNKCOL))
-									|| (dlg.panelMain.mark.getLightAtt(Att.COL, 0) == Col.UNKCOL)) {
-								dlg.panelMain.mark.setLightAtt(Att.COL, 0, col);
-								dlg.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
+						if (((String) SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0)).contains("Al")) {
+							if (((button == delButton) && (SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0) == Col.UNKCOL))
+									|| (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) == Col.UNKCOL)) {
+								SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, col);
+								SmedAction.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
 							} else {
-								dlg.panelMain.mark.setLightAtt(Att.ALT, 0, col);
-								dlg.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
+								SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, col);
+								SmedAction.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
 							}
 						} else {
-							dlg.panelMain.mark.setLightAtt(Att.COL, 0, col);
-							dlg.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
-							dlg.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
+							SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, col);
+							SmedAction.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
+							SmedAction.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
 						}
 						button.setBorderPainted(true);
 					} else {
 						if (button == delButton) {
-							dlg.panelMain.mark.subColour(ent, stackIdx);
+							SmedAction.panelMain.mark.subColour(ent, stackIdx);
 						} else if (button == addButton) {
 							if (stackCol.size() != 0)
 								stackIdx++;
 							if (stackCol.size() == 0)
-								dlg.panelMain.mark.setColour(ent, col);
+								SmedAction.panelMain.mark.setColour(ent, col);
 							else
-								switch (dlg.panelMain.mark.getPattern(ent)) {
+								switch (SmedAction.panelMain.mark.getPattern(ent)) {
 								case NOPAT:
 									break;
@@ -71,16 +71,16 @@
 								case CROSS:
 									if (stackCol.size() < 2)
-										dlg.panelMain.mark.addColour(ent, stackIdx, col);
+										SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
 									break;
 								case SQUARED:
 									if (stackCol.size() < 4)
-										dlg.panelMain.mark.addColour(ent, stackIdx, col);
+										SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
 									break;
 								default:
-									dlg.panelMain.mark.addColour(ent, stackIdx, col);
+									SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
 									break;
 								}
 						} else {
-							dlg.panelMain.mark.setColour(ent, stackIdx, col);
+							SmedAction.panelMain.mark.setColour(ent, stackIdx, col);
 						}
 						syncPanel();
@@ -150,5 +150,5 @@
 			for (Col col : colours.keySet()) {
 				JRadioButton button = colours.get(col);
-				if (dlg.panelMain.mark.getLightAtt(Att.COL, 0) == col) {
+				if (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) == col) {
 					button.setBorderPainted(true);
 				} else
@@ -157,5 +157,5 @@
 		} else {
 			int idx;
-			for (idx = 0; dlg.panelMain.mark.getColour(ent, idx) != Col.UNKCOL; idx++) {
+			for (idx = 0; SmedAction.panelMain.mark.getColour(ent, idx) != Col.UNKCOL; idx++) {
 				if (stackCol.size() <= idx) {
 					stackCol.add(idx, new JRadioButton(new ImageIcon(getClass().getResource("/images/ColourButton.png"))));
@@ -185,5 +185,5 @@
 					JRadioButton btnI = stackCol.get(idx);
 					btnI.setBounds(2, (2 + (idx * height)), 30, height);
-					btnI.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getColour(ent, idx)));
+					btnI.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getColour(ent, idx)));
 					if (stackIdx == idx) {
 						btnI.setBorderPainted(true);
Index: applications/editors/josm/plugins/smed/src/panels/PanelFog.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelFog.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelFog.java	(revision 30738)
@@ -30,5 +30,5 @@
 				JRadioButton button = fogs.get(fog);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setFogSound(fog);
+					SmedAction.panelMain.mark.setFogSound(fog);
 					button.setBorderPainted(true);
 				} else
@@ -41,5 +41,5 @@
 	private FocusListener flGroup = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setFogGroup(groupBox.getText());
+			SmedAction.panelMain.mark.setFogGroup(groupBox.getText());
 		}
 	};
@@ -48,5 +48,5 @@
 	private FocusListener flPeriod = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setFogPeriod(periodBox.getText());
+			SmedAction.panelMain.mark.setFogPeriod(periodBox.getText());
 		}
 	};
@@ -55,5 +55,5 @@
 	private FocusListener flSeq = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setFogSequence(seqBox.getText());
+			SmedAction.panelMain.mark.setFogSequence(seqBox.getText());
 		}
 	};
@@ -62,5 +62,5 @@
 	private FocusListener flRange = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setFogRange(rangeBox.getText());
+			SmedAction.panelMain.mark.setFogRange(rangeBox.getText());
 		}
 	};
@@ -120,10 +120,10 @@
 		for (Fog fog : fogs.keySet()) {
 			JRadioButton button = fogs.get(fog);
-			button.setBorderPainted(dlg.panelMain.mark.getFogSound() == fog);
+			button.setBorderPainted(SmedAction.panelMain.mark.getFogSound() == fog);
 		}
-		groupBox.setText(dlg.panelMain.mark.getFogGroup());
-		seqBox.setText(dlg.panelMain.mark.getFogSequence());
-		periodBox.setText(dlg.panelMain.mark.getFogPeriod());
-		rangeBox.setText(dlg.panelMain.mark.getFogRange());
+		groupBox.setText(SmedAction.panelMain.mark.getFogGroup());
+		seqBox.setText(SmedAction.panelMain.mark.getFogSequence());
+		periodBox.setText(SmedAction.panelMain.mark.getFogPeriod());
+		rangeBox.setText(SmedAction.panelMain.mark.getFogRange());
 	}
 
Index: applications/editors/josm/plugins/smed/src/panels/PanelHaz.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelHaz.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelHaz.java	(revision 30738)
@@ -24,9 +24,9 @@
 	private ActionListener alCat = new ActionListener() {
 		public void actionPerformed(java.awt.event.ActionEvent e) {
-			dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
+			SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
 			if (northButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.CAM_NORTH);
-				dlg.panelMain.mark.setObjColour(Col.BLACK);
-				dlg.panelMain.mark.addObjColour(Col.YELLOW);
+				SmedAction.panelMain.mark.setCategory(Cat.CAM_NORTH);
+				SmedAction.panelMain.mark.setObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
 				northButton.setBorderPainted(true);
 			} else {
@@ -34,7 +34,7 @@
 			}
 			if (southButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.CAM_SOUTH);
-				dlg.panelMain.mark.setObjColour(Col.YELLOW);
-				dlg.panelMain.mark.addObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.setCategory(Cat.CAM_SOUTH);
+				SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
+				SmedAction.panelMain.mark.addObjColour(Col.BLACK);
 				southButton.setBorderPainted(true);
 			} else {
@@ -42,8 +42,8 @@
 			}
 			if (eastButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.CAM_EAST);
-				dlg.panelMain.mark.setObjColour(Col.BLACK);
-				dlg.panelMain.mark.addObjColour(Col.YELLOW);
-				dlg.panelMain.mark.addObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.setCategory(Cat.CAM_EAST);
+				SmedAction.panelMain.mark.setObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
+				SmedAction.panelMain.mark.addObjColour(Col.BLACK);
 				eastButton.setBorderPainted(true);
 			} else {
@@ -51,8 +51,8 @@
 			}
 			if (westButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.CAM_WEST);
-				dlg.panelMain.mark.setObjColour(Col.YELLOW);
-				dlg.panelMain.mark.addObjColour(Col.BLACK);
-				dlg.panelMain.mark.addObjColour(Col.YELLOW);
+				SmedAction.panelMain.mark.setCategory(Cat.CAM_WEST);
+				SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
+				SmedAction.panelMain.mark.addObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
 				westButton.setBorderPainted(true);
 			} else {
@@ -60,15 +60,15 @@
 			}
 			if (isolButton.isSelected()) {
-				dlg.panelMain.mark.setCategory(Cat.NOCAT);
-				dlg.panelMain.mark.setObjColour(Col.BLACK);
-				dlg.panelMain.mark.addObjColour(Col.RED);
-				dlg.panelMain.mark.addObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
+				SmedAction.panelMain.mark.setObjColour(Col.BLACK);
+				SmedAction.panelMain.mark.addObjColour(Col.RED);
+				SmedAction.panelMain.mark.addObjColour(Col.BLACK);
 				isolButton.setBorderPainted(true);
 			} else {
 				isolButton.setBorderPainted(false);
 			}
-			topmarkButton.setVisible(dlg.panelMain.mark.testValid());
-			lightButton.setVisible(dlg.panelMain.mark.testValid());
-			dlg.panelMain.panelMore.syncPanel();
+			topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
+			lightButton.setVisible(SmedAction.panelMain.mark.testValid());
+			SmedAction.panelMain.panelMore.syncPanel();
 		}
 	};
@@ -90,15 +90,15 @@
 				JRadioButton button = shapes.get(shp);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setShape(shp);
+					SmedAction.panelMain.mark.setShape(shp);
 					if (isolButton.isSelected())
-						dlg.panelMain.mark.setObject(isdObjects.get(shp));
+						SmedAction.panelMain.mark.setObject(isdObjects.get(shp));
 					else
-						dlg.panelMain.mark.setObject(carObjects.get(shp));
+						SmedAction.panelMain.mark.setObject(carObjects.get(shp));
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			topmarkButton.setVisible(dlg.panelMain.mark.testValid());
-			lightButton.setVisible(dlg.panelMain.mark.testValid());
+			topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
+			lightButton.setVisible(SmedAction.panelMain.mark.testValid());
 		}
 	};
@@ -107,31 +107,31 @@
 		public void actionPerformed(java.awt.event.ActionEvent e) {
 			if (topmarkButton.isSelected()) {
-				dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
-				dlg.panelMain.mark.setTopColour(Col.BLACK);
-				switch (dlg.panelMain.mark.getCategory()) {
+				SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
+				SmedAction.panelMain.mark.setTopColour(Col.BLACK);
+				switch (SmedAction.panelMain.mark.getCategory()) {
 				case CAM_NORTH:
-					dlg.panelMain.mark.setTopmark(Top.NORTH);
+					SmedAction.panelMain.mark.setTopmark(Top.NORTH);
 					break;
 				case CAM_SOUTH:
-					dlg.panelMain.mark.setTopmark(Top.SOUTH);
+					SmedAction.panelMain.mark.setTopmark(Top.SOUTH);
 					break;
 				case CAM_EAST:
-					dlg.panelMain.mark.setTopmark(Top.EAST);
+					SmedAction.panelMain.mark.setTopmark(Top.EAST);
 					break;
 				case CAM_WEST:
-					dlg.panelMain.mark.setTopmark(Top.WEST);
+					SmedAction.panelMain.mark.setTopmark(Top.WEST);
 					break;
 				default:
-					dlg.panelMain.mark.setTopmark(Top.SPHERES2);
+					SmedAction.panelMain.mark.setTopmark(Top.SPHERES2);
 					break;
 				}
 				topmarkButton.setBorderPainted(true);
 			} else {
-				dlg.panelMain.mark.setTopmark(Top.NOTOP);
-				dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
-				dlg.panelMain.mark.setTopColour(Col.UNKCOL);
+				SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
+				SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
+				SmedAction.panelMain.mark.setTopColour(Col.UNKCOL);
 				topmarkButton.setBorderPainted(false);
 			}
-			dlg.panelMain.panelTop.syncPanel();
+			SmedAction.panelMain.panelTop.syncPanel();
 		}
 	};
@@ -140,33 +140,33 @@
 		public void actionPerformed(java.awt.event.ActionEvent e) {
 			if (lightButton.isSelected()) {
-				dlg.panelMain.mark.setLightAtt(Att.COL, 0, Col.WHITE);
-				switch (dlg.panelMain.mark.getCategory()) {
+				SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, Col.WHITE);
+				switch (SmedAction.panelMain.mark.getCategory()) {
 				case CAM_NORTH:
-					dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
-					dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "");
+					SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
+					SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "");
 					break;
 				case CAM_SOUTH:
-					dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q+LFl");
-					dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "6");
+					SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q+LFl");
+					SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "6");
 					break;
 				case CAM_EAST:
-					dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
-					dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "3");
+					SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
+					SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "3");
 					break;
 				case CAM_WEST:
-					dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
-					dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "9");
+					SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
+					SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "9");
 					break;
 				default:
-					dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Fl");
-					dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "2");
+					SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Fl");
+					SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "2");
 					break;
 				}
 				lightButton.setBorderPainted(true);
 			} else {
-				dlg.panelMain.mark.clrLight();
+				SmedAction.panelMain.mark.clrLight();
 				lightButton.setBorderPainted(false);
 			}
-			dlg.panelMain.panelLit.syncPanel();
+			SmedAction.panelMain.panelLit.syncPanel();
 		}
 	};
@@ -205,20 +205,20 @@
 
 	public void syncPanel() {
-		northButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_NORTH);
-		southButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_SOUTH);
-		eastButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_EAST);
-		westButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_WEST);
-		isolButton.setBorderPainted(SeaMark.GrpMAP.get(dlg.panelMain.mark.getObject()) == Grp.ISD);
+		northButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_NORTH);
+		southButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_SOUTH);
+		eastButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_EAST);
+		westButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_WEST);
+		isolButton.setBorderPainted(SeaMark.GrpMAP.get(SmedAction.panelMain.mark.getObject()) == Grp.ISD);
 		for (Shp shp : shapes.keySet()) {
 			JRadioButton button = shapes.get(shp);
-			button.setBorderPainted(dlg.panelMain.mark.getShape() == shp);
-		}
-		topmarkButton.setBorderPainted(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
-		topmarkButton.setSelected(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
-		topmarkButton.setVisible(dlg.panelMain.mark.testValid());
-		Boolean lit = (dlg.panelMain.mark.getLightAtt(Att.COL, 0) != Col.UNKCOL) && !((String)dlg.panelMain.mark.getLightAtt(Att.CHR, 0)).isEmpty();
+			button.setBorderPainted(SmedAction.panelMain.mark.getShape() == shp);
+		}
+		topmarkButton.setBorderPainted(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
+		topmarkButton.setSelected(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
+		topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
+		Boolean lit = (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) != Col.UNKCOL) && !((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0)).isEmpty();
 		lightButton.setBorderPainted(lit);
 		lightButton.setSelected(lit);
-		lightButton.setVisible(dlg.panelMain.mark.testValid());
+		lightButton.setVisible(SmedAction.panelMain.mark.testValid());
 	}
 
Index: applications/editors/josm/plugins/smed/src/panels/PanelLights.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelLights.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelLights.java	(revision 30738)
@@ -25,6 +25,6 @@
 				int idx = landCats.get(cat);
 				if (dlg.node != null && (idx == landCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -38,6 +38,6 @@
 				int idx = trafficCats.get(cat);
 				if (dlg.node != null && (idx == trafficCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -51,6 +51,6 @@
 				int idx = warningCats.get(cat);
 				if (dlg.node != null && (idx == warningCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -64,6 +64,6 @@
 				int idx = platformCats.get(cat);
 				if (dlg.node != null && (idx == platformCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -77,6 +77,6 @@
 				int idx = pilotCats.get(cat);
 				if (dlg.node != null && (idx == pilotCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -90,6 +90,6 @@
 				int idx = rescueCats.get(cat);
 				if (dlg.node != null && (idx == rescueCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -103,6 +103,6 @@
 				int idx = radioCats.get(cat);
 				if (dlg.node != null && (idx == radioCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -116,6 +116,6 @@
 				int idx = radarCats.get(cat);
 				if (dlg.node != null && (idx == radarCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -130,6 +130,6 @@
 				int idx = functions.get(fnc);
 				if (dlg.node != null && (idx == functionBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setFunc(fnc);
-					dlg.panelMain.mark.testValid();
+					SmedAction.panelMain.mark.setFunc(fnc);
+					SmedAction.panelMain.mark.testValid();
 				}
 			}
@@ -157,14 +157,14 @@
 				JRadioButton button = objects.get(obj);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setObject(obj);
+					SmedAction.panelMain.mark.setObject(obj);
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			if (dlg.panelMain.mark.getObject() == Obj.LITVES)
-				dlg.panelMain.mark.setShape(Shp.SUPER);
-			else if (dlg.panelMain.mark.getObject() == Obj.LITFLT)
-				dlg.panelMain.mark.setShape(Shp.FLOAT);
-			else dlg.panelMain.mark.setShape(Shp.UNKSHP);
+			if (SmedAction.panelMain.mark.getObject() == Obj.LITVES)
+				SmedAction.panelMain.mark.setShape(Shp.SUPER);
+			else if (SmedAction.panelMain.mark.getObject() == Obj.LITFLT)
+				SmedAction.panelMain.mark.setShape(Shp.FLOAT);
+			else SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 			functionLabel.setVisible(false);
 			categoryLabel.setVisible(false);
@@ -181,5 +181,5 @@
 			chLabel.setVisible(false);
 			chBox.setVisible(false);
-			dlg.panelMain.mark.setCategory(Cat.NOCAT);
+			SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
 			if (landButton.isSelected()) {
 				functionLabel.setVisible(true);
@@ -227,5 +227,5 @@
 				alRadarCatBox.actionPerformed(null);
 			}
-			dlg.panelMain.mark.testValid();
+			SmedAction.panelMain.mark.testValid();
 		}
 	};
@@ -234,5 +234,5 @@
 	private FocusListener flCh = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setChannel(chBox.getText());
+			SmedAction.panelMain.mark.setChannel(chBox.getText());
 		}
 	};
@@ -462,6 +462,6 @@
 		chLabel.setVisible(false);
 		chBox.setVisible(false);
-		chBox.setText(dlg.panelMain.mark.getChannel());
-		if ((dlg.panelMain.mark.getObject() == Obj.LNDMRK) && ((dlg.panelMain.mark.getCategory() != Cat.NOCAT) || (dlg.panelMain.mark.getFunc() != Fnc.UNKFNC))) {
+		chBox.setText(SmedAction.panelMain.mark.getChannel());
+		if ((SmedAction.panelMain.mark.getObject() == Obj.LNDMRK) && ((SmedAction.panelMain.mark.getCategory() != Cat.NOCAT) || (SmedAction.panelMain.mark.getFunc() != Fnc.UNKFNC))) {
 			functionLabel.setVisible(true);
 			categoryLabel.setVisible(true);
@@ -470,74 +470,74 @@
 			for (Fnc fnc : functions.keySet()) {
 				int item = functions.get(fnc);
-				if (dlg.panelMain.mark.getFunc() == fnc)
+				if (SmedAction.panelMain.mark.getFunc() == fnc)
 					functionBox.setSelectedIndex(item);
 			}
 			for (Cat cat : landCats.keySet()) {
 				int item = landCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					landCatBox.setSelectedIndex(item);
 			}
-		} else if (dlg.panelMain.mark.getObject() == Obj.SISTAT) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAT) {
 				categoryLabel.setVisible(true);
 				trafficCatBox.setVisible(true);
 				for (Cat cat : trafficCats.keySet()) {
 					int item = trafficCats.get(cat);
-					if (dlg.panelMain.mark.getCategory() == cat)
+					if (SmedAction.panelMain.mark.getCategory() == cat)
 						trafficCatBox.setSelectedIndex(item);
 				}
 				chLabel.setVisible(true);
 				chBox.setVisible(true);
-		} else if (dlg.panelMain.mark.getObject() == Obj.SISTAW) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAW) {
 			categoryLabel.setVisible(true);
 			warningCatBox.setVisible(true);
 			for (Cat cat : warningCats.keySet()) {
 				int item = warningCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					warningCatBox.setSelectedIndex(item);
 			}
 			chLabel.setVisible(true);
 			chBox.setVisible(true);
-		} else if (dlg.panelMain.mark.getObject() == Obj.OFSPLF) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.OFSPLF) {
 			categoryLabel.setVisible(true);
 			platformCatBox.setVisible(true);
 			for (Cat cat : platformCats.keySet()) {
 				int item = platformCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					platformCatBox.setSelectedIndex(item);
 			}
-		} else if (dlg.panelMain.mark.getObject() == Obj.PILBOP) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.PILBOP) {
 			categoryLabel.setVisible(true);
 			pilotCatBox.setVisible(true);
 			for (Cat cat : pilotCats.keySet()) {
 				int item = pilotCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					pilotCatBox.setSelectedIndex(item);
 			}
 			chLabel.setVisible(true);
 			chBox.setVisible(true);
-		} else if (dlg.panelMain.mark.getObject() == Obj.RSCSTA) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.RSCSTA) {
 			categoryLabel.setVisible(true);
 			rescueCatBox.setVisible(true);
 			for (Cat cat : rescueCats.keySet()) {
 				int item = rescueCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					rescueCatBox.setSelectedIndex(item);
 			}
-		} else if (dlg.panelMain.mark.getObject() == Obj.RDOSTA) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.RDOSTA) {
 			categoryLabel.setVisible(true);
 			radioCatBox.setVisible(true);
 			for (Cat cat : radioCats.keySet()) {
 				int item = radioCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					radioCatBox.setSelectedIndex(item);
 			}
 			chLabel.setVisible(true);
 			chBox.setVisible(true);
-		} else if (dlg.panelMain.mark.getObject() == Obj.RADSTA) {
+		} else if (SmedAction.panelMain.mark.getObject() == Obj.RADSTA) {
 			categoryLabel.setVisible(true);
 			radarCatBox.setVisible(true);
 			for (Cat cat : radarCats.keySet()) {
 				int item = radarCats.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					radarCatBox.setSelectedIndex(item);
 			}
@@ -547,7 +547,7 @@
 		for (Obj obj : objects.keySet()) {
 			JRadioButton button = objects.get(obj);
-			button.setBorderPainted(dlg.panelMain.mark.getObject() == obj);
-		}
-		dlg.panelMain.mark.testValid();
+			button.setBorderPainted(SmedAction.panelMain.mark.getObject() == obj);
+		}
+		SmedAction.panelMain.mark.testValid();
 	}
 	
Index: applications/editors/josm/plugins/smed/src/panels/PanelLit.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelLit.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelLit.java	(revision 30738)
@@ -21,5 +21,5 @@
 	private FocusListener flGroup = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.GRP, 0, groupBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, groupBox.getText());
 		}
 	};
@@ -28,5 +28,5 @@
 	private FocusListener flPeriod = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.PER, 0, periodBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.PER, 0, periodBox.getText());
 		}
 	};
@@ -35,5 +35,5 @@
 	private FocusListener flSequence = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.SEQ, 0, sequenceBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.SEQ, 0, sequenceBox.getText());
 		}
 	};
@@ -46,5 +46,5 @@
 				int idx = visibilities.get(vis);
 				if (idx == visibilityBox.getSelectedIndex())
-					dlg.panelMain.mark.setLightAtt(Att.VIS, 0, vis);
+					SmedAction.panelMain.mark.setLightAtt(Att.VIS, 0, vis);
 			}
 		}
@@ -54,5 +54,5 @@
 	private FocusListener flHeight = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.HGT, 0, heightBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.HGT, 0, heightBox.getText());
 		}
 	};
@@ -61,5 +61,5 @@
 	private FocusListener flRange = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.RNG, 0, rangeBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.RNG, 0, rangeBox.getText());
 		}
 	};
@@ -68,5 +68,5 @@
 	private FocusListener flOrientation = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.ORT, 0, orientationBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, orientationBox.getText());
 		}
 	};
@@ -75,5 +75,5 @@
 	private FocusListener flMultiple = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setLightAtt(Att.MLT, 0, multipleBox.getText());
+			SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, multipleBox.getText());
 		}
 	};
@@ -86,8 +86,8 @@
 				int idx = categories.get(lit);
 				if (idx == categoryBox.getSelectedIndex())
-					dlg.panelMain.mark.setLightAtt(Att.LIT, 0, lit);
-			}
-			if (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR) {
-				dlg.panelMain.mark.setLightAtt(Att.MLT, 0, "");
+					SmedAction.panelMain.mark.setLightAtt(Att.LIT, 0, lit);
+			}
+			if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR) {
+				SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, "");
 				multipleBox.setText("");
 				orientationLabel.setVisible(true);
@@ -95,6 +95,6 @@
 				multipleLabel.setVisible(false);
 				multipleBox.setVisible(false);
-			} else if ((dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ)) {
-				dlg.panelMain.mark.setLightAtt(Att.ORT, 0, "");
+			} else if ((SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ)) {
+				SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, "");
 				orientationBox.setText("");
 				orientationLabel.setVisible(false);
@@ -103,7 +103,7 @@
 				multipleBox.setVisible(true);
 			} else {
-				dlg.panelMain.mark.setLightAtt(Att.MLT, 0, "");
+				SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, "");
 				multipleBox.setText("");
-				dlg.panelMain.mark.setLightAtt(Att.ORT, 0, "");
+				SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, "");
 				orientationBox.setText("");
 				orientationLabel.setVisible(false);
@@ -122,5 +122,5 @@
 				int idx = exhibitions.get(exh);
 				if (idx == exhibitionBox.getSelectedIndex())
-					dlg.panelMain.mark.setLightAtt(Att.EXH, 0, exh);
+					SmedAction.panelMain.mark.setLightAtt(Att.EXH, 0, exh);
 			}
 		}
@@ -137,6 +137,6 @@
 			} else {
 				panelSector.setVisible(false);
-				while (dlg.panelMain.mark.getSectorCount() > 1)
-					dlg.panelMain.mark.delLight(1);
+				while (SmedAction.panelMain.mark.getSectorCount() > 1)
+					SmedAction.panelMain.mark.delLight(1);
 			}
 		}
@@ -285,29 +285,29 @@
 		multipleLabel.setVisible(false);
 		multipleBox.setVisible(false);
-		groupBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.GRP, 0));
-		periodBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.PER, 0));
-		sequenceBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.SEQ, 0));
-		heightBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.HGT, 0));
-		rangeBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.RNG, 0));
-		orientationBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.ORT, 0));
-		orientationBox.setVisible(dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR);
-		multipleBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.MLT, 0));
-		multipleBox.setVisible((dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ));
+		groupBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.GRP, 0));
+		periodBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.PER, 0));
+		sequenceBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.SEQ, 0));
+		heightBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.HGT, 0));
+		rangeBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.RNG, 0));
+		orientationBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.ORT, 0));
+		orientationBox.setVisible(SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR);
+		multipleBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.MLT, 0));
+		multipleBox.setVisible((SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ));
 		for (Vis vis : visibilities.keySet()) {
 			int item = visibilities.get(vis);
-			if (dlg.panelMain.mark.getLightAtt(Att.VIS, 0) == vis)
+			if (SmedAction.panelMain.mark.getLightAtt(Att.VIS, 0) == vis)
 				visibilityBox.setSelectedIndex(item);
 		}
 		for (Lit lit : categories.keySet()) {
 			int item = categories.get(lit);
-			if (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == lit)
+			if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == lit)
 				categoryBox.setSelectedIndex(item);
 		}
 		for (Exh exh : exhibitions.keySet()) {
 			int item = exhibitions.get(exh);
-			if (dlg.panelMain.mark.getLightAtt(Att.EXH, 0) == exh)
+			if (SmedAction.panelMain.mark.getLightAtt(Att.EXH, 0) == exh)
 				exhibitionBox.setSelectedIndex(item);
 		}
-		if (dlg.panelMain.mark.isSectored()) {
+		if (SmedAction.panelMain.mark.isSectored()) {
 			singleButton.setBorderPainted(false);
 			sectorButton.setBorderPainted(true);
@@ -317,6 +317,6 @@
 			sectorButton.setBorderPainted(false);
 			panelSector.setVisible(false);
-			while (dlg.panelMain.mark.getSectorCount() > 1)
-				dlg.panelMain.mark.delLight(dlg.panelMain.mark.getSectorCount() - 1);
+			while (SmedAction.panelMain.mark.getSectorCount() > 1)
+				SmedAction.panelMain.mark.delLight(SmedAction.panelMain.mark.getSectorCount() - 1);
 		}
 		panelCol.syncPanel();
Index: applications/editors/josm/plugins/smed/src/panels/PanelMore.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelMore.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelMore.java	(revision 30738)
@@ -19,5 +19,5 @@
 	private FocusListener flInfo = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setInfo(infoBox.getText());
+			SmedAction.panelMain.mark.setInfo(infoBox.getText());
 		}
 	};
@@ -26,5 +26,5 @@
 	private FocusListener flSource = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setSource(sourceBox.getText());
+			SmedAction.panelMain.mark.setSource(sourceBox.getText());
 		}
 	};
@@ -33,5 +33,5 @@
 	private FocusListener flElev = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setElevation(elevBox.getText());
+			SmedAction.panelMain.mark.setElevation(elevBox.getText());
 		}
 	};
@@ -40,5 +40,5 @@
 	private FocusListener flHeight = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setObjectHeight(heightBox.getText());
+			SmedAction.panelMain.mark.setObjectHeight(heightBox.getText());
 		}
 	};
@@ -50,6 +50,6 @@
 			for (Sts sts : statuses.keySet()) {
 				int idx = statuses.get(sts);
-				if (dlg.panelMain.mark != null && (idx == statusBox.getSelectedIndex()))
-					dlg.panelMain.mark.setStatus(sts);
+				if (SmedAction.panelMain.mark != null && (idx == statusBox.getSelectedIndex()))
+					SmedAction.panelMain.mark.setStatus(sts);
 			}
 		}
@@ -62,6 +62,6 @@
 			for (Cns cns : constructions.keySet()) {
 				int idx = constructions.get(cns);
-				if (dlg.panelMain.mark != null && (idx == constrBox.getSelectedIndex()))
-					dlg.panelMain.mark.setConstr(cns);
+				if (SmedAction.panelMain.mark != null && (idx == constrBox.getSelectedIndex()))
+					SmedAction.panelMain.mark.setConstr(cns);
 			}
 		}
@@ -74,6 +74,6 @@
 			for (Con con : conspicuities.keySet()) {
 				int idx = conspicuities.get(con);
-				if (dlg.panelMain.mark != null && (idx == conBox.getSelectedIndex()))
-					dlg.panelMain.mark.setConsp(con);
+				if (SmedAction.panelMain.mark != null && (idx == conBox.getSelectedIndex()))
+					SmedAction.panelMain.mark.setConsp(con);
 			}
 		}
@@ -86,6 +86,6 @@
 			for (Con con : reflectivities.keySet()) {
 				int idx = reflectivities.get(con);
-				if (dlg.panelMain.mark != null && (idx == reflBox.getSelectedIndex()))
-					dlg.panelMain.mark.setRefl(con);
+				if (SmedAction.panelMain.mark != null && (idx == reflBox.getSelectedIndex()))
+					SmedAction.panelMain.mark.setRefl(con);
 			}
 		}
@@ -99,5 +99,5 @@
 		public void actionPerformed(java.awt.event.ActionEvent e) {
 			if (regionAButton.isSelected()) {
-				dlg.panelMain.mark.setRegion(Reg.A);
+				SmedAction.panelMain.mark.setRegion(Reg.A);
 				switch (dlg.panelMain.mark.getCategory()) {
 				case LAM_PORT:
Index: applications/editors/josm/plugins/smed/src/panels/PanelPat.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelPat.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelPat.java	(revision 30738)
@@ -31,10 +31,10 @@
 				JRadioButton button = patterns.get(pat);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setPattern(ent, pat);
+					SmedAction.panelMain.mark.setPattern(ent, pat);
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			switch (dlg.panelMain.mark.getPattern(ent)) {
+			switch (SmedAction.panelMain.mark.getPattern(ent)) {
 			case NOPAT:
 				panelCol.trimStack(1);
@@ -74,5 +74,5 @@
 		for (Pat pat : patterns.keySet()) {
 			JRadioButton button = patterns.get(pat);
-			if (dlg.panelMain.mark.getPattern(ent) == pat) {
+			if (SmedAction.panelMain.mark.getPattern(ent) == pat) {
 				button.setBorderPainted(true);
 			} else
Index: applications/editors/josm/plugins/smed/src/panels/PanelPort.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelPort.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelPort.java	(revision 30738)
@@ -31,56 +31,56 @@
 				JRadioButton button = shapes.get(shp);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setShape(shp);
-					dlg.panelMain.mark.setObject(objects.get(shp));
+					SmedAction.panelMain.mark.setShape(shp);
+					SmedAction.panelMain.mark.setObject(objects.get(shp));
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			if (dlg.panelMain.mark.testValid()) {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(true);
-				dlg.panelMain.panelChan.lightButton.setVisible(true);
-				if (dlg.panelMain.mark.getCategory() == Cat.LAM_PORT) {
-					switch (dlg.panelMain.mark.getRegion()) {
+			if (SmedAction.panelMain.mark.testValid()) {
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
+				SmedAction.panelMain.panelChan.lightButton.setVisible(true);
+				if (SmedAction.panelMain.mark.getCategory() == Cat.LAM_PORT) {
+					switch (SmedAction.panelMain.mark.getRegion()) {
 					case A:
-						dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-						dlg.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
 						break;
 					case B:
-						dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-						dlg.panelMain.mark.setObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+						SmedAction.panelMain.mark.setObjColour(Col.GREEN);
 						break;
 					case C:
-						dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
-						dlg.panelMain.mark.setObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.WHITE);
-						dlg.panelMain.mark.addObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.WHITE);
+						SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.WHITE);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.WHITE);
 						break;
 					}
 				} else {
-					dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
-					switch (dlg.panelMain.mark.getRegion()) {
+					SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
+					switch (SmedAction.panelMain.mark.getRegion()) {
 					case A:
-						dlg.panelMain.mark.setObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
 						break;
 					case B:
-						dlg.panelMain.mark.setObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
 						break;
 					case C:
-						dlg.panelMain.mark.setObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
 						break;
 					}
 				}
-				dlg.panelMain.panelMore.syncPanel();
+				SmedAction.panelMain.panelMore.syncPanel();
 			} else {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(false);
-				dlg.panelMain.panelChan.lightButton.setVisible(false);
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
+				SmedAction.panelMain.panelChan.lightButton.setVisible(false);
 			}
 		}
@@ -104,5 +104,5 @@
 		for (Shp shp : shapes.keySet()) {
 			JRadioButton button = shapes.get(shp);
-			if (dlg.panelMain.mark.getShape() == shp) {
+			if (SmedAction.panelMain.mark.getShape() == shp) {
 				button.setBorderPainted(true);
 			} else
Index: applications/editors/josm/plugins/smed/src/panels/PanelRadar.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelRadar.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelRadar.java	(revision 30738)
@@ -35,5 +35,5 @@
 				int idx = radioCats.get(cat);
 				if (dlg.node != null && (idx == radioCatBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setRadio(cat);
+					SmedAction.panelMain.mark.setRadio(cat);
 				}
 			}
@@ -52,5 +52,5 @@
 				JRadioButton button = rads.get(rtb);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setRadar(rtb);
+					SmedAction.panelMain.mark.setRadar(rtb);
 				}
 			}
@@ -62,5 +62,5 @@
 	private FocusListener flGroup = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconGroup(groupBox.getText());
+			SmedAction.panelMain.mark.setRaconGroup(groupBox.getText());
 		}
 	};
@@ -69,5 +69,5 @@
 	private FocusListener flPeriod = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconPeriod(periodBox.getText());
+			SmedAction.panelMain.mark.setRaconPeriod(periodBox.getText());
 		}
 	};
@@ -76,5 +76,5 @@
 	private FocusListener flSeq = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconSequence(seqBox.getText());
+			SmedAction.panelMain.mark.setRaconSequence(seqBox.getText());
 		}
 	};
@@ -83,5 +83,5 @@
 	private FocusListener flRange = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconRange(rangeBox.getText());
+			SmedAction.panelMain.mark.setRaconRange(rangeBox.getText());
 		}
 	};
@@ -90,5 +90,5 @@
 	private FocusListener flSector1 = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconSector1(sector1Box.getText());
+			SmedAction.panelMain.mark.setRaconSector1(sector1Box.getText());
 		}
 	};
@@ -97,5 +97,5 @@
 	private FocusListener flSector2 = new FocusAdapter() {
 		public void focusLost(java.awt.event.FocusEvent e) {
-			dlg.panelMain.mark.setRaconSector2(sector2Box.getText());
+			SmedAction.panelMain.mark.setRaconSector2(sector2Box.getText());
 		}
 	};
@@ -204,5 +204,5 @@
 
 	public void syncPanel() {
-		boolean rad = ((dlg.panelMain.mark.getRadar() != Rtb.NORTB) && (dlg.panelMain.mark.getRadar() != Rtb.REFLECTOR));
+		boolean rad = ((SmedAction.panelMain.mark.getRadar() != Rtb.NORTB) && (SmedAction.panelMain.mark.getRadar() != Rtb.REFLECTOR));
 		groupLabel.setVisible(rad);
 		groupBox.setVisible(rad);
@@ -219,15 +219,15 @@
 		sectorsLabel.setVisible(rad);
 		for (Rtb rtb : rads.keySet()) {
-			rads.get(rtb).setBorderPainted(dlg.panelMain.mark.getRadar() == rtb);
-		}
-		groupBox.setText(dlg.panelMain.mark.getRaconGroup());
-		seqBox.setText(dlg.panelMain.mark.getRaconSequence());
-		periodBox.setText(dlg.panelMain.mark.getRaconPeriod());
-		rangeBox.setText(dlg.panelMain.mark.getRaconRange());
-		sector1Box.setText(dlg.panelMain.mark.getRaconSector1());
-		sector2Box.setText(dlg.panelMain.mark.getRaconSector2());
-		aisButton.setSelected(dlg.panelMain.mark.getRadio() != Cat.NOROS);
+			rads.get(rtb).setBorderPainted(SmedAction.panelMain.mark.getRadar() == rtb);
+		}
+		groupBox.setText(SmedAction.panelMain.mark.getRaconGroup());
+		seqBox.setText(SmedAction.panelMain.mark.getRaconSequence());
+		periodBox.setText(SmedAction.panelMain.mark.getRaconPeriod());
+		rangeBox.setText(SmedAction.panelMain.mark.getRaconRange());
+		sector1Box.setText(SmedAction.panelMain.mark.getRaconSector1());
+		sector2Box.setText(SmedAction.panelMain.mark.getRaconSector2());
+		aisButton.setSelected(SmedAction.panelMain.mark.getRadio() != Cat.NOROS);
 		aisButton.setBorderPainted(aisButton.isSelected());
-		radioCatBox.setVisible(dlg.panelMain.mark.getRadio() != Cat.NOROS);
+		radioCatBox.setVisible(SmedAction.panelMain.mark.getRadio() != Cat.NOROS);
 	}
 
Index: applications/editors/josm/plugins/smed/src/panels/PanelSaw.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelSaw.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelSaw.java	(revision 30738)
@@ -27,19 +27,19 @@
 				JRadioButton button = shapes.get(shp);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setShape(shp);
-					dlg.panelMain.mark.setObject(objects.get(shp));
+					SmedAction.panelMain.mark.setShape(shp);
+					SmedAction.panelMain.mark.setObject(objects.get(shp));
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			if (dlg.panelMain.mark.testValid()) {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(true);
-				dlg.panelMain.mark.setObjPattern(Pat.VSTRP);
-				dlg.panelMain.mark.setObjColour(Col.RED);
-				dlg.panelMain.mark.addObjColour(Col.WHITE);
+			if (SmedAction.panelMain.mark.testValid()) {
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
+				SmedAction.panelMain.mark.setObjPattern(Pat.VSTRP);
+				SmedAction.panelMain.mark.setObjColour(Col.RED);
+				SmedAction.panelMain.mark.addObjColour(Col.WHITE);
 			} else {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(false);
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
 			}
-			dlg.panelMain.panelMore.syncPanel();
+			SmedAction.panelMain.panelMore.syncPanel();
 		}
 	};
@@ -58,10 +58,10 @@
 		for (Shp shp : shapes.keySet()) {
 			JRadioButton button = shapes.get(shp);
-			if (dlg.panelMain.mark.getShape() == shp) {
+			if (SmedAction.panelMain.mark.getShape() == shp) {
 				button.setBorderPainted(true);
 			} else
 				button.setBorderPainted(false);
 		}
-		dlg.panelMain.mark.testValid();
+		SmedAction.panelMain.mark.testValid();
 	}
 	
Index: applications/editors/josm/plugins/smed/src/panels/PanelSectors.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelSectors.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelSectors.java	(revision 30738)
@@ -123,8 +123,8 @@
 
 		public int getRowCount() {
-			if (dlg.panelMain == null)
+			if (SmedAction.panelMain == null)
 				return 1;
 			else
-				return dlg.panelMain.mark.getSectorCount();
+				return SmedAction.panelMain.mark.getSectorCount();
 		}
 
@@ -152,27 +152,27 @@
 					return row;
 			case 1:
-				if (((String)dlg.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
-					if (dlg.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL) {
+				if (((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
+					if (SmedAction.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL) {
 						return Col.UNKCOL;
 					} else {
-						return dlg.panelMain.mark.getLightAtt(Att.ALT, row);
+						return SmedAction.panelMain.mark.getLightAtt(Att.ALT, row);
 					}
 				} else {
-					return dlg.panelMain.mark.getLightAtt(Att.COL, row);
+					return SmedAction.panelMain.mark.getLightAtt(Att.COL, row);
 				}
 			case 6:
-				return (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR);
+				return (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR);
 			case 7:
 			case 8:
-				if (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR)
-					return dlg.panelMain.mark.getLightAtt(Att.ORT, row);
+				if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR)
+					return SmedAction.panelMain.mark.getLightAtt(Att.ORT, row);
 				else
-					return dlg.panelMain.mark.getLightAtt(col - 1, row);
+					return SmedAction.panelMain.mark.getLightAtt(col - 1, row);
 			case 12:
-				return visibilities.get(dlg.panelMain.mark.getLightAtt(Att.VIS, row));
+				return visibilities.get(SmedAction.panelMain.mark.getLightAtt(Att.VIS, row));
 			case 13:
-				return exhibitions.get(dlg.panelMain.mark.getLightAtt(Att.EXH, row));
+				return exhibitions.get(SmedAction.panelMain.mark.getLightAtt(Att.EXH, row));
 			default:
-				return dlg.panelMain.mark.getLightAtt(col - 1, row);
+				return SmedAction.panelMain.mark.getLightAtt(col - 1, row);
 			}
 		}
@@ -184,13 +184,13 @@
 					ImageIcon img = colours.get(colour);
 					if (img == value)
-						if (((String)dlg.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
-							if (((colour == Col.UNKCOL) && (dlg.panelMain.mark.getLightAtt(Att.ALT, row) == Col.UNKCOL))
-									|| (dlg.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL)) {
-								dlg.panelMain.mark.setLightAtt(Att.COL, row, colour);
+						if (((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
+							if (((colour == Col.UNKCOL) && (SmedAction.panelMain.mark.getLightAtt(Att.ALT, row) == Col.UNKCOL))
+									|| (SmedAction.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL)) {
+								SmedAction.panelMain.mark.setLightAtt(Att.COL, row, colour);
 							} else {
-								dlg.panelMain.mark.setLightAtt(Att.ALT, row, colour);
+								SmedAction.panelMain.mark.setLightAtt(Att.ALT, row, colour);
 							}
 						} else {
-							dlg.panelMain.mark.setLightAtt(Att.COL, row, colour);
+							SmedAction.panelMain.mark.setLightAtt(Att.COL, row, colour);
 						}
 				}
@@ -200,22 +200,22 @@
 			case 10:
 			case 11:
-				dlg.panelMain.mark.setLightAtt(col - 1, row, value);
+				SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
 				break;
 			case 6:
 				if ((Boolean) value == true) {
-					dlg.panelMain.mark.setLightAtt(Att.LIT, row, Lit.DIR);
-					dlg.panelMain.mark.setLightAtt(Att.BEG, row, "");
-					dlg.panelMain.mark.setLightAtt(Att.END, row, "");
+					SmedAction.panelMain.mark.setLightAtt(Att.LIT, row, Lit.DIR);
+					SmedAction.panelMain.mark.setLightAtt(Att.BEG, row, "");
+					SmedAction.panelMain.mark.setLightAtt(Att.END, row, "");
 				} else {
-					dlg.panelMain.mark.setLightAtt(Att.LIT, row, Lit.UNKLIT);
-					dlg.panelMain.mark.setLightAtt(Att.ORT, row, "");
+					SmedAction.panelMain.mark.setLightAtt(Att.LIT, row, Lit.UNKLIT);
+					SmedAction.panelMain.mark.setLightAtt(Att.ORT, row, "");
 				}
 				break;
 			case 7:
 			case 8:
-				if (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR) {
-					dlg.panelMain.mark.setLightAtt(Att.ORT, row, value);
+				if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR) {
+					SmedAction.panelMain.mark.setLightAtt(Att.ORT, row, value);
 				} else {
-					dlg.panelMain.mark.setLightAtt(col - 1, row, value);
+					SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
 				}
 				break;
@@ -224,5 +224,5 @@
 					String str = visibilities.get(vis);
 					if (str.equals(value))
-						dlg.panelMain.mark.setLightAtt(Att.VIS, row, vis);
+						SmedAction.panelMain.mark.setLightAtt(Att.VIS, row, vis);
 				}
 				break;
@@ -231,9 +231,9 @@
 					String str = exhibitions.get(exh);
 					if (str.equals(value))
-						dlg.panelMain.mark.setLightAtt(Att.EXH, row, exh);
+						SmedAction.panelMain.mark.setLightAtt(Att.EXH, row, exh);
 				}
 				break;
 			default:
-				dlg.panelMain.mark.setLightAtt(col - 1, row, value);
+				SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
 			}
 		}
@@ -261,10 +261,10 @@
 		}
 		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
-			if (!((String)dlg.panelMain.mark.getLightAtt(Att.CHR, rowIndex)).contains("Al")) {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
+			if (!((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, rowIndex)).contains("Al")) {
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
 			} else {
-				col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, rowIndex)));
-			}
-			col1Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
+				col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, rowIndex)));
+			}
+			col1Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
 			return this;
 		}
@@ -276,5 +276,5 @@
 
 	public void addSector(int idx) {
-		dlg.panelMain.mark.addLight(idx);
+		SmedAction.panelMain.mark.addLight(idx);
 		table.setSize(860, ((table.getRowCount() * 16) + 28));
 		if (table.getRowCount() > 3) {
@@ -287,5 +287,5 @@
 	public void deleteSector(int idx) {
 		if (idx > 0) {
-			dlg.panelMain.mark.delLight(idx);
+			SmedAction.panelMain.mark.delLight(idx);
 			table.setSize(860, ((table.getRowCount() * 16) + 28));
 			if (table.getRowCount() > 3) {
Index: applications/editors/josm/plugins/smed/src/panels/PanelSpec.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelSpec.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelSpec.java	(revision 30738)
@@ -24,5 +24,5 @@
 				int idx = categories.get(cat);
 				if (dlg.node != null && (idx == categoryBox.getSelectedIndex()))
-					dlg.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.setCategory(cat);
 			}
 		}
@@ -35,12 +35,12 @@
 				int idx = moorings.get(cat);
 				if (dlg.node != null && (idx == mooringBox.getSelectedIndex())) {
-					dlg.panelMain.mark.setCategory(cat);
+					SmedAction.panelMain.mark.setCategory(cat);
 					if ((cat == Cat.INB_CALM) || (cat == Cat.INB_SBM)) {
-						dlg.panelMain.mark.setObject(Obj.BOYINB);
-						dlg.panelMain.mark.setShape(Shp.UNKSHP);
+						SmedAction.panelMain.mark.setObject(Obj.BOYINB);
+						SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 					} else {
-						dlg.panelMain.mark.setObject(Obj.MORFAC);
+						SmedAction.panelMain.mark.setObject(Obj.MORFAC);
 						if (cat != Cat.MOR_BUOY)
-							dlg.panelMain.mark.setShape(Shp.UNKSHP);
+							SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
 					}
 				}
@@ -66,20 +66,20 @@
 	public ActionListener alShape = new ActionListener() {
 		public void actionPerformed(java.awt.event.ActionEvent e) {
-			if ((dlg.panelMain.mark.getObject() != Obj.MORFAC) || (dlg.panelMain.mark.getCategory() == Cat.MOR_BUOY)) {
+			if ((SmedAction.panelMain.mark.getObject() != Obj.MORFAC) || (SmedAction.panelMain.mark.getCategory() == Cat.MOR_BUOY)) {
 				for (Shp shp : shapes.keySet()) {
 					JRadioButton button = shapes.get(shp);
 					if (button.isSelected()) {
-						dlg.panelMain.mark.setShape(shp);
-						if (SeaMark.EntMAP.get(dlg.panelMain.mark.getObject()) != Ent.MOORING) {
-							dlg.panelMain.mark.setObject(objects.get(shp));
-							if (dlg.panelMain.mark.getObjColour(0) == Col.UNKCOL) {
-								dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-								dlg.panelMain.mark.setObjColour(Col.YELLOW);
+						SmedAction.panelMain.mark.setShape(shp);
+						if (SeaMark.EntMAP.get(SmedAction.panelMain.mark.getObject()) != Ent.MOORING) {
+							SmedAction.panelMain.mark.setObject(objects.get(shp));
+							if (SmedAction.panelMain.mark.getObjColour(0) == Col.UNKCOL) {
+								SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+								SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
 							}
 							if (button == cairnButton) {
-								dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-								dlg.panelMain.mark.setObjColour(Col.UNKCOL);
+								SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+								SmedAction.panelMain.mark.setObjColour(Col.UNKCOL);
 							}
-							topmarkButton.setVisible(dlg.panelMain.mark.testValid());
+							topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
 						}
 						button.setBorderPainted(true);
@@ -87,5 +87,5 @@
 						button.setBorderPainted(false);
 				}
-				dlg.panelMain.panelMore.syncPanel();
+				SmedAction.panelMain.panelMore.syncPanel();
 			}
 		}
@@ -95,15 +95,15 @@
 		public void actionPerformed(java.awt.event.ActionEvent e) {
 			if (topmarkButton.isSelected()) {
-				dlg.panelMain.mark.setTopmark(Top.X_SHAPE);
-				dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
-				dlg.panelMain.mark.setTopColour(Col.YELLOW);
+				SmedAction.panelMain.mark.setTopmark(Top.X_SHAPE);
+				SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
+				SmedAction.panelMain.mark.setTopColour(Col.YELLOW);
 				topmarkButton.setBorderPainted(true);
 			} else {
-				dlg.panelMain.mark.setTopmark(Top.NOTOP);
-				dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
-				dlg.panelMain.mark.setTopColour(Col.UNKCOL);
+				SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
+				SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
+				SmedAction.panelMain.mark.setTopColour(Col.UNKCOL);
 				topmarkButton.setBorderPainted(false);
 			}
-			dlg.panelMain.panelTop.syncPanel();
+			SmedAction.panelMain.panelTop.syncPanel();
 		}
 	};
@@ -111,13 +111,13 @@
 	private ActionListener alNotice = new ActionListener() {
 		public void actionPerformed(java.awt.event.ActionEvent e) {
-			dlg.panelMain.mark.clrMark();
+			SmedAction.panelMain.mark.clrMark();
 			if (noticeButton.isSelected()) {
-				dlg.panelMain.mark.setObject(Obj.NOTMRK);
+				SmedAction.panelMain.mark.setObject(Obj.NOTMRK);
 				noticeButton.setBorderPainted(true);
 			} else {
-				dlg.panelMain.mark.setObject(Obj.UNKOBJ);
+				SmedAction.panelMain.mark.setObject(Obj.UNKOBJ);
 				noticeButton.setBorderPainted(false);
 			}
-			dlg.panelMain.syncPanel();
+			SmedAction.panelMain.syncPanel();
 		}
 	};
@@ -125,9 +125,9 @@
 	private ActionListener alMooring = new ActionListener() {
 		public void actionPerformed(java.awt.event.ActionEvent e) {
-			dlg.panelMain.mark.setObject(Obj.UNKOBJ);
-			dlg.panelMain.mark.setCategory(Cat.NOCAT);
-			dlg.panelMain.mark.setTopmark(Top.NOTOP);
+			SmedAction.panelMain.mark.setObject(Obj.UNKOBJ);
+			SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
+			SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
 			if (mooringButton.isSelected()) {
-				dlg.panelMain.mark.setObject(Obj.MORFAC);
+				SmedAction.panelMain.mark.setObject(Obj.MORFAC);
 				categoryBox.setVisible(false);
 				mooringBox.setVisible(true);
@@ -234,5 +234,5 @@
 
 	public void syncPanel() {
-		if (SeaMark.EntMAP.get(dlg.panelMain.mark.getObject()) == Ent.MOORING) {
+		if (SeaMark.EntMAP.get(SmedAction.panelMain.mark.getObject()) == Ent.MOORING) {
 			mooringButton.setBorderPainted(true);
 			categoryBox.setVisible(false);
@@ -248,5 +248,5 @@
 			for (Cat cat : moorings.keySet()) {
 				int item = moorings.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					mooringBox.setSelectedIndex(item);
 			}
@@ -262,10 +262,10 @@
 			cairnButton.setEnabled(true);
 			noticeButton.setEnabled(true);
-			topmarkButton.setBorderPainted(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
-			topmarkButton.setSelected(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
-			topmarkButton.setVisible(dlg.panelMain.mark.testValid());
+			topmarkButton.setBorderPainted(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
+			topmarkButton.setSelected(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
+			topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
 			for (Cat cat : categories.keySet()) {
 				int item = categories.get(cat);
-				if (dlg.panelMain.mark.getCategory() == cat)
+				if (SmedAction.panelMain.mark.getCategory() == cat)
 					categoryBox.setSelectedIndex(item);
 			}
@@ -273,5 +273,5 @@
 		for (Shp shp : shapes.keySet()) {
 			JRadioButton button = shapes.get(shp);
-			if (dlg.panelMain.mark.getShape() == shp) {
+			if (SmedAction.panelMain.mark.getShape() == shp) {
 				button.setBorderPainted(true);
 			} else
@@ -279,5 +279,5 @@
 		}
 		noticeButton.setBorderPainted(false);
-		dlg.panelMain.mark.testValid();
+		SmedAction.panelMain.mark.testValid();
 	}
 
Index: applications/editors/josm/plugins/smed/src/panels/PanelStbd.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelStbd.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelStbd.java	(revision 30738)
@@ -31,56 +31,56 @@
 				JRadioButton button = shapes.get(shp);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setShape(shp);
-					dlg.panelMain.mark.setObject(objects.get(shp));
+					SmedAction.panelMain.mark.setShape(shp);
+					SmedAction.panelMain.mark.setObject(objects.get(shp));
 					button.setBorderPainted(true);
 				} else
 					button.setBorderPainted(false);
 			}
-			if (dlg.panelMain.mark.testValid()) {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(true);
-				dlg.panelMain.panelChan.lightButton.setVisible(true);
-				if (dlg.panelMain.mark.getCategory() == Cat.LAM_STBD) {
-					switch (dlg.panelMain.mark.getRegion()) {
+			if (SmedAction.panelMain.mark.testValid()) {
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
+				SmedAction.panelMain.panelChan.lightButton.setVisible(true);
+				if (SmedAction.panelMain.mark.getCategory() == Cat.LAM_STBD) {
+					switch (SmedAction.panelMain.mark.getRegion()) {
 					case A:
-						dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-						dlg.panelMain.mark.setObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+						SmedAction.panelMain.mark.setObjColour(Col.GREEN);
 						break;
 					case B:
-						dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
-						dlg.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
 						break;
 					case C:
-						dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
-						dlg.panelMain.mark.setObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.WHITE);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.WHITE);
+						SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
+						SmedAction.panelMain.mark.setObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.WHITE);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.WHITE);
 						break;
 					}
 				} else {
-					dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
-					switch (dlg.panelMain.mark.getRegion()) {
+					SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
+					switch (SmedAction.panelMain.mark.getRegion()) {
 					case A:
-						dlg.panelMain.mark.setObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
 						break;
 					case B:
-						dlg.panelMain.mark.setObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
 						break;
 					case C:
-						dlg.panelMain.mark.setObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
-						dlg.panelMain.mark.addObjColour(Col.RED);
-						dlg.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.setObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
+						SmedAction.panelMain.mark.addObjColour(Col.RED);
+						SmedAction.panelMain.mark.addObjColour(Col.GREEN);
 						break;
 					}
 				}
-				dlg.panelMain.panelMore.syncPanel();
+				SmedAction.panelMain.panelMore.syncPanel();
 			} else {
-				dlg.panelMain.panelChan.topmarkButton.setVisible(false);
-				dlg.panelMain.panelChan.lightButton.setVisible(false);
+				SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
+				SmedAction.panelMain.panelChan.lightButton.setVisible(false);
 			}
 		}
@@ -104,5 +104,5 @@
 		for (Shp shp : shapes.keySet()) {
 			JRadioButton button = shapes.get(shp);
-			if (dlg.panelMain.mark.getShape() == shp) {
+			if (SmedAction.panelMain.mark.getShape() == shp) {
 				button.setBorderPainted(true);
 			} else
Index: applications/editors/josm/plugins/smed/src/panels/PanelTop.java
===================================================================
--- applications/editors/josm/plugins/smed/src/panels/PanelTop.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/panels/PanelTop.java	(revision 30738)
@@ -38,5 +38,5 @@
 				JRadioButton button = tops.get(top);
 				if (button.isSelected()) {
-					dlg.panelMain.mark.setTopmark(top);
+					SmedAction.panelMain.mark.setTopmark(top);
 					button.setBorderPainted(true);
 				} else
@@ -79,5 +79,5 @@
 		for (Top top : tops.keySet()) {
 			JRadioButton button = tops.get(top);
-			if (dlg.panelMain.mark.getTopmark() == top) {
+			if (SmedAction.panelMain.mark.getTopmark() == top) {
 				button.setBorderPainted(true);
 			} else
Index: applications/editors/josm/plugins/smed/src/seamarks/SeaMark.java
===================================================================
--- applications/editors/josm/plugins/smed/src/seamarks/SeaMark.java	(revision 30737)
+++ applications/editors/josm/plugins/smed/src/seamarks/SeaMark.java	(revision 30738)
@@ -1361,18 +1361,18 @@
 		}
 		if (tmp) {
-			dlg.panelMain.moreButton.setVisible(true);
-			dlg.panelMain.saveButton.setEnabled(true);
-			dlg.panelMain.topButton.setEnabled(true);
-			dlg.panelMain.fogButton.setEnabled(true);
-			dlg.panelMain.radButton.setEnabled(true);
-			dlg.panelMain.litButton.setEnabled(true);
+			SmedAction.panelMain.moreButton.setVisible(true);
+			SmedAction.panelMain.saveButton.setEnabled(true);
+			SmedAction.panelMain.topButton.setEnabled(true);
+			SmedAction.panelMain.fogButton.setEnabled(true);
+			SmedAction.panelMain.radButton.setEnabled(true);
+			SmedAction.panelMain.litButton.setEnabled(true);
 			return true;
 		} else {
-			dlg.panelMain.moreButton.setVisible(false);
-			dlg.panelMain.moreButton.setText(">>");
-			dlg.panelMain.topButton.setEnabled(false);
-			dlg.panelMain.fogButton.setEnabled(false);
-			dlg.panelMain.radButton.setEnabled(false);
-			dlg.panelMain.litButton.setEnabled(false);
+			SmedAction.panelMain.moreButton.setVisible(false);
+			SmedAction.panelMain.moreButton.setText(">>");
+			SmedAction.panelMain.topButton.setEnabled(false);
+			SmedAction.panelMain.fogButton.setEnabled(false);
+			SmedAction.panelMain.radButton.setEnabled(false);
+			SmedAction.panelMain.litButton.setEnabled(false);
 			PanelMain.messageBar.setText("Seamark not recognised");
 			return false;
@@ -1398,5 +1398,5 @@
 		setSource("");
 		setFixme("");
-		dlg.panelMain.syncPanel();
+		SmedAction.panelMain.syncPanel();
 		repaint();
 	}
Index: applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java
===================================================================
--- applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java	(revision 30737)
+++ applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java	(revision 30738)
@@ -68,7 +68,7 @@
             // @see LiveGpsLayer
             PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(tmpFile)));
-            GpxWriter gpxWriter = new GpxWriter(out);
-            gpxWriter.write(gpsLayer.data);
-            gpxWriter.close();
+            try (GpxWriter gpxWriter = new GpxWriter(out)) {
+            	gpxWriter.write(gpsLayer.data);
+            }
             tmpFile.renameTo(file);
         } catch (IOException ioExc) {
Index: applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java
===================================================================
--- applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java	(revision 30737)
+++ applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java	(revision 30738)
@@ -26,7 +26,7 @@
 
 import org.openstreetmap.josm.Main;
+import org.openstreetmap.josm.actions.JosmAction;
 import org.openstreetmap.josm.tools.Shortcut;
 import org.openstreetmap.josm.tools.XmlObjectParser;
-import org.openstreetmap.josm.actions.JosmAction;
 import org.xml.sax.SAXException;
 
@@ -50,5 +50,6 @@
     }
 
-    public void actionPerformed(ActionEvent e) {
+    @Override
+	public void actionPerformed(ActionEvent e) {
         if(surveyorFrame == null) {
             surveyorFrame = new JFrame();
@@ -64,5 +65,6 @@
             // zoomout:
             actionMap.put("zoomout", new AbstractAction() {
-                public void actionPerformed(ActionEvent e) {
+                @Override
+				public void actionPerformed(ActionEvent e) {
                     if(Main.map != null && Main.map.mapView != null) {
                         Main.map.mapView.zoomToFactor(2);
@@ -73,5 +75,6 @@
             // zoomin:
             actionMap.put("zoomin", new AbstractAction() {
-                public void actionPerformed(ActionEvent e) {
+                @Override
+				public void actionPerformed(ActionEvent e) {
                     if(Main.map != null && Main.map.mapView != null) {
                         Main.map.mapView.zoomToFactor(1/2);
@@ -82,5 +85,6 @@
             // autocenter:
             actionMap.put("autocenter", new AbstractAction() {
-                public void actionPerformed(ActionEvent e) {
+                @Override
+				public void actionPerformed(ActionEvent e) {
                     // toggle autocenter
                     gpsPlugin.setAutoCenter(!gpsPlugin.isAutoCenter());
@@ -105,5 +109,4 @@
 
     public SurveyorComponent createComponent() {
-        InputStream in = null;
         String source = Main.pref.get("surveyor.source");
         if(source == null || source.length() == 0) {
@@ -114,18 +117,14 @@
             // </FIXXME>
         }
-        SurveyorComponent component= null;
-        try {
-            in = ResourceLoader.getInputStream(source);
-            component = createComponent(in);
-            in.close();
-            return component;
+        try (InputStream in = ResourceLoader.getInputStream(source)) {
+            return createComponent(in);
         } catch (IOException e) {
-            e.printStackTrace();
+            Main.error(e);
             JOptionPane.showMessageDialog(Main.parent, tr("Could not read surveyor definition: {0}",source));
         } catch (SAXException e) {
-            e.printStackTrace();
+            Main.error(e);
             JOptionPane.showMessageDialog(Main.parent, tr("Error parsing {0}: {1}", source, e.getMessage()));
         }
-        return component;
+        return null;
     }
 
Index: applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java
===================================================================
--- applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java	(revision 30737)
+++ applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java	(revision 30738)
@@ -28,5 +28,6 @@
      * @throws IOException if an error occurs on opening the url, or if the file is not found.
      */
-    public static InputStream getInputStream(String source) throws IOException {
+    @SuppressWarnings("resource")
+	public static InputStream getInputStream(String source) throws IOException {
         InputStream in = null;
         if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://") || source.startsWith("file:")) {
Index: applications/editors/josm/plugins/tageditor/src/org/openstreetmap/josm/plugins/tageditor/tagspec/TagSpecifications.java
===================================================================
--- applications/editors/josm/plugins/tageditor/src/org/openstreetmap/josm/plugins/tageditor/tagspec/TagSpecifications.java	(revision 30737)
+++ applications/editors/josm/plugins/tageditor/src/org/openstreetmap/josm/plugins/tageditor/tagspec/TagSpecifications.java	(revision 30738)
@@ -26,8 +26,8 @@
 /**
  * This class manages a list of {@link TagSpecification}s.
- * 
+ *
  * It also provides a method for reading a list of {@link TagSpecification}s from
  * an XML file.
- * 
+ *
  * @author Gubaer
  *
@@ -63,5 +63,5 @@
      * loads the tag specifications from the resource file given by
      * {@link #RES_NAME_TAG_SPECIFICATIONS}.
-     * 
+     *
      * @return the list of {@link TagSpecification}s
      * @throws Exception thrown, if an exception occurs
@@ -71,11 +71,11 @@
         if (in == null) {
             logger.log(Level.SEVERE, "failed to create input stream for resource '" + RES_NAME_TAG_SPECIFICATIONS + "'");
-        }
-        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
-        TagSpecifications spec = new TagSpecifications();
-        spec.load(reader);
-        reader.close();
-        instance = spec;
-
+            return;
+        }
+        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
+	        TagSpecifications spec = new TagSpecifications();
+	        spec.load(reader);
+	        instance = spec;
+        }
     }
 
@@ -97,5 +97,5 @@
     /**
      * loads the tag specifications from a specific reader
-     * 
+     *
      * @param in  the reader to read from
      * @throws Exception thrown, if an exception occurs
@@ -156,9 +156,9 @@
         return items;
     }
-    
+
     /**
      * replies a list of {@see KeyValuePair}s for all {@see TagSpecification}s and
      * {@see LableSpecification}s.
-     * 
+     *
      * @return the list
      */
@@ -178,5 +178,5 @@
     /**
      * The SAX handler for reading XML files with tag specifications
-     * 
+     *
      * @author gubaer
      *
@@ -212,5 +212,5 @@
          * parses a string value consisting of 'yes' or 'no' (exactly, case
          * sensitive)
-         * 
+         *
          * @param value the string value
          * @return true, if value is <code>yes</code>; false, if value is <code>no</code>
@@ -228,5 +228,5 @@
         /**
          * handles a start element with name <code>osm-tag-definitions</code>
-         * 
+         *
          * @param atts  the XML attributes
          * @throws SAXException
@@ -238,5 +238,5 @@
         /**
          * handles an end element with name <code>osm-tag-specifications</code>
-         * 
+         *
          * @throws SAXException
          */
@@ -247,5 +247,5 @@
         /**
          * handles a start element with name <code>tag</code>
-         * 
+         *
          * @param atts the XML attributes of the element
          * @throws SAXException
@@ -285,5 +285,5 @@
         /**
          * handles a start element with name <code>label</code>
-         * 
+         *
          * @param atts the XML attributes
          * @throws SAXException
@@ -311,5 +311,5 @@
         /**
          * handles an end element with name <code>label</code>
-         * 
+         *
          * @throws SAXException
          */
@@ -352,5 +352,6 @@
     class ResourceEntityResolver implements EntityResolver {
 
-        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
+        @Override
+		public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
             if (systemId != null && systemId.endsWith(DTD)) {
                 InputStream stream = TagSpecifications.class.getResourceAsStream("/resources/"+DTD);
Index: applications/editors/josm/plugins/tracer2/src/org/openstreetmap/josm/plugins/tracer2/preferences/ServerParamList.java
===================================================================
--- applications/editors/josm/plugins/tracer2/src/org/openstreetmap/josm/plugins/tracer2/preferences/ServerParamList.java	(revision 30737)
+++ applications/editors/josm/plugins/tracer2/src/org/openstreetmap/josm/plugins/tracer2/preferences/ServerParamList.java	(revision 30738)
@@ -1,15 +1,15 @@
 /**
  *  Tracer2 - plug-in for JOSM to capture contours
- *  
+ *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
- *  
+ *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
- *  
+ *
  *  You should have received a copy of the GNU General Public License along
  *  with this program; if not, write to the Free Software Foundation, Inc.,
@@ -28,9 +28,11 @@
 import java.util.List;
 
+import org.openstreetmap.josm.Main;
+
 public class ServerParamList {
     ArrayList<ServerParam> m_listServerParam = new ArrayList<>();
     ServerParam m_oActivParam = null;
     String m_strFilename;
-    
+
     public ServerParamList(String filename) {
         this.m_strFilename = filename;
@@ -41,8 +43,7 @@
         }
     }
-    
+
     public void load() {
-        try {
-            BufferedReader oReader = new BufferedReader(new InputStreamReader(new FileInputStream(m_strFilename), "UTF-8"));
+        try (BufferedReader oReader = new BufferedReader(new InputStreamReader(new FileInputStream(m_strFilename), "UTF-8"))) {
             StringBuilder oBuilder = new StringBuilder();
             String strLine;
@@ -54,14 +55,14 @@
                 }
             }
-            oReader.close();
         } catch (Exception e) {
         	loadDefault();
         }
     }
-    
+
     public void loadDefault() {
-        try {
+        try (
         	InputStream oIP = getClass().getResourceAsStream("/resources/serverParam.cfg");
             BufferedReader oReader = new BufferedReader(new InputStreamReader(oIP));
+        ) {
             StringBuilder oBuilder = new StringBuilder();
             String strLine;
@@ -73,28 +74,23 @@
                 }
             }
-            oReader.close();
         } catch (Exception e) {
-        	System.err.println("Tracer2 warning: can't load file " + m_strFilename);
-            //e.printStackTrace();
+        	Main.warn("Tracer2 warning: can't load file " + m_strFilename);
         }
     }
 
     public void save() {
-        try {
-            OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream(m_strFilename), "UTF-8");
+        try (OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream(m_strFilename), "UTF-8")) {
             for (ServerParam param : m_listServerParam) {
             	oWriter.write(param.serialize());
             }
-            oWriter.close();
         } catch (Exception e) {
-        	System.err.println("Tracer2 warning: can't save file " + m_strFilename);
-            //e.printStackTrace();
+        	Main.warn("Tracer2 warning: can't save file " + m_strFilename);
         }
     }
-    
+
     public List<ServerParam> getParamList() {
         return m_listServerParam;
     }
-    
+
     public ServerParam getActivParam() {
         return m_oActivParam;
@@ -105,5 +101,5 @@
     	}
     }
-    
+
     public List<ServerParam> getEnableParamList() {
     	List<ServerParam> listParam = new ArrayList<>();
@@ -115,13 +111,12 @@
     	return listParam;
     }
-    
+
     public void addParam(ServerParam param) {
     	m_listServerParam.add(param);
     }
-    
+
     public void removeParam(ServerParam param) {
     	param.setEnabled(false);
     	m_listServerParam.remove(param);
     }
-    
 }
Index: applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java
===================================================================
--- applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java	(revision 30737)
+++ applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java	(revision 30738)
@@ -13,4 +13,5 @@
 import org.bouncycastle.bcpg.BCPGOutputStream;
 import org.bouncycastle.openpgp.PGPSignature;
+import org.openstreetmap.josm.Main;
 
 public class TrustSignatures {
@@ -126,7 +127,6 @@
         if (textsigs.containsKey(plain)){
             List<PGPSignature> l = textsigs.get(plain);
-            try {
-                ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                ArmoredOutputStream aOut = new ArmoredOutputStream(baos);
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            try (ArmoredOutputStream aOut = new ArmoredOutputStream(baos)) {
                 aOut.beginClearText(l.get(0).getHashAlgorithm());
                 aOut.write(plain.getBytes(Charset.forName("UTF-8")));
@@ -134,16 +134,14 @@
                 aOut.endClearText();
 
-                BCPGOutputStream bOut = new BCPGOutputStream(aOut);
-                for (PGPSignature sig : l) {
-                    sig.encode(bOut);
+                try (BCPGOutputStream bOut = new BCPGOutputStream(aOut)) {
+		            for (PGPSignature sig : l) {
+		                sig.encode(bOut);
+		            }
                 }
-
-                bOut.close();
-                aOut.close();
 
                 return baos.toString("UTF-8");
 
             } catch (Exception e) {
-                e.printStackTrace();
+                Main.error(e);
                 return "Error - read console Output";
             }
@@ -153,7 +151,6 @@
 
     public String getArmoredFulltextSignature(PGPSignature sig) {
-        try {
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            ArmoredOutputStream aOut = new ArmoredOutputStream(baos);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        try (ArmoredOutputStream aOut = new ArmoredOutputStream(baos)) {
             aOut.beginClearText(sig.getHashAlgorithm());
             aOut.write(getSigtext(sig).getBytes(Charset.forName("UTF-8")));
@@ -161,16 +158,13 @@
             aOut.endClearText();
 
-            BCPGOutputStream bOut = new BCPGOutputStream(aOut);
-            sig.encode(bOut);
-            bOut.close();
-            aOut.close();
-
+            try (BCPGOutputStream bOut = new BCPGOutputStream(aOut)) {
+            	sig.encode(bOut);
+            }
 
             return baos.toString("UTF-8");
         } catch (Exception e) {
-            e.printStackTrace();
+            Main.error(e);
             return "Error - read console Output";
         }
     }
-
 }
Index: applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java
===================================================================
--- applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java	(revision 30737)
+++ applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java	(revision 30738)
@@ -8,8 +8,8 @@
 /**
  * This class is released under GNU general public license
- * 
+ *
  * Description: This class generates random names from syllables, and provides programmer a
  * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names.
- * 
+ *
  * SYLLABLE FILE REQUIREMENTS/FORMAT:
  * 1) all syllables are separated by line break.
@@ -17,5 +17,5 @@
  * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
  * 4) Empty lines are ignored.
- * 
+ *
  * SYLLABLE CLASSIFICATION:
  * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix.
@@ -23,14 +23,14 @@
  * To declare syllable as a suffix in the file, insert "+" as a first character of the line.
  * everything else is read as a middle part.
- * 
+ *
  * NUMBER OF SYLLABLES:
  * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix.
  * In case of 1 syllable, name will be chosen from amongst the prefixes.
  * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.
- * 
+ *
  * ASSIGNING RULES:
  * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the
  * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.
- * 
+ *
  * RULES:
  * 1) +v means that next syllable must definitely start with a vocal.
@@ -41,8 +41,8 @@
  * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected
  * and RuntimeException will be thrown.
- * 
+ *
  * TO START:
  * Create a new NameGenerator object, provide the syllable file, and create names using compose() method.
- * 
+ *
  * @author Joonas Vali, August 2009.
  *
@@ -85,36 +85,29 @@
      */
     public void refresh() throws IOException{
-
-        FileReader input = null;
-        BufferedReader bufRead;
-        String line;
-
-        input = new FileReader(fileName);
-
-        bufRead = new BufferedReader(input);
-        line="";
-
-        while(line != null){
-            line = bufRead.readLine();
-            if(line != null && !line.equals("")){
-                if(line.charAt(0) == '-'){
-                    pre.add(line.substring(1).toLowerCase());
-                }
-                else if(line.charAt(0) == '+'){
-                    sur.add(line.substring(1).toLowerCase());
-                }
-                else{
-                    mid.add(line.toLowerCase());
-                }
-            }
-        }
-        bufRead.close();
-    }
-
-    private String upper(String s){
+    	try (
+	        FileReader input = new FileReader(fileName);
+	        BufferedReader bufRead = new BufferedReader(input);
+		) {
+	        String line="";
+	        while (line != null){
+	            line = bufRead.readLine();
+	            if (line != null && !line.equals("")) {
+	                if(line.charAt(0) == '-') {
+	                    pre.add(line.substring(1).toLowerCase());
+	                } else if (line.charAt(0) == '+') {
+	                    sur.add(line.substring(1).toLowerCase());
+	                } else {
+	                    mid.add(line.toLowerCase());
+	                }
+	            }
+	        }
+    	}
+    }
+
+    private String upper(String s) {
         return s.substring(0,1).toUpperCase().concat(s.substring(1));
     }
 
-    private boolean containsConsFirst(ArrayList<String> array){
+    private boolean containsConsFirst(ArrayList<String> array) {
         for(String s: array){
             if(consonantFirst(s)) return true;
Index: applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java
===================================================================
--- applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java	(revision 30737)
+++ applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java	(revision 30738)
@@ -8,8 +8,8 @@
 /**
  * This class is released under GNU general public license
- * 
+ *
  * Description: This class generates random names from syllables, and provides programmer a
  * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names.
- * 
+ *
  * SYLLABLE FILE REQUIREMENTS/FORMAT:
  * 1) all syllables are separated by line break.
@@ -17,5 +17,5 @@
  * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
  * 4) Empty lines are ignored.
- * 
+ *
  * SYLLABLE CLASSIFICATION:
  * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix.
@@ -23,14 +23,14 @@
  * To declare syllable as a suffix in the file, insert "+" as a first character of the line.
  * everything else is read as a middle part.
- * 
+ *
  * NUMBER OF SYLLABLES:
  * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix.
  * In case of 1 syllable, name will be chosen from amongst the prefixes.
  * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.
- * 
+ *
  * ASSIGNING RULES:
  * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the
  * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.
- * 
+ *
  * RULES:
  * 1) +v means that next syllable must definitely start with a vocal.
@@ -41,8 +41,8 @@
  * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected
  * and RuntimeException will be thrown.
- * 
+ *
  * TO START:
  * Create a new NameGenerator object, provide the syllable file, and create names using compose() method.
- * 
+ *
  * @author Joonas Vali, August 2009.
  *
@@ -85,38 +85,32 @@
      */
     public void refresh() throws IOException{
-
-        FileReader input = null;
-        BufferedReader bufRead;
-        String line;
-
-        input = new FileReader(fileName);
-
-        bufRead = new BufferedReader(input);
-        line="";
-
-        while(line != null){
-            line = bufRead.readLine();
-            if(line != null && !line.equals("")){
-                if(line.charAt(0) == '-'){
-                    pre.add(line.substring(1).toLowerCase());
-                }
-                else if(line.charAt(0) == '+'){
-                    sur.add(line.substring(1).toLowerCase());
-                }
-                else{
-                    mid.add(line.toLowerCase());
-                }
-            }
-        }
-        bufRead.close();
-    }
-
-    private String upper(String s){
+        try (
+    		FileReader input = new FileReader(fileName);
+    		BufferedReader bufRead = new BufferedReader(input);
+        ) {
+        	String line="";
+
+	        while (line != null) {
+	            line = bufRead.readLine();
+	            if (line != null && !line.equals("")) {
+	                if (line.charAt(0) == '-') {
+	                    pre.add(line.substring(1).toLowerCase());
+	                } else if (line.charAt(0) == '+') {
+	                    sur.add(line.substring(1).toLowerCase());
+	                } else{
+	                    mid.add(line.toLowerCase());
+	                }
+	            }
+	        }
+        }
+    }
+
+    private String upper(String s) {
         return s.substring(0,1).toUpperCase().concat(s.substring(1));
     }
 
-    private boolean containsConsFirst(ArrayList<String> array){
-        for(String s: array){
-            if(consonantFirst(s)) return true;
+    private boolean containsConsFirst(ArrayList<String> array) {
+        for (String s: array) {
+            if (consonantFirst(s)) return true;
         }
         return false;
Index: applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java
===================================================================
--- applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java	(revision 30737)
+++ applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java	(revision 30738)
@@ -25,5 +25,6 @@
     }
 
-    public void actionPerformed(ActionEvent e) {
+    @Override
+	public void actionPerformed(ActionEvent e) {
         String wpid = JOptionPane.showInputDialog(Main.parent,
             tr("Enter a walking-papers.org URL or ID (the bit after the ?id= in the URL)"),
@@ -51,6 +52,5 @@
         String tile = null;
 
-        try {
-            BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"));
+        try (BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"))) {
             for (String line = r.readLine(); line != null; line = r.readLine()) {
                 m = spanPattern.matcher(line);
@@ -65,6 +65,7 @@
                 }
             }
-            r.close();
-            if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) throw new Exception();
+            if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) {
+            	throw new IllegalStateException();
+            }
         } catch (Exception ex) {
             JOptionPane.showMessageDialog(Main.parent,tr("Could not read information from walking-papers.org the id \"{0}\"", mungedWpId));
Index: applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikipediaApp.java
===================================================================
--- applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikipediaApp.java	(revision 30737)
+++ applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikipediaApp.java	(revision 30738)
@@ -25,4 +25,5 @@
 import javax.xml.xpath.XPathFactory;
 
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.coor.LatLon;
 import org.openstreetmap.josm.data.osm.OsmPrimitive;
@@ -116,8 +117,7 @@
                 connection.setDoOutput(true);
 
-                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
-                out.write("articles=" + encodeURL(Utils.join(",", articleNames)));
-                out.close();
-
+                try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
+                	out.write("articles=" + encodeURL(Utils.join(",", articleNames)));
+                }
 
                 final Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\n");
@@ -129,5 +129,5 @@
                         status.put(x[0], "1".equals(x[1]));
                     } else {
-                        System.err.println("Unknown element " + line);
+                        Main.error("Unknown element " + line);
                     }
                 }
