Welcome to mirror list, hosted at ThFree Co, Russian Federation.

arc_welder.cpp « ArcWelder - github.com/FormerLurker/ArcWelderLib.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1e601e52ec04fa0da0374e2c2cd9203ee69eda87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Arc Welder: Anti-Stutter Library
//
// Compresses many G0/G1 commands into G2/G3(arc) commands where possible, ensuring the tool paths stay within the specified resolution.
// This reduces file size and the number of gcodes per second.
//
// Uses the 'Gcode Processor Library' for gcode parsing, position processing, logging, and other various functionality.
//
// Copyright(C) 2020 - Brad Hochgesang
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This program is free software : you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
//
// You can contact the author at the following email address: 
// FormerLurker@pm.me
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if _MSC_VER > 1200
#define _CRT_SECURE_NO_DEPRECATE
#endif

#include "arc_welder.h"
#include <vector>
#include <sstream>
#include "utilities.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <version.h>

arc_welder::arc_welder(
  std::string source_path,
  std::string target_path,
  logger* log,
  double resolution_mm,
  double path_tolerance_percent,
  double max_radius,
  int min_arc_segments,
  double mm_per_arc_segment,
  bool g90_g91_influences_extruder,
  bool allow_3d_arcs,
  bool allow_travel_arcs,
  bool allow_dynamic_precision,
  unsigned char default_xyz_precision,
  unsigned char default_e_precision,
  double extrusion_rate_variance_percent,
  int max_gcode_length,
  int buffer_size,
  progress_callback callback) : current_arc_(
    DEFAULT_MIN_SEGMENTS,
    buffer_size,
    resolution_mm,
    path_tolerance_percent,
    max_radius,
    min_arc_segments,
    mm_per_arc_segment,
    allow_3d_arcs,
    default_xyz_precision,
    default_e_precision,
    max_gcode_length
  ),
  segment_statistics_(
    segment_statistic_lengths,
    segment_statistic_lengths_count,
    log
  ),
  travel_statistics_(
    segment_statistic_lengths,
    segment_statistic_lengths_count,
    log
  )
{
  p_logger_ = log;
  debug_logging_enabled_ = false;
  info_logging_enabled_ = false;
  error_logging_enabled_ = false;
  verbose_logging_enabled_ = false;

  logger_type_ = 0;
  resolution_mm_ = resolution_mm;
  progress_callback_ = callback;
  verbose_output_ = false;
  source_path_ = source_path;
  target_path_ = target_path;
  gcode_position_args_ = get_args_(g90_g91_influences_extruder, buffer_size);
  allow_3d_arcs_ = allow_3d_arcs;
  allow_travel_arcs_ = allow_travel_arcs;
  allow_dynamic_precision_ = allow_dynamic_precision;
  extrusion_rate_variance_percent_ = extrusion_rate_variance_percent;
  notification_period_seconds = 1;
  lines_processed_ = 0;
  gcodes_processed_ = 0;
  file_size_ = 0;
  last_gcode_line_written_ = 0;
  points_compressed_ = 0;
  arcs_created_ = 0;
  arcs_aborted_by_flow_rate_ = 0;
  waiting_for_arc_ = false;
  previous_feedrate_ = -1;
  gcode_position_args_.set_num_extruders(8);
  previous_extrusion_rate_ = 0;
  for (int index = 0; index < 8; index++)
  {
    gcode_position_args_.retraction_lengths[0] = .0001;
    gcode_position_args_.z_lift_heights[0] = 0.001;
    gcode_position_args_.x_firmware_offsets[0] = 0.0;
    gcode_position_args_.y_firmware_offsets[0] = 0.0;
  }

  // We don't care about the printer settings, except for g91 influences extruder.

  p_source_position_ = new gcode_position(gcode_position_args_);
}

gcode_position_args arc_welder::get_args_(bool g90_g91_influences_extruder, int buffer_size)
{
  gcode_position_args args;
  // Configure gcode_position_args
  args.g90_influences_extruder = g90_g91_influences_extruder;
  if (buffer_size < 2)
  {
    buffer_size = 2;
  }
  args.position_buffer_size = buffer_size;
  args.autodetect_position = true;
  args.home_x = 0;
  args.home_x_none = true;
  args.home_y = 0;
  args.home_y_none = true;
  args.home_z = 0;
  args.home_z_none = true;
  args.shared_extruder = true;
  args.zero_based_extruder = true;


  args.default_extruder = 0;
  args.xyz_axis_default_mode = "absolute";
  args.e_axis_default_mode = "absolute";
  args.units_default = "millimeters";
  args.location_detection_commands = std::vector<std::string>();
  args.is_bound_ = false;
  args.is_circular_bed = false;
  args.x_min = -9999;
  args.x_max = 9999;
  args.y_min = -9999;
  args.y_max = 9999;
  args.z_min = -9999;
  args.z_max = 9999;
  return args;
}

