board = pcbnew.GetBoard()
for i in range(1, 97):
    keyName = "K_20%02d" % i
    diodeName = "D_20%02d" % i
    key = board.FindModuleByReference(keyName)
    diode = board.FindModuleByReference(diodeName)
    resistor = board.FindModuleByReference("R30%02d" % i)
    led = board.FindModuleByReference("D30%02d" % i)
    
    if diode is None:
        print("Missing diode {}".format(diodeName))
        continue
    
    keyCenterPoint = key.GetPosition()
    
    diodeCenterPoint = pcbnew.wxPoint(keyCenterPoint.x - pcbnew.FromMM(6.4), keyCenterPoint.y - pcbnew.FromMM(1.4))
    diode.SetPosition(diodeCenterPoint)
    diode.SetOrientation(2700)
    
    if (diode.GetLayer() == 0):
        diode.Flip(diode.GetPosition())
    
    ledCenterPoint = pcbnew.wxPoint(keyCenterPoint.x - pcbnew.FromMM(2.46), keyCenterPoint.y + pcbnew.FromMM(10))
    led.SetPosition(ledCenterPoint)
    
    resistorCenterPoint = pcbnew.wxPoint(ledCenterPoint.x - pcbnew.FromMM(0), ledCenterPoint.y + pcbnew.FromMM(3))
    resistor.SetPosition(resistorCenterPoint)

    print("key {}({}) on {}({})"
      .format(key.GetReference(),
              key.GetValue(),
              key.GetPosition().x, key.GetPosition().y
      ))

pcbnew.Refresh()
