for loop working but not linking correctly