arc_welder::~arc_welder()
{
  delete p_source_position_;
}

void arc_welder::set_logger_type(int logger_type)
{
  logger_type_ = logger_type;
}

void arc_welder::reset()
{
  p_logger_->log(logger_type_, DEBUG, "Resetting all tracking variables.");
  lines_processed_ = 0;
  gcodes_processed_ = 0;
  last_gcode_line_written_ = 0;
  file_size_ = 0;
  points_compressed_ = 0;
  arcs_created_ = 0;
  waiting_for_arc_ = false;
}

long arc_welder::get_file_size(const std::string& file_path)
{
  // Todo:  Fix this function.  This is a pretty weak implementation :(
  std::ifstream file(file_path.c_str(), std::ios::in | std::ios::binary);
  const long l = (long)file.tellg();
  file.seekg(0, std::ios::end);
  const long m = (long)file.tellg();
  file.close();
  return (m - l);
}

double arc_welder::get_next_update_time() const
{
  return clock() + (notification_period_seconds * CLOCKS_PER_SEC);
}

double arc_welder::get_time_elapsed(double start_clock, double end_clock)
{
  return static_cast<double>(end_clock - start_clock) / CLOCKS_PER_SEC;
}

arc_welder_results arc_welder::process()
{
  arc_welder_results results;
  p_logger_->log(logger_type_, DEBUG, "Configuring logging settings.");
  verbose_logging_enabled_ = p_logger_->is_log_level_enabled(logger_type_, VERBOSE);
  debug_logging_enabled_ = p_logger_->is_log_level_enabled(logger_type_, DEBUG);
  info_logging_enabled_ = p_logger_->is_log_level_enabled(logger_type_, INFO);
  error_logging_enabled_ = p_logger_->is_log_level_enabled(logger_type_, ERROR);

  std::stringstream stream;
  // reset tracking variables
  reset();
  // local variable to hold the progress update return.  If it's false, we will exit.
  bool continue_processing = true;

  p_logger_->log(logger_type_, DEBUG, "Configuring progress updates.");
  int read_lines_before_clock_check = 1000;
  double next_update_time = get_next_update_time();
  const clock_t start_clock = clock();
  p_logger_->log(logger_type_, DEBUG, "Getting source file size.");
  file_size_ = get_file_size(source_path_);
  stream.clear();
  stream.str("");
  stream << "Source file size: " << file_size_;
  p_logger_->log(logger_type_, DEBUG, stream.str());

  // Determine if we need to overwrite the source file
  bool overwrite_source_file = false;
  std::string temp_file_path;
  if (source_path_ == target_path_)
  {
    overwrite_source_file = true;
    if (!utilities::get_temp_file_path_for_file(source_path_, temp_file_path))
    {
      results.success = false;
      results.message = "The source and target path are the same, but a temporary file path could not be created.  Are the paths empty?";
      p_logger_->log_exception(logger_type_, results.message);
      return results;
    }

    stream.clear();
    stream.str("");
    stream << "Source and target path are the same.  The source file will be overwritten.  Temporary file path: " << temp_file_path;
    p_logger_->log(logger_type_, DEBUG, stream.str());
    target_path_ = temp_file_path;
  }

  // Create the source file read stream and target write stream
  std::ifstream gcodeFile;
  p_logger_->log(logger_type_, DEBUG, "Opening the source file for reading.");
  gcodeFile.open(source_path_.c_str(), std::ifstream::in);
  if (!gcodeFile.is_open())
  {
    results.success = false;
    results.message = "Unable to open the source file.";
    p_logger_->log_exception(logger_type_, results.message);
    return results;
  }
  p_logger_->log(logger_type_, DEBUG, "Source file opened successfully.");

  p_logger_->log(logger_type_, DEBUG, "Opening the target file for writing.");

  output_file_.open(target_path_.c_str(), std::ios_base::binary | std::ios_base::out);
  if (!output_file_.is_open())
  {
    results.success = false;
    results.message = "Unable to open the target file.";
    p_logger_->log_exception(logger_type_, results.message);
    gcodeFile.close();
    return results;
  }

  p_logger_->log(logger_type_, DEBUG, "Target file opened successfully.");
  std::string line;
  int lines_with_no_commands = 0;
  parsed_command cmd;
  // Communicate every second
  p_logger_->log(logger_type_, DEBUG, "Sending initial progress update.");
  continue_processing = on_progress_(get_progress_(static_cast<long>(gcodeFile.tellg()), static_cast<double>(start_clock)));
  p_logger_->log(logger_type_, DEBUG, "Processing source file.");

  bool arc_Welder_comment_added = false;
  while (std::getline(gcodeFile, line) && continue_processing)
  {
    lines_processed_++;
    // Check the first line of gcode and see if it = ;FLAVOR:UltiGCode
// This comment MUST be preserved as the first line for ultimakers, else things won't work
    if (lines_processed_ == 1)
    {
      bool isUltiGCode = line == ";FLAVOR:UltiGCode";
      bool isPrusaSlicer = line.rfind("; generated by PrusaSlicer", 0) == 0;
      if (isUltiGCode || isPrusaSlicer)
      {
        write_gcode_to_file(line);
      }
      add_arcwelder_comment_to_target();
      if (isUltiGCode || isPrusaSlicer)
      {
        lines_with_no_commands++;
        continue;
      }
    }


    cmd.clear();
    if (verbose_logging_enabled_)
    {
      stream.clear();
      stream.str("");
      stream << "Parsing: " << line;
      p_logger_->log(logger_type_, VERBOSE, stream.str());
    }
    parser_.try_parse_gcode(line.c_str(), cmd, true);
    bool has_gcode = false;
    if (cmd.gcode.length() > 0)
    {
      has_gcode = true;
      gcodes_processed_++;
    }
    else
    {
      lines_with_no_commands++;
    }

    // Always process the command through the printer, even if no command is found
    // This is important so that comments can be analyzed
    //std::cout << "stabilization::process_file - updating position...";
    process_gcode(cmd, false, false);

    // Only continue to process if we've found a command and either a progress_callback_ is supplied, or debug loggin is enabled.
    if (has_gcode)
    {
      if ((lines_processed_ % read_lines_before_clock_check) == 0 && next_update_time < clock())
      {
        if (verbose_logging_enabled_)
        {
          p_logger_->log(logger_type_, VERBOSE, "Sending progress update.");
        }
        continue_processing = on_progress_(get_progress_(static_cast<long>(gcodeFile.tellg()), static_cast<double>(start_clock)));
        next_update_time = get_next_update_time();
      }
    }
  }

  if (current_arc_.is_shape() && waiting_for_arc_)
  {
    p_logger_->log(logger_type_, DEBUG, "Processing the final line.");
    process_gcode(cmd, true, false);
  }
  p_logger_->log(logger_type_, DEBUG, "Writing all unwritten gcodes to the target file.");
  write_unwritten_gcodes_to_file();

  p_logger_->log(logger_type_, DEBUG, "Fetching the final progress struct.");

  arc_welder_progress final_progress = get_progress_(static_cast<long>(file_size_), static_cast<double>(start_clock));
  if (debug_logging_enabled_)
  {
    p_logger_->log(logger_type_, DEBUG, "Sending final progress update message.");
  }
  on_progress_(final_progress);

  p_logger_->log(logger_type_, DEBUG, "Closing source and target files.");
  output_file_.close();
  gcodeFile.close();

  if (overwrite_source_file)
  {
    stream.clear();
    stream.str("");
    stream << "Deleting the original source file at '" << source_path_ << "'.";
    p_logger_->log(logger_type_, DEBUG, stream.str());
    stream.clear();
    stream.str("");
    std::remove(source_path_.c_str());
    stream << "Renaming temporary file at '" << target_path_ << "' to '" << source_path_ << "'.";
    p_logger_->log(0, DEBUG, stream.str());
    std::rename(target_path_.c_str(), source_path_.c_str());
  }

  results.success = continue_processing;
  results.cancelled = !continue_processing;
  results.progress = final_progress;
  p_logger_->log(logger_type_, DEBUG, "Returning processing results.");

  return results;
}

