From ec6ff3e60403355498a55e800cae1516652eae2a Mon Sep 17 00:00:00 2001
From: tobias <thinkdifferent055@gmail.com>
Date: Sun, 29 Nov 2020 20:43:26 +0100
Subject: [PATCH] #160 - Cleanup code

---
 .../de/tobias/playpad/project/page/Page.java     | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/PlayWallCore/src/main/java/de/tobias/playpad/project/page/Page.java b/PlayWallCore/src/main/java/de/tobias/playpad/project/page/Page.java
index 700457ac..24f20789 100644
--- a/PlayWallCore/src/main/java/de/tobias/playpad/project/page/Page.java
+++ b/PlayWallCore/src/main/java/de/tobias/playpad/project/page/Page.java
@@ -254,7 +254,7 @@ public class Page {
 		final int rows = getProject().getSettings().getRows();
 
 		for (int i = 0; i < rows; i++) {
-			insertPadInto(columns, i, rows * columns);
+			insertPadAndShiftSuccessor(columns, i, rows * columns);
 		}
 	}
 
@@ -263,13 +263,21 @@ public class Page {
 		final int rows = getProject().getSettings().getRows() - 1;
 
 		for (int i = 0; i < columns; i++) {
-			insertPadInto(columns, i, rows * columns);
+			insertPadAndShiftSuccessor(columns, i, rows * columns);
 		}
 	}
 
-	private void insertPadInto(int x, int y, int maxPad) {
+	/**
+	 * Insert a pad into given (x, y). Moves all other pads one position ahead.
+	 *
+	 * @param x            x
+	 * @param y            y
+	 * @param lastPadIndex index of the last pad on the page
+	 */
+	private void insertPadAndShiftSuccessor(int x, int y, int lastPadIndex) {
 		int position = getPadPosition(x, y);
-		for (int i = maxPad - 1; i >= position; i--) {
+		// Going backwards to avoid overwriting the next pad when updating the position of the current one.
+		for (int i = lastPadIndex - 1; i >= position; i--) {
 			getPad(i).setPosition(i + 1);
 		}
 		getPad(position);
-- 
GitLab