Gera cabeçalhos para versão 2017.
[cascardo/declara.git] / lib / gera.c
1 /*
2  *  Copyright (C) 2015-2017  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include "gera.h"
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <zlib.h>
25 #include "declaracao.h"
26 #include "cmd.h"
27 #include "rendimento.h"
28 #include "isento.h"
29 #include "pagamento.h"
30 #include "bem.h"
31 #include "dependente.h"
32 #include "totais.h"
33 #include "sistema.h"
34 #include "ano.h"
35
36 static void gera_header(struct declaracao *dec, FILE *f)
37 {
38         int i;
39
40         fprintf(f, "IRPF    ");
41         fprintf(f, "%04d", dec->ano); /* Exercício */
42         fprintf(f, "%04d", dec->ano - 1); /* Ano base */
43         if (dec->ano == 2015)
44                 fprintf(f, "2500"); /* Código */
45         else if (dec->ano == 2016)
46                 fprintf(f, "2600"); /* Código */
47         else if (dec->ano == 2017)
48                 fprintf(f, "2700"); /* Código */
49         fprintf(f, "%s", dec->retifica ? "1" : "0"); /* Retificadora */
50         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
51         fprintf(f, "   "); /* Filler */
52         fprintf(f, "1"); /* Tipo NI: Pessoa Física (1) */
53         if (dec->ano == 2015)
54                 fprintf(f, "130"); /* Versão IRPF */
55         else if (dec->ano == 2016)
56                 fprintf(f, "110"); /* Versão IRPF */
57         else if (dec->ano == 2017)
58                 fprintf(f, "100"); /* Versão IRPF */
59         fprintf(f, "%-60.60s", dec->nome);
60         fprintf(f, "%-2.2s", dec->contribuinte.uf ?: "");
61         fprintf(f, "%s", "0000000000"); /* FIXME: hash */
62         fprintf(f, "1"); /* TODO: certificavel */
63         fprintf(f, "%-8.8s", dec->contribuinte.dn ?: "");
64         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
65         /* TODO: resultado imposto, 1 - pagar, 2 - restituicao */
66         fprintf(f, "%s", dec->restituicao ? "2" : (dec->pagar ? "1" : "0"));
67         fprintf(f, "S"); /* TODO: gerada? */
68         fprintf(f, "%-10.10s", dec->retifica ?: ""); /* recibo retificada ex. atual */
69         fprintf(f, "2"); /* TODO: PGD */
70         fprintf(f, "%-14.14s", sistema_get_so(dec));
71         fprintf(f, "%-7.7s", sistema_get_so_versao(dec));
72         fprintf(f, "%-9.9s", sistema_get_jvm_versao(dec));
73         fprintf(f, "%-10.10s", ""); /* TODO: última declaração transmitida (pode ser vazio?) */
74         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
75         fprintf(f, "%-11.11s", dec->conjuge.cpf ? : ""); /* TODO: CPF conjuge */
76         fprintf(f, "%d", dec->obrigatoria ? 1 : 0); /* obrigatoria entrega */
77         fprintf(f, "%013lld", dec->devido); /* imposto devido, carne-leao, complementar dos dependentes */
78         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* recibo ex. anterior */
79         /* Indicador de segurança: 0 se retificadora, 2 se recibo
80          * anterior, se não 1. */
81         fprintf(f, "%d", dec->retifica ? 0 : (dec->recibo ? 2 : 1));
82         /* Indicador imposto pago, TODO: carnê leão e Lei 11.033. */
83         fprintf(f, "%02d", dec->retido ? 1 : 0);
84         /* Indicador imposto antecipado, TODO: carnê leão, Lei 11.033,
85          * outros. */
86         fprintf(f, "%d", dec->retido ? 1 : 0);
87         fprintf(f, "0"); /* TODO: mudanca endereco */
88         fprintf(f, "%-8.8s", dec->contribuinte.cep ?: "");
89         fprintf(f, "0"); /* TODO: debito 1a quota */
90         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* no banco */
91         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agencia */
92         fprintf(f, " "); /* TODO: filler */
93         fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
94         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
95         fprintf(f, " "); /* RRA1 */
96         fprintf(f, "%-11.11s", ""); /* CPF RRA1 */
97         fprintf(f, " "); /* RRA2 */
98         fprintf(f, "%-11.11s", ""); /* CPF RRA2 */
99         fprintf(f, " "); /* RRA3 */
100         fprintf(f, "%-11.11s", ""); /* CPF RRA3 */
101         fprintf(f, " "); /* RRA4 */
102         fprintf(f, "%-11.11s", ""); /* CPF RRA4 */
103         fprintf(f, "0000000000000"); /* TODO: Doacao ECA */
104         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
105         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* CNPJ maior 2 */
106         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* CNPJ maior 3 */
107         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* CNPJ maior 4 */
108         /* CPF e DN de dependentes 1 a 6 */
109         for (i = 1; i <= 6; i++) {
110                 struct dependente *dependente = list_get(dec->dependentes, i - 1);
111                 if (dependente && dependente->cpf && dependente->cpf[0]) {
112                         fprintf(f, "%-11.11s", dependente->cpf);
113                 } else {
114                         fprintf(f, "%-11.11s", "");
115                 }
116                 if (dependente && dependente->dn && dependente->dn[0]) {
117                         fprintf(f, "%-8.8s", dependente->dn);
118                 } else {
119                         fprintf(f, "%-8.8s", "");
120                 }
121         }
122         /* medico maior, TODO: outros códigos */
123         fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 0));
124         /* medico maior 2, TODO: outros códigos */
125         fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 1));
126         fprintf(f, "%-11.11s", ""); /* CPF pensao */
127         fprintf(f, "%-11.11s", ""); /* CPF inventariante */
128         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
129         fprintf(f, "%-60.60s", dec->nome);
130         fprintf(f, "%-11.11s", ""); /* CPF empregada */
131         fprintf(f, "%-12.12s", sistema_get_mac(dec));
132         fprintf(f, "%08d", 0); /* Data saída */
133         fprintf(f, "%-11.11s", ""); /* CPF procurador */
134         fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
135         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
136         /* CNPJ previdencia */
137         fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 0));
138         /* CNPJ previdencia 2 */
139         fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 1));
140         /* Total isentos */
141         fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
142         /* Total exclusivo */
143         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS"));
144         /* Total pagamentos */
145         fprintf(f, "%013lld", totais_get(dec, "PAGAMENTOS"));
146         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
147         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
148         fprintf(f, "0"); /* TODO: revalidar DV conta */
149
150         /* Mudanças de 2015 */
151
152         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* natureza ocupacao */
153         fprintf(f, "%-11.11s", ""); /* CPF domestica */
154         fprintf(f, "%-11.11s", ""); /* NI domestica */
155         fprintf(f, "%-11.11s", ""); /* CPF domestica 2 */
156         fprintf(f, "%-11.11s", ""); /* NI domestica 2 */
157         fprintf(f, "%-11.11s", ""); /* CPF domestica 3 */
158         fprintf(f, "%-11.11s", ""); /* NI domestica 3 */
159         fprintf(f, "1"); /* Declaracao iniciada */
160         fprintf(f, "1"); /* Utilizou PGD */
161         fprintf(f, "0"); /* Utilizou APP */
162         fprintf(f, "0"); /* Utilizou online */
163         fprintf(f, "0"); /* Utilizou rascunho */
164         fprintf(f, "0"); /* Utilizou pre preenchida */
165         fprintf(f, "0"); /* Utilizou fontes */
166         fprintf(f, "0"); /* Utilizou plano saude */
167         fprintf(f, "0"); /* Utilizou recuperar */
168         fprintf(f, "1"); /* Declaracao iniciada */
169
170         /* Fim das mudanças de 2015 */
171
172         /* Mudanças de 2016 */
173
174         if (dec->ano >= 2016) {
175                 /* CNPJ maior pagamento dedutível */
176                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 0));
177                 /* CNPJ maior pagamento dedutível */
178                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 1));
179                 /* CNPJ maior pagamento dedutível */
180                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 2));
181                 /* CNPJ maior pagamento dedutível */
182                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 3));
183                 /* CNPJ maior pagamento dedutível */
184                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 4));
185                 /* CNPJ maior pagamento dedutível */
186                 fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 5));
187                 /* TODO: CNPJ maior pagamento FUNPRESP */
188                 fprintf(f, "%-14.14s", "");
189         }
190
191         /* Fim das mudanças de 2016 */
192
193         fprintf(f, "   "); /* Teste PGD, FILLER2 */
194 }
195
196 static void gera_contribuinte(struct declaracao *dec, FILE *f)
197 {
198         fprintf(f, "16");
199         fprintf(f, "%s", dec->cpf);
200         fprintf(f, "%-60.60s", dec->nome);
201         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
202         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
203         fprintf(f, "%-6.6s", dec->contribuinte.numero);
204         fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
205         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
206         fprintf(f, "%-9.9s", dec->contribuinte.cep);
207         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
208         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
209         fprintf(f, "%-2.2s", dec->contribuinte.uf);
210         fprintf(f, "   "); /* TODO: código exterior */
211         fprintf(f, "105"); /* TODO: código país */
212         if (dec->ano == 2015) {
213                 fprintf(f, "%-100.100s", ""); /* FILLER3 */
214                 fprintf(f, "%-4.4s", ""); /* FILLER1 */
215                 fprintf(f, "%-8.8s", ""); /* FILLER2 */
216         } else if (dec->ano >= 2016) {
217                 fprintf(f, "%-90.90s", ""); /* FILLER3 */
218                 /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
219                 fprintf(f, "%-11.11s", "");
220                 /* CPF do cônjuge */
221                 fprintf(f, "%-11.11s", dec->conjuge.cpf ?: "");
222         }
223         fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
224         fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
225         fprintf(f, "%-8.8s", dec->contribuinte.dn);
226         fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor ?: "");
227         fprintf(f, "%03d", dec->contribuinte.ocupacao_principal);
228         fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao);
229         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: qnt quotas */
230         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
231         fprintf(f, "%s", dec->retifica ? "S" : "N");
232         fprintf(f, "S"); /* GERADO */
233         fprintf(f, "N"); /* TODO: mudança de endereço */
234         fprintf(f, "%-12.12s", dec->retifica ? : ""); /* Recibo declaração original */
235         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* banco */
236         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agência */
237         fprintf(f, "N"); /* TODO: deficiência */
238         fprintf(f, "0"); /* FILLER: pré-preenchida */
239         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* conta */
240         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
241         fprintf(f, "N"); /* TODO: débito automático */
242         fprintf(f, "0"); /* TODO: débito primeira quota */
243         /* CNPJ principal fonte */
244         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0));
245         fprintf(f, "%-10.10s", dec->recibo ?: ""); /* Recibo última declaração ano anterior */
246         fprintf(f, "A"); /* Declaração de Ajuste */
247         fprintf(f, "%-11.11s", ""); /* TODO: CPF procurador */
248         if (dec->ano >= 2016)
249                 fprintf(f, "%-20.20s", ""); /* TODO: registro profissional */
250         if (dec->ano >= 2017) {
251                 fprintf(f, "%-11.11s", ""); /* TODO: celular */
252                 fprintf(f, "%s", dec->conjuge.cpf ? "S" : "N");
253         }
254 }
255
256 static void gera_simples(struct declaracao *dec, FILE *f)
257 {
258         fprintf(f, "17");
259         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
260         fprintf(f, "%013lld", 0); /* TODO: carnê leão */
261         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
262         /* rendimentos isentos titular */
263         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT"));
264         /* rendimentos tributação exclusiva, exceto décimo terceiro */
265         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
266         /* 13o. */
267         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
268         fprintf(f, "%013lld", 0); /* TODO: retido na fonte (Lei 11.033) */
269         fprintf(f, "%013lld", 0); /* TODO: 13o. dependentes */
270         fprintf(f, "%013lld", 0); /* TODO: lucros dependentes */
271         /* BUG IRPF: O IRPF imprime 0 aqui mesmo com doações e poupança. */
272         /* fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); */
273         fprintf(f, "%013lld", 0); /* isentos dependentes */
274         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* exclusivos dependentes */
275         fprintf(f, "%-13.13s", ""); /* FILLER */
276         fprintf(f, "%-13.13s", ""); /* FILLER */
277         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF */
278         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependentes */
279         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior */
280         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF ext. depend. */
281         fprintf(f, "%013lld", 0); /* TODO: carnê-leão PF? */
282         fprintf(f, "%013lld", 0); /* TODO: carnê-leão dependentes */
283         fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* dedução dependentes */
284         fprintf(f, "%013lld", 0); /* TODO: previdência RRA */
285         fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
286         fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
287         fprintf(f, "%013lld", 0); /* TODO: pensão RRA dependentes */
288         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
289         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
290         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
291 }
292
293 static void gera_totais_simples(struct declaracao *dec, FILE *f)
294 {
295         fprintf(f, "18");
296         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
297         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* TODO: rendimentos tributáveis */
298         /* desconto simplificado */
299         fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
300          /* base de cálculo */
301         fprintf(f, "%013lld", totais_get(dec, "BASE"));
302         fprintf(f, "%013lld", dec->devido); /* imposto devido */
303         fprintf(f, "%013lld", dec->retido); /* imposto retido */
304         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
305         fprintf(f, "%013lld", 0); /* TODO: carnê-leão */
306         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
307         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
308         fprintf(f, "%013lld", dec->pagar); /* imposto pagar */
309         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
310         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
311         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
312         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
313         if (dec->ano == 2015) {
314                 fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
315         } else if (dec->ano >= 2016) {
316                 fprintf(f, "%013lld", 0); /* FILLER */
317         }
318         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
319         fprintf(f, "%013lld", 0); /* TODO: imposto retido dependente */
320         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
321         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimento tributável PJ titular */
322         fprintf(f, "%013lld", 0); /* TODO: total rural */
323         fprintf(f, "%013lld", dec->retido); /* imposto retido titular */
324         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
325         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
326         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
327         fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
328         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* tributação exclusiva titular */
329         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
330         fprintf(f, "%013lld", 0); /* TODO: total não tributável AR */
331         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
332         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
333         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
334         fprintf(f, "%013lld", 0); /* TODO: isentos e não tributáveis, transportado */
335         fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva, transportado */
336         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos renda variável */
337         fprintf(f, "%013lld", 0); /* TODO: parcela isenta ganhos capital */
338         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
339         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependentes */
340         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
341         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
342         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
343         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
344         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
345         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
346         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
347         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
348         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
349         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
350         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
351         fprintf(f, "%013lld", dec->devido); /* imposto devido */
352         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
353         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
354         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
355         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
356         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
357 }
358
359 static void gera_completa(struct declaracao *dec, FILE *f)
360 {
361         fprintf(f, "19");
362         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
363         fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
364         fprintf(f, "%013lld", 0); /* TODO: imposto pago no exterior */
365         fprintf(f, "%013lld", 0); /* TODO: imposto complementar pago */
366         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
367         fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - titular */
368         fprintf(f, "%013lld", 0); /* TODO: livro caixa - titular */
369         fprintf(f, "%013lld", 0); /* TODO: carnê-leão - titular */
370         fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - dependente */
371         fprintf(f, "%013lld", 0); /* TODO: livro caixa - dependente */
372         fprintf(f, "%013lld", 0); /* TODO: carnê-leão - dependente */
373         fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* TODO: contribuição previdenciária privada */
374         fprintf(f, "%013lld", 0); /* TODO: contribuição FAPI */
375         /* INSS titular, TODO (2016): sem RRA */
376         fprintf(f, "%013lld", totais_get(dec, "INSS"));
377         /* TODO: INSS dependente, TODO (2016): sem RRA */
378         fprintf(f, "%013lld", 0);
379         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO")); /* TODO: 13o titular */
380         fprintf(f, "%013lld", 0); /* TODO: 13o dependente */
381         fprintf(f, "%05d", totais_get(dec, "DEPSINSTRUCAO")); /* dependentes com instrucao */
382         fprintf(f, "%05d", 0); /* TODO: alimentandos com instrucao */
383         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF titular */
384         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
385         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
386         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependente */
387         /* IRPF-2015-1.3 gera este valor como 0, antes era dec->devido */
388         fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
389         fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
390         if (dec->ano >= 2016) {
391                 /* TODO: valor até o limite da FUNPRESP */
392                 fprintf(f, "%013lld", 0);
393                 /* TODO: valor acima do limite da FUNPRESP */
394                 fprintf(f, "%013lld", 0);
395         }
396 }
397
398 static void gera_totais_completa(struct declaracao *dec, FILE *f)
399 {
400         fprintf(f, "20");
401         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
402         /* FIXME: completar campos */
403         fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimentos PJ titular */
404         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF titular */
405         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
406         fprintf(f, "%013lld", 0); /* TODO: resultado atividade rural */
407         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* TODO: total rendimentos tributáveis */
408         /* TODO (2016): somar FUNPRESP até o limite */
409         fprintf(f, "%013lld", totais_get(dec, "INSS")); /* previdencia oficial */
410         /* TODO (2016): somar FUNPRESP acima do limite */
411         fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* previdencia privada */
412         fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* deducao dependentes */
413         fprintf(f, "%013lld", totais_get(dec, "INSTRUCAO")); /* deducao instrucao */
414         fprintf(f, "%013lld", totais_get(dec, "MEDICAS")); /* despesas medicas */
415         fprintf(f, "%013lld", 0); /* TODO: pensao */
416         fprintf(f, "%013lld", 0); /* TODO: pensao escritura publica */
417         fprintf(f, "%013lld", 0); /* TODO: livro caixa */
418         fprintf(f, "%013lld", totais_get(dec, "DEDUCOES")); /* total deduções */
419         fprintf(f, "%013lld", totais_get(dec, "BASE")); /* base de cálculo */
420         fprintf(f, "%013lld", dec->devido); /* TODO: valor do imposto */
421         fprintf(f, "%013lld", 0); /* TODO: deducao do imposto (limitado a 6%) */
422         fprintf(f, "%013lld", dec->devido); /* imposto devido */
423         fprintf(f, "%013lld", 0); /* TODO: contribuicao patronal */
424         fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido menos patronal */
425         fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido mais RRA */
426         fprintf(f, "%013lld", dec->retido); /* imposto na fonte */
427         fprintf(f, "%013lld", 0); /* TODO: carne leao */
428
429         fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
430         fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
431         fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
432         fprintf(f, "%013lld", dec->retido); /* TODO: total imposto pago */
433         fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
434         fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
435         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
436         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
437
438         fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
439         fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
440         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
441         fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
442         if (dec->ano == 2015) {
443                 fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
444         } else if (dec->ano >= 2016) {
445                 fprintf(f, "%013lld", 0); /* FILLER */
446         }
447         fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
448         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
449         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
450         fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
451         fprintf(f, "%013lld", 0); /* TODO: imposto renda variável */
452
453         fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
454         fprintf(f, "%013lld", 0); /* TODO: imposto fonte dependente */
455         fprintf(f, "%013lld", 0); /* TODO: imposto moeda estrangeira */
456         fprintf(f, "%013lld", 0); /* TODO: imposto ganhos capital moeda */
457         fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
458         fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
459         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
460         fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
461         fprintf(f, "%013lld", 0); /* TODO: doações campanha */
462         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
463         fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
464         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
465         fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
466
467         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
468         fprintf(f, "%013lld", 0); /* TODO: previdencia RRA titular */
469         fprintf(f, "%013lld", 0); /* TODO: pensao RRA titular */
470         fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
471         fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
472         fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
473         fprintf(f, "%013lld", 0); /* TODO: previdencia RRA dependentes */
474         fprintf(f, "%013lld", 0); /* TODO: pensao RRA dependentes */
475         fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
476         fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
477
478         fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
479         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
480         fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
481         fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
482 }
483
484 static void gera_isentos(struct declaracao *dec, FILE *f)
485 {
486         fprintf(f, "23");
487         fprintf(f, "%-11.11s", dec->cpf);
488         fprintf(f, "%013lld", 0); /* TODO: bolsa de estudo */
489         fprintf(f, "%013lld", 0); /* TODO: pecúlio de previdência privada */
490         fprintf(f, "%013lld", totais_get(dec, "INDENIZACOES")); /* FGTS, aviso prévio indenizado */
491         fprintf(f, "%013lld", 0); /* TODO: ganho de capital isento */
492         fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
493         fprintf(f, "%013lld", 0); /* TODO: atividade rural */
494         fprintf(f, "%013lld", 0); /* TODO: contribuintes com 65 anos ou mais */
495         fprintf(f, "%013lld", 0); /* TODO: pensão por invalidez */
496         fprintf(f, "%013lld", totais_get(dec, "POUPANCA"));
497         fprintf(f, "%013lld", 0); /* TODO: sócio ou titular de empresa */
498         fprintf(f, "%013lld", totais_get(dec, "DOACOES")); /* herança, transferências patrimoniais */
499         fprintf(f, "%013lld", 0); /* TODO: outros rendimentos isentos */
500         fprintf(f, "%-60.60s", ""); /* FILLER1 */
501         fprintf(f, "%-13.13s", ""); /* FILLER2 */
502         fprintf(f, "%013lld", 0); /* TODO: alienação bens pequeno valor */
503         fprintf(f, "%013lld", 0); /* TODO: alienação único imóvel */
504         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital */
505         fprintf(f, "%013lld", 0); /* TODO: total bens pequeno valor, transportado GC */
506         fprintf(f, "%013lld", 0); /* TODO: alienção único imóvel, transportado GC */
507         fprintf(f, "%013lld", 0); /* TODO: redução ganho capital, transportado GC */
508         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira */
509         fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira, transportado */
510         fprintf(f, "%013lld", 0); /* TODO: GC total informado */
511         fprintf(f, "%013lld", 0); /* TODO: GC total transportado */
512         fprintf(f, "%013lld", 0); /* TODO: imposto renda anos anteriores */
513         fprintf(f, "%013lld", 0); /* TODO: rendimentos assalariados moeda estrangeira */
514         fprintf(f, "%013lld", 0); /* TODO: bonificações ações */
515         fprintf(f, "%013lld", 0); /* TODO: médicos residentes */
516         fprintf(f, "%013lld", 0); /* TODO: volutários da Copa */
517         fprintf(f, "%013lld", 0); /* TODO: meação e dissolução */
518         fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos com ações */
519         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital com ouro */
520         fprintf(f, "%013lld", 0); /* TODO: recuperação prejuízos na bolsa */
521         fprintf(f, "%013lld", 0); /* TODO: transportador de cargas */
522         fprintf(f, "%013lld", 0); /* TODO: transportador de passageiros */
523         fprintf(f, "%013lld", 0); /* TODO: retistuição imposto anos anteriores */
524 }
525
526 static void gera_exclusivos(struct declaracao *dec, FILE *f)
527 {
528         fprintf(f, "24");
529         fprintf(f, "%-11.11s", dec->cpf);
530         fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
531         fprintf(f, "%013lld", 0); /* TODO: ganho de capital */
532         fprintf(f, "%013lld", 0); /* TODO: ganho líquido renda variável */
533         fprintf(f, "%013lld", totais_get(dec, "APLICACOES")); /* TODO: aplicações financeiras */
534         fprintf(f, "%013lld", 0); /* TODO: outros */
535         fprintf(f, "%-60.60s", ""); /* FILLER1 */
536         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital alienação de bens */
537         fprintf(f, "%013lld", 0); /* TODO: ganhos de capital moeda estrangeira */
538         fprintf(f, "%013lld", 0); /* TODO: décimo terceiro dependentes */
539         fprintf(f, "%-13.13s", ""); /* FILLER2 */
540         fprintf(f, "%-60.60s", ""); /* FILLER3 */
541         fprintf(f, "%013lld", 0); /* TODO: RRA */
542         fprintf(f, "%013lld", 0); /* TODO: RRA dependentes */
543         fprintf(f, "%013lld", 0); /* TODO: Juros capital próprio */
544         fprintf(f, "%013lld", totais_get(dec, "PLR"));
545 }
546
547 static void gera_conjuge(struct declaracao *dec, FILE *f)
548 {
549         fprintf(f, "29");
550         fprintf(f, "%-11.11s", dec->cpf);
551         fprintf(f, "%-11.11s", dec->conjuge.cpf);
552         fprintf(f, "%013lld", dec->conjuge.base);
553         fprintf(f, "%013lld", dec->conjuge.imposto);
554         fprintf(f, "%013lld", dec->conjuge.isento);
555         fprintf(f, "%013lld", dec->conjuge.exclusivo);
556         fprintf(f, "%013lld", dec->conjuge.rendpj_exigibilidade_suspensa);
557         fprintf(f, "%013lld", dec->conjuge.total);
558         fprintf(f, "%c", dec->conjuge.entregou ? 'S' : 'N');
559 }
560
561 static int is_trailler_filler(int ano, int i)
562 {
563         return i == 44;
564         /* Ano 2016, linha 29 é um FILLER, mas preenchida com múltiplos
565          * 0s. Como esta linha não é gerada na declaração de 2016, não
566          * deve constar aqui, e será contabilizada como 0. */
567         /* || (ano == 2016 && i == 29); */
568 }
569
570 static int is_trailler_empty(int ano, int i)
571 {
572         return (i == 57 || i == 64 || i == 79) ||
573                 (ano == 2015 && i == 49);
574 }
575
576 static void gera_trailler(struct declaracao *dec, FILE *f)
577 {
578         int i;
579         fprintf(f, "T9");
580         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
581         fprintf(f, "%06d", dec->linhas[0]);
582         for (i = 16; i < 100; i++) {
583                 if (is_trailler_filler(dec->ano, i))
584                         fprintf(f, "%-5.5s", "0"); /* FILLER */
585                 else if (is_trailler_empty(dec->ano, i))
586                         ;
587                 else
588                         fprintf(f, "%05d", dec->linhas[i]);
589         }
590 }
591
592 static void gera_reciboheader(struct declaracao *dec, FILE *f)
593 {
594         fprintf(f, "HR");
595         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
596         fprintf(f, "%-3.3s", ""); /* FILLER */
597 }
598
599 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
600 {
601         fprintf(f, "DR");
602         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
603         fprintf(f, "%-3.3s", ""); /* FILLER */
604         fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
605         fprintf(f, "%-60.60s", dec->nome);
606         fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
607         fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
608         fprintf(f, "%-6.6s", dec->contribuinte.numero);
609         fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
610         fprintf(f, "%-19.19s", dec->contribuinte.bairro);
611         fprintf(f, "%-9.9s", dec->contribuinte.cep);
612         fprintf(f, "%04d", dec->contribuinte.cd_municipio);
613         fprintf(f, "%-40.40s", dec->contribuinte.municipio);
614         fprintf(f, "%-2.2s", dec->contribuinte.uf);
615         fprintf(f, "%-100.100s", ""); /* FILLER */
616         fprintf(f, "%-4.4s", ""); /* FILLER */
617         fprintf(f, "%-8.8s", ""); /* FILLER */
618         fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
619         fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
620         fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
621         fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
622         fprintf(f, "%013lld", dec->devido); /* Imposto devido */
623         fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
624         fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
625         fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
626         fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
627         fprintf(f, "%-3.3s", dec->banco ? : "000"); /* numero banco */
628         fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* numero agencia */
629         fprintf(f, " "); /* FILLER */
630         fprintf(f, "%d", 0); /* TODO: debito primeira quota */
631         fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
632         fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
633         fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
634         fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
635 }
636
637 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
638 {
639         fprintf(f, "R9");
640         fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
641         fprintf(f, "%-3.3s", ""); /* FILLER */
642         fprintf(f, "%010u", dec->rhash);
643 }
644
645 static void gera_rendimento(struct declaracao *dec, FILE *f)
646 {
647         struct rendimento *r;
648         r = list_get(dec->rendimento, dec->linhas[21]);
649         fprintf(f, "21");
650         fprintf(f, "%s", dec->cpf);
651         fprintf(f, "%-14.14s", r->cnpj);
652         fprintf(f, "%-60.60s", r->nome);
653         fprintf(f, "%013lld", r->rendimento);
654         fprintf(f, "%013lld", r->previdencia);
655         fprintf(f, "%013lld", r->decimoterceiro);
656         fprintf(f, "%013lld", r->imposto);
657         fprintf(f, "%-8.8s", r->saida);
658         fprintf(f, "%013lld", r->imposto_13o);
659 }
660
661 static void gera_pagamento(struct declaracao *dec, FILE *f)
662 {
663         struct pagamento *p;
664         p = list_get(dec->pagamentos, dec->linhas[26]);
665         fprintf(f, "26");
666         fprintf(f, "%s", dec->cpf);
667         fprintf(f, "%02d", p->codigo);
668         fprintf(f, "%05d", p->dependente);
669         fprintf(f, "%-14.14s", p->cnpj);
670         fprintf(f, "%-60.60s", p->nome);
671         fprintf(f, "%-11.11s", ""); /* TODO: NIT */
672         fprintf(f, "%013lld", p->pagamento);
673         fprintf(f, "%013lld", p->reembolso);
674         if (dec->ano >= 2016) {
675                 /* TODO: contribuição do ente público patrocinador (FUNPRESP?) */
676                 fprintf(f, "%013lld", 0);
677         }
678         fprintf(f, "%d", strlen(p->cnpj) == 11 ? 1 : 2);
679         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
680         fprintf(f, "%c", p->dependente ? 'D' : 'T');
681 }
682
683 static void gera_isento(struct declaracao *dec, FILE *f, int codigo)
684 {
685         struct isento *i;
686         i = isento_get(dec, codigo, dec->linhas[codigo]);
687         fprintf(f, "%02d", codigo);
688         fprintf(f, "%-11.11s", dec->cpf); /* Titular */
689         fprintf(f, "%05d", dec->linhas[codigo] + 1); /* Chave */
690         /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
691         fprintf(f, "%c", i->dependente ? 'D' : 'T');
692         fprintf(f, "%-14.14s", i->cnpj);
693         fprintf(f, "%-60.60s", i->nome);
694         fprintf(f, "%013lld", i->valor);
695         if (i->dependente) {
696                 struct dependente *d;
697                 d = list_get(dec->dependentes, i->dependente - 1);
698                 fprintf(f, "%-11.11s", d ? d->cpf : "");
699         } else {
700                 fprintf(f, "%-11.11s", dec->cpf);
701         }
702 }
703
704 static void gera_doacao(struct declaracao *dec, FILE *f)
705 {
706         gera_isento(dec, f, 82);
707 }
708
709 static void gera_indenizacoes(struct declaracao *dec, FILE *f)
710 {
711         gera_isento(dec, f, 93);
712 }
713
714 static void gera_plr(struct declaracao *dec, FILE *f)
715 {
716         gera_isento(dec, f, 96);
717 }
718
719 static void gera_poupanca(struct declaracao *dec, FILE *f)
720 {
721         gera_isento(dec, f, 98);
722 }
723
724 static void gera_aplicacoes(struct declaracao *dec, FILE *f)
725 {
726         gera_isento(dec, f, 99);
727 }
728
729 static void gera_dependente(struct declaracao *dec, FILE *f)
730 {
731         struct dependente *d;
732         d = list_get(dec->dependentes, dec->linhas[25]);
733
734         fprintf(f, "25");
735         fprintf(f, "%s", dec->cpf);
736         fprintf(f, "%05d", dec->linhas[25] + 1);
737         fprintf(f, "%02d", d->codigo);
738         fprintf(f, "%-60.60s", d->nome);
739         fprintf(f, "%-8.8s", d->dn);
740         fprintf(f, "%-11.11s", d->cpf);
741         /* TODO: Indicador de saída */
742         fprintf(f, " ");
743         if (dec->ano >= 2016) {
744                 /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
745                 fprintf(f, "%-11.11s", "");
746         }
747 }
748
749 static void gera_bem(struct declaracao *dec, FILE *f)
750 {
751         struct bem *b;
752         b = list_get(dec->bens, dec->linhas[27]);
753
754         fprintf(f, "27");
755         fprintf(f, "%s", dec->cpf);
756         fprintf(f, "%02d", b->codigo);
757
758         /* FIXME: exterior */
759         fprintf(f, "0");
760         fprintf(f, "105"); /* código Brasil */
761
762         fprintf(f, "%-512.512s", b->descricao);
763         fprintf(f, "%013lld", b->valor_anterior);
764         fprintf(f, "%013lld", b->valor);
765
766         /* Imóvel */
767         fprintf(f, "%-40.40s", b->logradouro ?: "");
768         fprintf(f, "%-6.6s", b->numero ?: "");
769         fprintf(f, "%-40.40s", b->complemento ?: "");
770         fprintf(f, "%-40.40s", b->bairro ?: "");
771         fprintf(f, "%-9.9s", b->cep ?: "");
772         fprintf(f, "%-2.2s", b->uf ?: "");
773         fprintf(f, "%04d", b->cd_municipio);
774         fprintf(f, "%-40.40s", b->municipio ?: "");
775         /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
776         fprintf(f, "%d", b->registro ? 1 : 0);
777         fprintf(f, "%-40.40s", b->matricula ?: "");
778         fprintf(f, "%-40.40s", b->registro ?: "");
779         fprintf(f, "%011lld", b->area);
780         /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
781         fprintf(f, "%d", 0);
782         fprintf(f, "%-60.60s", b->cartorio ?: "");
783
784         /* Número de chave */
785         fprintf(f, "%05d", dec->linhas[27] + 1);
786 }
787
788 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
789
790 static void update_hash(struct declaracao *dec, char *buf, size_t len)
791 {
792         int r;
793         int linha;
794         r = sscanf(buf, "%2d", &linha);
795         if (r == 1 || !strncmp(buf, "T9", 2)) {
796                 dec->hash = crc32(dec->hash, buf, len - 2);
797                 dec->rhash = crc32(dec->rhash, buf, len - 2);
798                 return;
799         } else if (strncmp(buf, "R9", 2) && strncmp(buf, "IRPF", 4)) {
800                 dec->rhash = crc32(dec->rhash, buf, len - 2);
801         }
802 }
803
804 static int wrap(gera_linha fn, struct declaracao *dec, struct list *l)
805 {
806         FILE *m;
807         char *buf = NULL;
808         size_t bsize;
809         int linha;
810         int r;
811         uLong c = crc32(0L, Z_NULL, 0);
812         m = open_memstream(&buf, &bsize);
813         if (!m) {
814                 return -errno;
815         }
816         fn(dec, m);
817         dec->linhas[0]++;
818         fflush(m);
819
820         /* Calcula CRC32 para campo de controle dos registros. */
821         c = crc32(c, buf, bsize);
822         fprintf(m, "%010ld\r\n", c);
823
824         fclose(m);
825         r = sscanf(buf, "%2d", &linha);
826         if (r == 1 && linha >= 0 && linha < 100) {
827                 dec->linhas[linha]++;
828         }
829         update_hash(dec, buf, bsize);
830         return list_add(&l, buf);
831 }
832
833 static void insert_hash(struct declaracao *dec, char *irpf)
834 {
835         uLong c = crc32(0L, NULL, 0);
836         char cpf[13];
837         char crc[11];
838         snprintf(cpf, 13, "%-8.8s.DEC", dec->cpf);
839         c = crc32(c, cpf, 12);
840         snprintf(crc, 11, "%010ld", dec->hash);
841         memcpy(irpf + 101, crc, 10);
842         c = crc32(c, irpf, strlen(irpf) - 12);
843         snprintf(crc, 11, "%010ld", c);
844         memcpy(irpf + strlen(irpf) - 12, crc, 10);
845 }
846
847 static int gera(struct declaracao *dec, char *filename)
848 {
849         FILE *f;
850         int r = 0;
851         int i;
852         struct rendimento *rendimento;
853         struct isento *isento;
854         struct pagamento *pagamento;
855         struct bem *bem;
856         struct dependente *dependente;
857         struct list *linhas;
858         char *buf;
859
860         linhas = list_new();
861         if (!linhas)
862                 return -ENOMEM;
863
864         dec->hash = crc32(0L, NULL, 0);
865         dec->rhash = crc32(0L, NULL, 0);
866
867 #define W(fn) \
868         do { \
869                 r = wrap(fn, dec, linhas); \
870                 if (r < 0) \
871                         goto out; \
872         } while (0);
873
874         f = fopen(filename, "w");
875         if (!f) {
876                 r = -errno;
877                 dec_set_error(dec, "Não foi possível abrir arquivo %s: %s.",
878                               filename, strerror(errno));
879                 goto out_file;
880         }
881         memset(dec->linhas, 0, sizeof(dec->linhas));
882         W(gera_header);
883         W(gera_contribuinte);
884         if (dec->tipo == COMPLETA) {
885                 W(gera_completa);
886                 W(gera_totais_completa);
887         } else {
888                 W(gera_simples);
889                 W(gera_totais_simples);
890         }
891         for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
892                 W(gera_rendimento);
893         }
894
895         if (totais_get(dec, "ISENTOS"))
896                 W(gera_isentos);
897         if (totais_get(dec, "EXCLUSIVOS"))
898                 W(gera_exclusivos);
899
900         for (i = 0; (dependente = list_get(dec->dependentes, i)); i++) {
901                 W(gera_dependente);
902         }
903         for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
904                 W(gera_pagamento);
905         }
906         for (i = 0; (bem = list_get(dec->bens, i)); i++) {
907                 W(gera_bem);
908         }
909
910         if (dec->ano == 2015 && dec->conjuge.cpf)
911                 W(gera_conjuge);
912
913         /* Rendimentos isentos e com tributação exclusiva */
914         /* Registros 82 a 89, e 92 a 99 */
915 #define IW(fn, codigo) \
916         for (i = 0; ; i++) { \
917                 isento = isento_get(dec, codigo, i); \
918                 if (!isento) \
919                         break; \
920                 W(fn); \
921         }
922         IW(gera_doacao, 82);
923         IW(gera_indenizacoes, 93);
924         IW(gera_plr, 96);
925         IW(gera_poupanca, 98);
926         IW(gera_aplicacoes, 99);
927
928         W(gera_trailler);
929         W(gera_reciboheader);
930         W(gera_recibodetalhe);
931         W(gera_recibotrailler);
932
933         insert_hash(dec, list_get(linhas, 0));
934         for (i = 0; (buf = list_get(linhas, i)); i++) {
935                 fwrite(buf, strlen(buf), 1, f);
936         }
937
938         fclose(f);
939         list_free(linhas, free);
940         return 0;
941 out:
942         fclose(f);
943 out_file:
944         list_free(linhas, free);
945         return r;
946 }
947
948 static int run_gera(struct declaracao *dec, char **args, int argc)
949 {
950         if (argc != 2) {
951                 dec_set_error(dec, "Comando %s recebe um nome de arquivo como parâmetro.",
952                               args[0]);
953                 return -EINVAL;
954         }
955         if (!ANO_VALIDO(dec->ano)) {
956                 dec_set_error(dec, "Comando %s não suporta ano %d.",
957                               args[0], dec->ano);
958                 return -EINVAL;
959         }
960         return gera(dec, args[1]);
961 }
962
963 static struct cmd cmd_gera = {
964         .name = "gera",
965         .run = run_gera,
966 };
967
968 int gera_cmd_init(void)
969 {
970         cmd_add(&cmd_gera);
971         return 0;
972 }