bool arc_welder::on_progress_(const arc_welder_progress& progress)
{
  if (progress_callback_ != NULL)
  {
    return progress_callback_(progress, p_logger_, logger_type_);
  }
  else if (info_logging_enabled_)
  {
    p_logger_->log(logger_type_, INFO, progress.str());
  }

  return true;
}

arc_welder_progress arc_welder::get_progress_(long source_file_position, double start_clock)
{
  arc_welder_progress progress;
  progress.gcodes_processed = gcodes_processed_;
  progress.lines_processed = lines_processed_;
  progress.points_compressed = points_compressed_;
  progress.arcs_created = arcs_created_;
  progress.arcs_aborted_by_flow_rate = arcs_aborted_by_flow_rate_;
  progress.source_file_position = source_file_position;
  progress.target_file_size = static_cast<long>(output_file_.tellp());
  progress.source_file_size = file_size_;
  long bytesRemaining = file_size_ - static_cast<long>(source_file_position);
  progress.percent_complete = static_cast<double>(source_file_position) / static_cast<double>(file_size_) * 100.0;
  progress.seconds_elapsed = get_time_elapsed(start_clock, clock());
  double bytesPerSecond = static_cast<double>(source_file_position) / progress.seconds_elapsed;
  progress.seconds_remaining = bytesRemaining / bytesPerSecond;
  
  if (source_file_position > 0) {
    progress.compression_ratio = (static_cast<float>(source_file_position) / static_cast<float>(progress.target_file_size));
    progress.compression_percent = (1.0 - (static_cast<float>(progress.target_file_size) / static_cast<float>(source_file_position))) * 100.0f;
  }
  else {
    progress.compression_ratio = 0;
    progress.compression_percent = 0;
  }
  progress.num_firmware_compensations = current_arc_.get_num_firmware_compensations();
  progress.num_gcode_length_exceptions = current_arc_.get_num_gcode_length_exceptions();
  progress.segment_statistics = segment_statistics_;
  progress.travel_statistics = travel_statistics_;
  return progress;

}

