Root/fab/gmerge

1#!/usr/bin/perl
2#
3# gmerge - Merge multiple KiCAD Gerber files into one
4#
5# Written 2011, 2016 by Werner Almesberger
6# Copyright 2011, 2016 Werner Almesberger
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13
14
15$state = "HDR";
16
17LINE: while (<>) {
18    if ($state eq "HDR") {
19        if (/^G04 APERTURE LIST/) {
20            $state = "APT";
21            next;
22        }
23        $hdr .= $_;
24        $phdr .= $_ unless /^G04/;
25        next;
26    }
27    if ($state eq "APT") {
28        if (/^G04 APERTURE END LIST/) {
29            $state = "CMD";
30            next;
31        }
32        die "unrecognized aperture"
33            unless /^%ADD(\d+)([CRO],(\d|\.)+(X(\d|\.)+)?)\*%/;
34        for (keys %apt) {
35            if ($apt{$_} == $2) {
36                $map{$1} = $_;
37                next LINE;
38            }
39        }
40        for ($t = $1; defined $apt{$t}; $t++) {}
41        $apt{$t} = $2;
42        $map{$1} = $t;
43        next;
44    }
45    die "internal error" unless $state eq "CMD";
46    if (/^M02\*/) {
47        $state = "HDR";
48        if (defined $ghdr) {
49            if ($gphdr ne $phdr) {
50                print STDERR "--- first header ---\n", $gphdr;
51                print STDERR "--- current header ---\n", $phdr;
52                die "incompatible headers";
53            }
54            
55        } else {
56            $ghdr = $hdr;
57            $gphdr = $phdr;
58        }
59        undef $hdr;
60        undef $phdr;
61        next;
62    }
63    if (/^G54D(\d+)\*/) {
64        die "undeclared aperture" unless defined $map{$1};
65        $c .= "G54D".$map{$1}."*\n";
66        next;
67    }
68    die "unexpected command \"$_\"" unless /^X-?\d+Y-?\d+D0*[12]\*/;
69    $c .= $_;
70}
71
72print $ghdr || die $!;
73print "G04 APERTURE LIST*\n" || die $!;
74for (sort keys %apt) {
75    print "\%ADD".$_.$apt{$_}."*%\n" || die $!;
76}
77print "G04 APERTURE END LIST*\n" || die $!;
78print $c || die $!;
79print "M02*\n" || die $!;
80

Archive Download this file

Branches:
master



interactive