#!/usr/bin/python
#GPLv2

import cv2
import sys

import time
def pr(*l):
  print(" ".join(map(str, l)))
#  time.sleep(0.01)

with file('settings.json') as fin:
  import json
  settings = json.load(fin)
  dpm = float(settings['inputDPI'])/25.4
  spotsize = float(settings['spotSize'])
  machinedpm = float(settings['machineDPI'])/25.4
  basic_speed = float(settings['basicSpeed'])
  oversampling = float(settings['oversampling'])
  focus_speed = float(settings['focusSpeed'])
  travel_speed = float(settings['travelSpeed'])
  focusedZ = float(settings['focusedZ'])
  travelZ = float(settings['travelZ'])
  endZ = float(settings['endZ'])
  passes = int(settings['passes'])

def main():
  # header
  pr('G90') # absolute pos
  pr('G21') # units in mm
  pr('M3 S1000') # set spindle speed to 1000
  pr('G4 P15') # wait 10 seconds
  pr('G00 Z{} F400'.format(travelZ)) # go to standby position

  img = cv2.imread(sys.argv[1], 0)
#  imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  #print hierarchy
  for contour in contours:
    for i, p in enumerate(contour):
      p = p[0]
      if i == 0:
        pr('G00 X{} Y{} F{} (begin)'.format(p[0]/dpm, p[1]/dpm, travel_speed))
        pr('G01 Z{} F{} (begin)'.format(focusedZ, focus_speed))
     #   pr('G5 L1')
      pr('G01 X{} Y{} Z{} F{}'.format(p[0]/dpm, p[1]/dpm, focusedZ, basic_speed))
    if len(contour) > 0:
      p = contour[0][0]
      pr('G01 X{} Y{} Z{} F{}'.format(p[0]/dpm, p[1]/dpm, focusedZ, basic_speed))

#    pr('G01 X{} Y{} Z{} F{}'.format(p[0]/dpm, p[1]/dpm, focusedZ, basic_speed))
    #pr('G5 L0')
    pr('G00 X{} Y{} Z{} F{} (retract)'.format(p[0]/dpm, p[1]/dpm, travelZ, basic_speed))
  pr('G00 Z{} F400'.format(endZ))
  pr('M05')
  pr('M02')

if __name__ == "__main__":
  main()