int arc_welder::process_gcode(parsed_command cmd, bool is_end, bool is_reprocess)
{
  /* use to catch gcode for debugging since I can't set conditions equal to strings
  if (cmd.gcode == "G1 X118.762 Y104.054 E0.0163")
  {
    std::cout << "Found it!";
  }
  */
  // Update the position for the source gcode file
  p_source_position_->update(cmd, lines_processed_, gcodes_processed_, -1);
  position* p_cur_pos = p_source_position_->get_current_position_ptr();
  position* p_pre_pos = p_source_position_->get_previous_position_ptr();
  bool is_previous_extruder_relative = p_pre_pos->is_extruder_relative;
  extruder extruder_current = p_cur_pos->get_current_extruder();
  extruder previous_extruder = p_pre_pos->get_current_extruder();

  // Determine if this is a G0, G1, G2 or G3
  bool is_g0_g1 = cmd.command == "G0" || cmd.command == "G1";
  bool is_g2_g3 = cmd.command == "G2" || cmd.command == "G3";
  //std::cout << lines_processed_ << " - " << cmd.gcode << ", CurrentEAbsolute: " << cur_extruder.e <<", ExtrusionLength: " << cur_extruder.extrusion_length << ", Retraction Length: " << cur_extruder.retraction_length << ", IsExtruding: " << cur_extruder.is_extruding << ", IsRetracting: " << cur_extruder.is_retracting << ".\n";

  int lines_written = 0;
  // see if this point is an extrusion

  bool arc_added = false;
  bool clear_shapes = false;
  double movement_length_mm = 0;
  bool has_e_changed = extruder_current.e_relative != 0;
  // Update the source file statistics
  if (p_cur_pos->has_xy_position_changed)
  {
    // If this is a g2/g3 command, we need to do a bit more to get the length of the arc.
      // The movement_length_mm variable will contain the chord length, which we will need
    if (is_g2_g3)
    {
      // Determine the radius of the arc, which is necessary to calculate the arc length from the chord length.
      double i = 0;
      double j = 0;
      double r = 0;
      // Iterate through the parameters and fill in I, J and R;
      for (std::vector<parsed_command_parameter>::iterator it = cmd.parameters.begin(); it != cmd.parameters.end(); ++it)
      {
        switch ((*it).name[0])
        {
        case 'I':
          i = (*it).double_precision;
          break;
        case 'J':
          j = (*it).double_precision;
          break;
          // Note that the R form isn't fully implemented!
        case 'R':
          r = (*it).double_precision;
          break;
        }
      }

      // Calculate R
      if (r == 0)
      {
        r = std::sqrt(i * i + j * j);
      }
      // Now we know the radius and the chord length;
      movement_length_mm = utilities::get_arc_distance(p_pre_pos->x, p_pre_pos->y, p_pre_pos->z, p_cur_pos->x, p_cur_pos->y, p_cur_pos->z, i, j, r, p_cur_pos->command.command == "G2");

    }
    else if (allow_3d_arcs_) {
      movement_length_mm = utilities::get_cartesian_distance(p_pre_pos->x, p_pre_pos->y, p_pre_pos->z, p_cur_pos->x, p_cur_pos->y, p_cur_pos->z);
    }
    else {
      movement_length_mm = utilities::get_cartesian_distance(p_pre_pos->x, p_pre_pos->y, p_cur_pos->x, p_cur_pos->y);
    }

    if (movement_length_mm > 0)
    {
      if (!is_reprocess)
      {
        if (has_e_changed)
        {
          segment_statistics_.update(movement_length_mm, true);
        }
        else if (allow_travel_arcs_)
        {
          travel_statistics_.update(movement_length_mm, true);
        }

      }
    }
  }

  // calculate the extrusion rate (mm/mm) and see how much it changes
  double mm_extruded_per_mm_travel = 0;
  double extrusion_rate_change_percent = 0;
  bool aborted_by_flow_rate = false;
  // TODO:  MAKE SURE THIS WORKS FOR TRANSITIONS FROM TRAVEL TO NON TRAVEL MOVES
  if (movement_length_mm > 0 && has_e_changed)
  {
    mm_extruded_per_mm_travel = extruder_current.e_relative / movement_length_mm;
    if (previous_extrusion_rate_ > 0)
    {
      extrusion_rate_change_percent = std::fabs(utilities::get_percent_change(previous_extrusion_rate_, mm_extruded_per_mm_travel));
    }
  }
  if (previous_extrusion_rate_ != 0 && utilities::greater_than(extrusion_rate_change_percent, extrusion_rate_variance_percent_))
  {
    arcs_aborted_by_flow_rate_++;
    aborted_by_flow_rate = true;
  }

  // We need to make sure the printer is using absolute xyz, is extruding, and the extruder axis mode is the same as that of the previous position
  // TODO: Handle relative XYZ axis.  This is possible, but maybe not so important.
  
  if (allow_dynamic_precision_ && is_g0_g1)
  {
    for (std::vector<parsed_command_parameter>::iterator it = cmd.parameters.begin(); it != cmd.parameters.end(); ++it)
    {
      switch ((*it).name[0])
      {
      case 'X':
      case 'Y':
      case 'Z':
        current_arc_.update_xyz_precision((*it).double_precision);
        break;
      case 'E':
        current_arc_.update_e_precision((*it).double_precision);
        break;
      }
    }
  }

  bool z_axis_ok = allow_3d_arcs_ ||
    utilities::is_equal(p_cur_pos->z, p_pre_pos->z);

  if (
    !is_end && cmd.is_known_command && !cmd.is_empty && (
      is_g0_g1 && z_axis_ok &&
      utilities::is_equal(p_cur_pos->x_offset, p_pre_pos->x_offset) &&
      utilities::is_equal(p_cur_pos->y_offset, p_pre_pos->y_offset) &&
      utilities::is_equal(p_cur_pos->z_offset, p_pre_pos->z_offset) &&
      utilities::is_equal(p_cur_pos->x_firmware_offset, p_pre_pos->x_firmware_offset) &&
      utilities::is_equal(p_cur_pos->y_firmware_offset, p_pre_pos->y_firmware_offset) &&
      utilities::is_equal(p_cur_pos->z_firmware_offset, p_pre_pos->z_firmware_offset) &&
      (previous_extrusion_rate_ == 0 || utilities::less_than_or_equal(extrusion_rate_change_percent, extrusion_rate_variance_percent_)) &&
      !p_cur_pos->is_relative &&
      (
        !waiting_for_arc_ ||
        extruder_current.is_extruding ||
        // Test for travel conversion
        (allow_travel_arcs_ && p_cur_pos->is_travel()) ||
        //(previous_extruder.is_extruding && extruder_current.is_extruding) || // Test to see if 
        // we can get more arcs.
        (previous_extruder.is_retracting && extruder_current.is_retracting)
        ) &&
      p_cur_pos->is_extruder_relative == is_previous_extruder_relative &&
      (!waiting_for_arc_ || p_pre_pos->f == p_cur_pos->f) && // might need to skip the waiting for arc check...
      (!waiting_for_arc_ || p_pre_pos->feature_type_tag == p_cur_pos->feature_type_tag)
      )
    ) {

    // Record the extrusion rate
    previous_extrusion_rate_ = mm_extruded_per_mm_travel;
    printer_point p(p_cur_pos->get_gcode_x(), p_cur_pos->get_gcode_y(), p_cur_pos->get_gcode_z(), extruder_current.get_offset_e(), extruder_current.e_relative, p_cur_pos->f, movement_length_mm, p_pre_pos->is_extruder_relative);
    if (!waiting_for_arc_)
    {
      if (debug_logging_enabled_)
      {
        p_logger_->log(logger_type_, DEBUG, "Starting new arc from Gcode:" + cmd.gcode);
      }
      write_unwritten_gcodes_to_file();
      // add the previous point as the starting point for the current arc
      printer_point previous_p(p_pre_pos->get_gcode_x(), p_pre_pos->get_gcode_y(), p_pre_pos->get_gcode_z(), previous_extruder.get_offset_e(), previous_extruder.e_relative, p_pre_pos->f, 0, p_pre_pos->is_extruder_relative);
      // Don't add any extrusion, or you will over extrude!
      //std::cout << "Trying to add first point (" << p.x << "," << p.y << "," << p.z << ")...";

      current_arc_.try_add_point(previous_p);
    }

    double e_relative = extruder_current.e_relative;
    int num_points = current_arc_.get_num_segments();
    arc_added = current_arc_.try_add_point(p);
    if (arc_added)
    {
      // Make sure our position list is large enough to handle all the segments
      if (current_arc_.get_num_segments() + 2 > p_source_position_->get_max_positions())
      {
        p_source_position_->grow_max_positions(p_source_position_->get_max_positions() * 2);
      }
      if (!waiting_for_arc_)
      {
        waiting_for_arc_ = true;
        previous_feedrate_ = p_pre_pos->f;
      }
      else
      {
        if (debug_logging_enabled_)
        {
          if (num_points + 1 == current_arc_.get_num_segments())
          {
            p_logger_->log(logger_type_, DEBUG, "Adding point to arc from Gcode:" + cmd.gcode);
          }

        }
      }
    }
  }
  else {

    if (debug_logging_enabled_) {
      if (is_end)
      {
        p_logger_->log(logger_type_, DEBUG, "Procesing final shape, if one exists.");
      }
      else if (!cmd.is_empty)
      {
        if (!cmd.is_known_command)
        {
          p_logger_->log(logger_type_, DEBUG, "Command '" + cmd.command + "' is Unknown.  Gcode:" + cmd.gcode);
        }
        else if (cmd.command != "G0" && cmd.command != "G1")
        {
          p_logger_->log(logger_type_, DEBUG, "Command '" + cmd.command + "' is not G0/G1, skipping.  Gcode:" + cmd.gcode);
        }
        else if (!allow_3d_arcs_ && !utilities::is_equal(p_cur_pos->z, p_pre_pos->z))
        {
          p_logger_->log(logger_type_, DEBUG, "Z axis position changed, cannot convert:" + cmd.gcode);
        }
        else if (p_cur_pos->is_relative)
        {
          p_logger_->log(logger_type_, DEBUG, "XYZ Axis is in relative mode, cannot convert:" + cmd.gcode);
        }
        else if (
          waiting_for_arc_ && !(
            (previous_extruder.is_extruding && extruder_current.is_extruding) ||
            (previous_extruder.is_retracting && extruder_current.is_retracting)
            )
          )
        {
          std::string message = "Extruding or retracting state changed, cannot add point to current arc: " + cmd.gcode;
          if (verbose_logging_enabled_)
          {

            message.append(
              " - Verbose Info\n\tCurrent Position Info - Absolute E:" + utilities::to_string(extruder_current.e) +
              ", Offset E:" + utilities::to_string(extruder_current.get_offset_e()) +
              ", Mode:" + (p_cur_pos->is_extruder_relative_null ? "NULL" : p_cur_pos->is_extruder_relative ? "relative" : "absolute") +
              ", Retraction: " + utilities::to_string(extruder_current.retraction_length) +
              ", Extrusion: " + utilities::to_string(extruder_current.extrusion_length) +
              ", Retracting: " + (extruder_current.is_retracting ? "True" : "False") +
              ", Extruding: " + (extruder_current.is_extruding ? "True" : "False")
            );
            message.append(
              "\n\tPrevious Position Info - Absolute E:" + utilities::to_string(previous_extruder.e) +
              ", Offset E:" + utilities::to_string(previous_extruder.get_offset_e()) +
              ", Mode:" + (p_pre_pos->is_extruder_relative_null ? "NULL" : p_pre_pos->is_extruder_relative ? "relative" : "absolute") +
              ", Retraction: " + utilities::to_string(previous_extruder.retraction_length) +
              ", Extrusion: " + utilities::to_string(previous_extruder.extrusion_length) +
              ", Retracting: " + (previous_extruder.is_retracting ? "True" : "False") +
              ", Extruding: " + (previous_extruder.is_extruding ? "True" : "False")
            );
            p_logger_->log(logger_type_, VERBOSE, message);
          }
          else
          {
            p_logger_->log(logger_type_, DEBUG, message);
          }

        }
        else if (p_cur_pos->is_extruder_relative != p_pre_pos->is_extruder_relative)
        {
          p_logger_->log(logger_type_, DEBUG, "Extruder axis mode changed, cannot add point to current arc: " + cmd.gcode);
        }
        else if (waiting_for_arc_ && p_pre_pos->f != p_cur_pos->f)
        {
          p_logger_->log(logger_type_, DEBUG, "Feedrate changed, cannot add point to current arc: " + cmd.gcode);
        }
        else if (waiting_for_arc_ && p_pre_pos->feature_type_tag != p_cur_pos->feature_type_tag)
        {
          p_logger_->log(logger_type_, DEBUG, "Feature type changed, cannot add point to current arc: " + cmd.gcode);
        }
        else if (aborted_by_flow_rate)
        {
          std::stringstream stream;
          stream << std::fixed << std::setprecision(5);
          stream << "Arc Canceled - The extrusion rate variance of " << extrusion_rate_variance_percent_ << "% exceeded by " << extrusion_rate_change_percent - extrusion_rate_variance_percent_ << "% on line " << lines_processed_ << ".  Extruded " << extruder_current.e_relative << "mm over " << movement_length_mm << "mm of travel (" << mm_extruded_per_mm_travel << "mm/mm).  Previous rate: " << previous_extrusion_rate_ << "mm/mm.";
          p_logger_->log(logger_type_, DEBUG, stream.str());
        }
        else
        {
          // Todo:  Add all the relevant values
          p_logger_->log(logger_type_, DEBUG, "There was an unknown issue preventing the current point from being added to the arc: " + cmd.gcode);
        }
      }
    }

    // Reset the previous extrusion rate
    previous_extrusion_rate_ = 0;
  }

  if (!arc_added && !(cmd.is_empty && cmd.comment.length() == 0))
  {
    if (current_arc_.get_num_segments() < current_arc_.get_min_segments()) {
      if (debug_logging_enabled_ && !cmd.is_empty)
      {
        if (current_arc_.get_num_segments() != 0)
        {
          p_logger_->log(logger_type_, DEBUG, "Not enough segments, resetting. Gcode:" + cmd.gcode);
        }

      }
      waiting_for_arc_ = false;
      current_arc_.clear();
    }
    else if (waiting_for_arc_)
    {

      if (current_arc_.is_shape())
      {
        // update our statistics
        points_compressed_ += current_arc_.get_num_segments() - 1;
        arcs_created_++; // increment the number of generated arcs
        write_arc_gcodes(p_pre_pos->f);
        // Now clear the arc and flag the processor as not waiting for an arc
        waiting_for_arc_ = false;
        current_arc_.clear();
        p_cur_pos = NULL;
        p_pre_pos = NULL;

        // Reprocess this line
        if (!is_end)
        {
          return process_gcode(cmd, false, true);
        }
        else
        {
          if (debug_logging_enabled_)
          {
            p_logger_->log(logger_type_, DEBUG, "Final arc created, exiting.");
          }
          return 0;
        }

      }
      else
      {
        if (debug_logging_enabled_)
        {
          p_logger_->log(logger_type_, DEBUG, "The current arc is not a valid arc, resetting.");
        }
        current_arc_.clear();
        waiting_for_arc_ = false;
      }
    }
    else if (debug_logging_enabled_)
    {
      p_logger_->log(logger_type_, DEBUG, "Could not add point to arc from gcode:" + cmd.gcode);
    }

  }

  if (waiting_for_arc_ || !arc_added)
  {
    // This might not work....
    //position* cur_pos = p_source_position_->get_current_position_ptr();

    unwritten_commands_.push_back(unwritten_command(cmd, is_previous_extruder_relative, !has_e_changed && (is_g0_g1 || is_g2_g3), movement_length_mm));

  }
  else if (!waiting_for_arc_)
  {
    write_unwritten_gcodes_to_file();
    current_arc_.clear();
  }
  return lines_written;
}

