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