void arc_welder::write_arc_gcodes(double current_feedrate)
{

  std::string comment = get_comment_for_arc();
  // remove the same number of unwritten gcodes as there are arc segments, minus 1 for the start point
  // Which isn't a movement
  // note, skip the first point, it is the starting point
  int num_segments = current_arc_.get_num_segments() - 1;
  for (int index = 0; index < num_segments; index++)
  {
    while (!unwritten_commands_.pop_back().is_g0_g1);
  }

  // Undo the current command, since it isn't included in the arc
  p_source_position_->undo_update();

  // Set the current feedrate if it is different, else set to 0 to indicate that no feedrate should be included
  if (previous_feedrate_ > 0 && previous_feedrate_ == current_feedrate) {
    current_feedrate = 0;
  }

  // Craete the arc gcode
  std::string gcode = get_arc_gcode(comment);

  if (debug_logging_enabled_)
  {
    char buffer[20];
    std::string message = "Arc created with ";
    sprintf(buffer, "%d", current_arc_.get_num_segments());
    message += buffer;
    message += " segments: ";
    message += gcode;
    p_logger_->log(logger_type_, DEBUG, message);
  }

  // Write everything that hasn't yet been written	
  write_unwritten_gcodes_to_file();

  // Update the current extrusion statistics for the current arc gcode
  if (current_arc_.get_shape_e_relative() != 0)
  {
    segment_statistics_.update(current_arc_.get_shape_length(), false);

  }
  else if (allow_travel_arcs_) {
    travel_statistics_.update(current_arc_.get_shape_length(), false);
  }
  // now write the current arc to the file 
  write_gcode_to_file(gcode);
}

std::string arc_welder::get_comment_for_arc()
{
  // build a comment string from the commands making up the arc
        // We need to start with the first command entered.
  int comment_index = unwritten_commands_.count() - (current_arc_.get_num_segments() - 1);
  std::string comment;
  for (; comment_index < unwritten_commands_.count(); comment_index++)
  {
    std::string old_comment = unwritten_commands_[comment_index].comment;
    if (old_comment != comment && old_comment.length() > 0)
    {
      if (comment.length() > 0)
      {
        comment += " - ";
      }
      comment += old_comment;
    }
  }
  return comment;
}

std::string arc_welder::create_g92_e(double absolute_e)
{
  std::stringstream stream;
  stream << std::fixed << std::setprecision(5);
  stream << "G92 E" << absolute_e;
  return stream.str();
}

int arc_welder::write_gcode_to_file(std::string gcode)
{
  output_file_ << gcode << "\n";
  return 1;
}

int arc_welder::write_unwritten_gcodes_to_file()
{
  int size = unwritten_commands_.count();
  std::string lines_to_write;

  for (int index = 0; index < size; index++)
  {
    // The the current unwritten position and remove it from the list
    unwritten_command p = unwritten_commands_.pop_front();
    if ((p.is_g0_g1 || p.is_g2_g3) && p.length > 0)
    {
      if (!p.is_travel)
      {
        segment_statistics_.update(p.length, false);
      }
      else if (allow_travel_arcs_) {
        travel_statistics_.update(p.length, false);
      }
    }
    lines_to_write.append(p.to_string()).append("\n");
  }

  output_file_ << lines_to_write;
  return size;
}

std::string arc_welder::get_arc_gcode(const std::string comment)
{
  // Write gcode to file
  std::string gcode;

  gcode = current_arc_.get_shape_gcode();

  if (comment.length() > 0)
  {
    gcode += ";" + comment;
  }
  return gcode;

}

void arc_welder::add_arcwelder_comment_to_target()
{
  p_logger_->log(logger_type_, DEBUG, "Adding ArcWelder comment to the target file.");
  std::stringstream stream;
  stream << std::fixed;
  stream << "; Postprocessed by [ArcWelder](https://github.com/FormerLurker/ArcWelderLib)\n";
  stream << "; Copyright(C) 2020 - Brad Hochgesang\n";
  stream << "; Version: " << GIT_TAGGED_VERSION << ", Branch: " << GIT_BRANCH << ", BuildDate: " << BUILD_DATE << "\n";
  stream << "; resolution=" << std::setprecision(2) << resolution_mm_ << "mm\n";
  stream << "; path_tolerance=" << std::setprecision(1) << (current_arc_.get_path_tolerance_percent() * 100.0) << "%\n";
  stream << "; max_radius=" << std::setprecision(2) << (current_arc_.get_max_radius()) << "mm\n";
  if (gcode_position_args_.g90_influences_extruder)
  {
    stream << "; g90_influences_extruder=True\n";
  }
  if (current_arc_.get_mm_per_arc_segment() > 0 && current_arc_.get_min_arc_segments() > 0)
  {
    stream << "; firmware_compensation=True\n";
    stream << "; mm_per_arc_segment=" << std::setprecision(2) << current_arc_.get_mm_per_arc_segment() << "mm\n";
    stream << "; min_arc_segments=" << std::setprecision(0) << current_arc_.get_min_arc_segments() << "\n";
  }
  if (allow_3d_arcs_)
  {
    stream << "; allow_3d_arcs=True\n";

  }
  if (allow_dynamic_precision_)
  {
    stream << "; allow_dynamic_precision=True\n";
  }
  stream << "; default_xyz_precision=" << std::setprecision(0) << static_cast<int>(current_arc_.get_xyz_precision()) << "\n";
  stream << "; default_e_precision=" << std::setprecision(0) << static_cast<int>(current_arc_.get_e_precision()) << "\n";
  stream << "; extrusion_rate_variance_percent=" << std::setprecision(1) << (extrusion_rate_variance_percent_ * 100.0) << "%\n\n";


  output_file_ << stream.str();
}