Utiliza atributos para bens.
[cascardo/declara.git] / lib / gera.c
index 09c1bdd..214037c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (C) 2015  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
+ *  Copyright (C) 2015-2017  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#include <zlib.h>
 #include "declaracao.h"
 #include "cmd.h"
 #include "rendimento.h"
+#include "carne.h"
+#include "isento.h"
 #include "pagamento.h"
+#include "bem.h"
+#include "dependente.h"
 #include "totais.h"
+#include "sistema.h"
+#include "ano.h"
+#include "attr.h"
 
 static void gera_header(struct declaracao *dec, FILE *f)
 {
+       int i;
+
        fprintf(f, "IRPF    ");
        fprintf(f, "%04d", dec->ano); /* Exercício */
        fprintf(f, "%04d", dec->ano - 1); /* Ano base */
-       fprintf(f, "2500"); /* Código */
+       if (dec->ano == 2015)
+               fprintf(f, "2500"); /* Código */
+       else if (dec->ano == 2016)
+               fprintf(f, "2600"); /* Código */
+       else if (dec->ano == 2017)
+               fprintf(f, "2700"); /* Código */
+       else if (dec->ano == 2018)
+               fprintf(f, "2800"); /* Código */
+       else if (dec->ano == 2019)
+               fprintf(f, "2900"); /* Código */
+       else if (dec->ano == 2020)
+               fprintf(f, "3000");
        fprintf(f, "%s", dec->retifica ? "1" : "0"); /* Retificadora */
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        fprintf(f, "   "); /* Filler */
        fprintf(f, "1"); /* Tipo NI: Pessoa Física (1) */
-       fprintf(f, "100"); /* Versão IRPF */
+       if (dec->ano == 2015)
+               fprintf(f, "130"); /* Versão IRPF */
+       else if (dec->ano == 2016)
+               fprintf(f, "110"); /* Versão IRPF */
+       else if (dec->ano == 2017)
+               fprintf(f, "130"); /* Versão IRPF */
+       else if (dec->ano == 2018)
+               fprintf(f, "160"); /* Versão IRPF */
+       else if (dec->ano == 2019)
+               fprintf(f, "150"); /* Versão IRPF */
+       else if (dec->ano == 2020)
+               fprintf(f, "180"); /* Versão IRPF */
        fprintf(f, "%-60.60s", dec->nome);
-       fprintf(f, "%s", dec->contribuinte.uf);
+       fprintf(f, "%-2.2s", dec->contribuinte.uf ?: "");
        fprintf(f, "%s", "0000000000"); /* FIXME: hash */
        fprintf(f, "1"); /* TODO: certificavel */
-       fprintf(f, "%s", dec->contribuinte.dn);
+       fprintf(f, "%-8.8s", dec->contribuinte.dn ?: "");
        fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
-       fprintf(f, "%s", dec->restituicao ? "2" : "0"); /* TODO: resultado imposto, 2 - restituicao */
+       /* TODO: resultado imposto, 1 - pagar, 2 - restituicao */
+       fprintf(f, "%s", dec->restituicao ? "2" : (dec->pagar ? "1" : "0"));
        fprintf(f, "S"); /* TODO: gerada? */
        fprintf(f, "%-10.10s", dec->retifica ?: ""); /* recibo retificada ex. atual */
        fprintf(f, "2"); /* TODO: PGD */
-       fprintf(f, "LINUX         "); /* TODO: SO */
-       fprintf(f, "3.16.0-"); /* TODO: versao SO */
-       fprintf(f, "1.7.0_75 "); /* TODO: versao JVM */
+       fprintf(f, "%-14.14s", sistema_get_so(dec));
+       fprintf(f, "%-7.7s", sistema_get_so_versao(dec));
+       fprintf(f, "%-9.9s", sistema_get_jvm_versao(dec));
        fprintf(f, "%-10.10s", ""); /* TODO: última declaração transmitida (pode ser vazio?) */
        fprintf(f, "%04d", dec->contribuinte.cd_municipio);
-       fprintf(f, "           "); /* TODO: CPF conjuge */
+       fprintf(f, "%-11.11s", dec->conjuge.cpf ? : ""); /* TODO: CPF conjuge */
        fprintf(f, "%d", dec->obrigatoria ? 1 : 0); /* obrigatoria entrega */
        fprintf(f, "%013lld", dec->devido); /* imposto devido, carne-leao, complementar dos dependentes */
        fprintf(f, "%-10.10s", dec->recibo ?: ""); /* recibo ex. anterior */
@@ -61,15 +94,16 @@ static void gera_header(struct declaracao *dec, FILE *f)
         * anterior, se não 1. */
        fprintf(f, "%d", dec->retifica ? 0 : (dec->recibo ? 2 : 1));
        /* Indicador imposto pago, TODO: carnê leão e Lei 11.033. */
-       fprintf(f, "%02d", dec->retido ? 1 : 0);
+       fprintf(f, "%02d", totais_get(dec, "CARNE") > 0 ? 7 :
+                                                       (dec->retido ? 1 : 0));
        /* Indicador imposto antecipado, TODO: carnê leão, Lei 11.033,
         * outros. */
        fprintf(f, "%d", dec->retido ? 1 : 0);
        fprintf(f, "0"); /* TODO: mudanca endereco */
-       fprintf(f, "%s", dec->contribuinte.cep);
+       fprintf(f, "%-8.8s", dec->contribuinte.cep ?: "");
        fprintf(f, "0"); /* TODO: debito 1a quota */
-       fprintf(f, "%-3.3s", dec->banco); /* no banco */
-       fprintf(f, "%-4.4s", dec->agencia); /* agencia */
+       fprintf(f, "%-3.3s", dec->banco ? : "000"); /* no banco */
+       fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agencia */
        fprintf(f, " "); /* TODO: filler */
        fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
        fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
@@ -82,48 +116,58 @@ static void gera_header(struct declaracao *dec, FILE *f)
        fprintf(f, " "); /* RRA4 */
        fprintf(f, "%-11.11s", ""); /* CPF RRA4 */
        fprintf(f, "0000000000000"); /* TODO: Doacao ECA */
-       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* TODO: CNPJ maior */
-       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* TODO: CNPJ maior 2 */
-       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* TODO: CNPJ maior 3 */
-       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* TODO: CNPJ maior 4 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 1 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 1 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 2 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 2 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 3 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 3 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 4 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 4 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 5 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 5 */
-       fprintf(f, "%-11.11s", ""); /* CPF Dependente 6 */
-       fprintf(f, "%-8.8s", ""); /* DN Dependente 6 */
+       fprintf(f, "0000000000000"); /* TODO: Doacao Idoso */
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 1)); /* CNPJ maior 2 */
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 2)); /* CNPJ maior 3 */
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 3)); /* CNPJ maior 4 */
+       if (dec->ano < 2017 || dec->ano >= 2019) {
+               /* CPF e DN de dependentes 1 a 6 */
+               for (i = 1; i <= 6; i++) {
+                       struct dependente *dependente = list_get(dec->dependentes, i - 1);
+                       if (dependente && dependente->cpf && dependente->cpf[0]) {
+                               fprintf(f, "%-11.11s", dependente->cpf);
+                       } else {
+                               fprintf(f, "%-11.11s", "");
+                       }
+                       if (dependente && dependente->dn && dependente->dn[0]) {
+                               fprintf(f, "%-8.8s", dependente->dn);
+                       } else {
+                               fprintf(f, "%-8.8s", "");
+                       }
+               }
+       } else {
+               fprintf(f, "%-114.114s", "");
+       }
        /* medico maior, TODO: outros códigos */
-       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 0));
+       fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 0));
        /* medico maior 2, TODO: outros códigos */
-       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 1));
+       fprintf(f, "%-14.14s", medico_cnpj_ordenado(dec, 1));
        fprintf(f, "%-11.11s", ""); /* CPF pensao */
        fprintf(f, "%-11.11s", ""); /* CPF inventariante */
        fprintf(f, "%-40.40s", dec->contribuinte.municipio);
        fprintf(f, "%-60.60s", dec->nome);
-       fprintf(f, "%-11.11s", ""); /* CPF empregada */
-       fprintf(f, "000000000000"); /* FIXME: MAC */
+       if (dec->ano >= 2017)
+               fprintf(f, "%010u ", crc32(0, dec->cpf, 11)); /* hash CPF */
+       else
+               fprintf(f, "%-11.11s", ""); /* CPF empregada, FILLER */
+       fprintf(f, "%-12.12s", sistema_get_mac(dec));
        fprintf(f, "%08d", 0); /* Data saída */
        fprintf(f, "%-11.11s", ""); /* CPF procurador */
        fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
-       fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
+       fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* Total tributavel */
        /* CNPJ previdencia */
-       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 0));
+       fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 0));
        /* CNPJ previdencia 2 */
-       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 1));
+       fprintf(f, "%-14.14s", inss_cnpj_ordenado(dec, 1));
        /* Total isentos */
        fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
        /* Total exclusivo */
        fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS"));
        /* Total pagamentos */
        fprintf(f, "%013lld", totais_get(dec, "PAGAMENTOS"));
-       fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
-       fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
+       fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
+       fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
        fprintf(f, "0"); /* TODO: revalidar DV conta */
 
        /* Mudanças de 2015 */
@@ -148,9 +192,31 @@ static void gera_header(struct declaracao *dec, FILE *f)
 
        /* Fim das mudanças de 2015 */
 
+       /* Mudanças de 2016 */
+
+       if (dec->ano >= 2016) {
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 0));
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 1));
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 2));
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 3));
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 4));
+               /* CNPJ maior pagamento dedutível */
+               fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 5));
+               /* TODO: CNPJ maior pagamento FUNPRESP */
+               fprintf(f, "%-14.14s", "");
+       }
+
+       /* Fim das mudanças de 2016 */
+
+       if (dec->ano >= 2020)
+               fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor ?: "");
+
        fprintf(f, "   "); /* Teste PGD, FILLER2 */
-       fprintf(f, "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
 }
 
 static void gera_contribuinte(struct declaracao *dec, FILE *f)
@@ -161,7 +227,7 @@ static void gera_contribuinte(struct declaracao *dec, FILE *f)
        fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
        fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
        fprintf(f, "%-6.6s", dec->contribuinte.numero);
-       fprintf(f, "%-21.21s", dec->contribuinte.complemento);
+       fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
        fprintf(f, "%-19.19s", dec->contribuinte.bairro);
        fprintf(f, "%-9.9s", dec->contribuinte.cep);
        fprintf(f, "%04d", dec->contribuinte.cd_municipio);
@@ -169,27 +235,42 @@ static void gera_contribuinte(struct declaracao *dec, FILE *f)
        fprintf(f, "%-2.2s", dec->contribuinte.uf);
        fprintf(f, "   "); /* TODO: código exterior */
        fprintf(f, "105"); /* TODO: código país */
-       fprintf(f, "%-100.100s", ""); /* TODO: FILLER3 */
-       fprintf(f, "%-4.4s", ""); /* TODO: FILLER1 */
-       fprintf(f, "%-8.8s", ""); /* TODO: FILLER2 */
-       fprintf(f, "%-4.4s", dec->contribuinte.ddd);
-       fprintf(f, "%-9.9s", dec->contribuinte.telefone);
+       if (dec->ano == 2015) {
+               fprintf(f, "%-100.100s", ""); /* FILLER3 */
+               fprintf(f, "%-4.4s", ""); /* FILLER1 */
+               fprintf(f, "%-8.8s", ""); /* FILLER2 */
+       } else if (dec->ano >= 2016) {
+               fprintf(f, "%-90.90s", ""); /* FILLER3 */
+               /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
+               fprintf(f, "%-11.11s", dec->contribuinte.nit ?: "");
+               /* CPF do cônjuge */
+               fprintf(f, "%-11.11s", dec->conjuge.cpf ?: "");
+       }
+       if (dec->ano <= 2017) {
+               fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
+               fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
+       } else if (dec->ano >= 2020) {
+               fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
+               fprintf(f, "%-9.9s", "");
+       } else {
+               fprintf(f, "%-13.13s", ""); /* FILLER */
+       }
        fprintf(f, "%-8.8s", dec->contribuinte.dn);
-       fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor);
+       fprintf(f, "%-13.13s", dec->contribuinte.titulo_eleitor ?: "");
        fprintf(f, "%03d", dec->contribuinte.ocupacao_principal);
        fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao);
-       fprintf(f, "0"); /* TODO: qnt quotas */
+       fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: qnt quotas */
        fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
        fprintf(f, "%s", dec->retifica ? "S" : "N");
        fprintf(f, "S"); /* GERADO */
        fprintf(f, "N"); /* TODO: mudança de endereço */
        fprintf(f, "%-12.12s", dec->retifica ? : ""); /* Recibo declaração original */
-       fprintf(f, "%-3.3s", dec->banco); /* banco */
-       fprintf(f, "%-4.4s", dec->agencia); /* agência */
+       fprintf(f, "%-3.3s", dec->banco ? : "000"); /* banco */
+       fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* agência */
        fprintf(f, "N"); /* TODO: deficiência */
        fprintf(f, "0"); /* FILLER: pré-preenchida */
-       fprintf(f, "%-13.13s", dec->contacorrente); /* conta */
-       fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
+       fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* conta */
+       fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
        fprintf(f, "N"); /* TODO: débito automático */
        fprintf(f, "0"); /* TODO: débito primeira quota */
        /* CNPJ principal fonte */
@@ -197,8 +278,17 @@ static void gera_contribuinte(struct declaracao *dec, FILE *f)
        fprintf(f, "%-10.10s", dec->recibo ?: ""); /* Recibo última declaração ano anterior */
        fprintf(f, "A"); /* Declaração de Ajuste */
        fprintf(f, "%-11.11s", ""); /* TODO: CPF procurador */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       if (dec->ano >= 2016)
+               fprintf(f, "%-20.20s", ""); /* TODO: registro profissional */
+       if (dec->ano >= 2017) {
+               fprintf(f, "%-11.11s", dec->contribuinte.celular ?: ""); /* celular */
+               fprintf(f, "%s", dec->conjuge.cpf ? "S" : "N");
+       }
+       if (dec->ano >= 2020) {
+               fprintf(f, "%-11.11s", dec->contribuinte.telefone ?: "");
+       } else if (dec->ano >= 2018) {
+               fprintf(f, "%-2.2s%-9.9s", dec->contribuinte.ddd ?: "", dec->contribuinte.telefone ?: "");
+       }
 }
 
 static void gera_simples(struct declaracao *dec, FILE *f)
@@ -207,8 +297,8 @@ static void gera_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        fprintf(f, "%013lld", 0); /* TODO: carnê leão */
        fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
-       /* rendimentos isentos */
-       fprintf(f, "%013lld", totais_get(dec, "ISENTOS"));
+       /* rendimentos isentos titular */
+       fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT"));
        /* rendimentos tributação exclusiva, exceto décimo terceiro */
        fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
        /* 13o. */
@@ -216,17 +306,24 @@ static void gera_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", 0); /* TODO: retido na fonte (Lei 11.033) */
        fprintf(f, "%013lld", 0); /* TODO: 13o. dependentes */
        fprintf(f, "%013lld", 0); /* TODO: lucros dependentes */
-       fprintf(f, "%013lld", 0); /* TODO: isentos dependentes */
-       fprintf(f, "%013lld", 0); /* TODO: exclusivos dependentes */
+       /* BUG IRPF: O IRPF imprime 0 aqui mesmo com doações e poupança. */
+       /* fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); */
+       fprintf(f, "%013lld", 0); /* isentos dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* exclusivos dependentes */
        fprintf(f, "%-13.13s", ""); /* FILLER */
        fprintf(f, "%-13.13s", ""); /* FILLER */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependentes */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF ext. depend. */
-       fprintf(f, "%013lld", 0); /* TODO: carnê-leão PF? */
-       fprintf(f, "%013lld", 0); /* TODO: carnê-leão dependentes */
-       fprintf(f, "%013lld", 0); /* TODO: dedução dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* rendimentos PF titular */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFDEP")); /* rendimentos PF dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "RENDEXTTIT")); /* FIXME: rendimentos PF exterior titular */
+       fprintf(f, "%013lld", totais_get(dec, "RENDEXTDEP")); /* FIXME: rendimentos PF ext. depend. */
+
+       /* FIXME: um teste demonstra que não há valor quando existem rendimentos de PF para o titular */
+       /* totais_get(dec, "RENDPF")); */
+       /* TODO: carnê-leão PF? */
+       fprintf(f, "%013lld", totais_get(dec, "CARNETIT"));
+
+       fprintf(f, "%013lld", totais_get(dec, "CARNEDEP")); /* carnê-leão dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* dedução dependentes */
        fprintf(f, "%013lld", 0); /* TODO: previdência RRA */
        fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
        fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
@@ -234,15 +331,13 @@ static void gera_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
        fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
        fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
 }
 
 static void gera_totais_simples(struct declaracao *dec, FILE *f)
 {
        fprintf(f, "18");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
-       fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* TODO: rendimentos tributáveis */
+       fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* rendimentos tributáveis */
        /* desconto simplificado */
        fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
         /* base de cálculo */
@@ -250,28 +345,32 @@ static void gera_totais_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", dec->devido); /* imposto devido */
        fprintf(f, "%013lld", dec->retido); /* imposto retido */
        fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
-       fprintf(f, "%013lld", 0); /* TODO: carnê-leão */
+       fprintf(f, "%013lld", totais_get(dec, "CARNE")); /* TODO: imposto pago carnê-leão */
        fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
        fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
        fprintf(f, "%013lld", dec->pagar); /* imposto pagar */
-       fprintf(f, "%d", 0); /* TODO: quotas */
-       fprintf(f, "%013lld", 0); /* TODO: valor quota */
+       fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
+       fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
        fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
        fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
-       fprintf(f, "%013lld", 0); /* TODO: conjuge */
+       if (dec->ano == 2015) {
+               fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
+       } else if (dec->ano >= 2016) {
+               fprintf(f, "%013lld", 0); /* FILLER */
+       }
        fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
        fprintf(f, "%013lld", 0); /* TODO: imposto retido dependente */
        fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
        fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimento tributável PJ titular */
        fprintf(f, "%013lld", 0); /* TODO: total rural */
-       fprintf(f, "%013lld", dec->retido); /* imposto retido titular */
+       fprintf(f, "%013lld", dec->retido); /* FIXME: imposto retido titular */
        fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
        fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
        fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos isentos dependentes */
-       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
-       fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva dependentes */
-       fprintf(f, "%013lld", 0); /* TODO: total não tributável */
+       fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* tributação exclusiva titular */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: total não tributável AR */
        fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
        fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
        fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
@@ -279,8 +378,8 @@ static void gera_totais_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva, transportado */
        fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos renda variável */
        fprintf(f, "%013lld", 0); /* TODO: parcela isenta ganhos capital */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
-       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT") + totais_get(dec, "RENDEXTTIT")); /* TODO: rendimentos PF + exterior titular */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFDEP") + totais_get(dec, "RENDEXTDEP")); /* TODO: rendimentos PF exterior dependentes */
        fprintf(f, "%013lld", 0); /* TODO: doações campanha */
        fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
        fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
@@ -298,18 +397,48 @@ static void gera_totais_simples(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
        fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
        fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       if (dec->ano >= 2018) {
+               fprintf(f, "%05lld", dec->aliquota_efetiva);
+       }
 }
 
 static void gera_completa(struct declaracao *dec, FILE *f)
 {
        fprintf(f, "19");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior */
-       /* FIXME: completar campos */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0)); /* CNPJ maior */
+       fprintf(f, "%013lld", 0); /* TODO: imposto pago no exterior */
+       fprintf(f, "%013lld", 0); /* TODO: imposto complementar pago */
+       fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - titular */
+       fprintf(f, "%013lld", 0); /* TODO: livro caixa - titular */
+       fprintf(f, "%013lld", 0); /* TODO: carnê-leão - titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos recebidos no exterior - dependente */
+       fprintf(f, "%013lld", 0); /* TODO: livro caixa - dependente */
+       fprintf(f, "%013lld", 0); /* TODO: carnê-leão - dependente */
+       fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* TODO: contribuição previdenciária privada */
+       fprintf(f, "%013lld", 0); /* TODO: contribuição FAPI */
+       /* INSS titular, TODO (2016): sem RRA */
+       fprintf(f, "%013lld", totais_get(dec, "INSS"));
+       /* TODO: INSS dependente, TODO (2016): sem RRA */
+       fprintf(f, "%013lld", 0);
+       fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO")); /* TODO: 13o titular */
+       fprintf(f, "%013lld", 0); /* TODO: 13o dependente */
+       fprintf(f, "%05d", totais_get(dec, "DEPSINSTRUCAO")); /* dependentes com instrucao */
+       fprintf(f, "%05d", 0); /* TODO: alimentandos com instrucao */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* TODO: rendimentos PF titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exterior dependente */
+       /* IRPF-2015-1.3 gera este valor como 0, antes era dec->devido */
+       fprintf(f, "%013lld", 0); /* TODO: imposto devido sem rendimento exterior */
+       fprintf(f, "%013lld", 0); /* TODO: limite imposto pago exterior */
+       if (dec->ano >= 2016) {
+               /* TODO: valor até o limite da FUNPRESP */
+               fprintf(f, "%013lld", 0);
+               /* TODO: valor acima do limite da FUNPRESP */
+               fprintf(f, "%013lld", 0);
+       }
 }
 
 static void gera_totais_completa(struct declaracao *dec, FILE *f)
@@ -317,8 +446,248 @@ static void gera_totais_completa(struct declaracao *dec, FILE *f)
        fprintf(f, "20");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        /* FIXME: completar campos */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       fprintf(f, "%013lld", totais_get(dec, "RENDPJTIT")); /* rendimentos PJ titular */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPFTIT")); /* TODO: rendimentos PF titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF dependente */
+       fprintf(f, "%013lld", 0); /* TODO: resultado atividade rural */
+       fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* total rendimentos tributáveis */
+       /* TODO (2016): somar FUNPRESP até o limite */
+       fprintf(f, "%013lld", totais_get(dec, "INSS")); /* previdencia oficial */
+       /* TODO (2016): somar FUNPRESP acima do limite */
+       fprintf(f, "%013lld", totais_get(dec, "PREVIDENCIA")); /* previdencia privada */
+       fprintf(f, "%013lld", totais_get(dec, "DEPENDENTES")); /* deducao dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "INSTRUCAO")); /* deducao instrucao */
+       fprintf(f, "%013lld", totais_get(dec, "MEDICAS")); /* despesas medicas */
+       fprintf(f, "%013lld", 0); /* TODO: pensao */
+       fprintf(f, "%013lld", 0); /* TODO: pensao escritura publica */
+       fprintf(f, "%013lld", 0); /* TODO: livro caixa */
+       fprintf(f, "%013lld", totais_get(dec, "DEDUCOES")); /* total deduções */
+       fprintf(f, "%013lld", totais_get(dec, "BASE")); /* base de cálculo */
+       fprintf(f, "%013lld", dec->devido); /* TODO: valor do imposto */
+       fprintf(f, "%013lld", 0); /* TODO: deducao do imposto (limitado a 6%) */
+       fprintf(f, "%013lld", dec->devido); /* imposto devido */
+       fprintf(f, "%013lld", 0); /* TODO: contribuicao patronal */
+       fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido menos patronal */
+       fprintf(f, "%013lld", dec->devido); /* TODO: imposto devido mais RRA */
+       fprintf(f, "%013lld", dec->retido); /* imposto na fonte */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPF")); /* TODO: carne leao */
+
+       fprintf(f, "%013lld", 0); /* TODO: imposto complementar */
+       fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
+       fprintf(f, "%013lld", 0); /* TODO: imposto retido Lei 11.033 */
+       fprintf(f, "%013lld", dec->retido); /* TODO: total imposto pago */
+       fprintf(f, "%013lld", dec->restituicao); /* imposto a restituir */
+       fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
+       fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
+       fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
+
+       fprintf(f, "%013lld", totais_get(dec, "BENSANTERIOR")); /* total bens ano anterior */
+       fprintf(f, "%013lld", totais_get(dec, "BENS")); /* total bens ano base */
+       fprintf(f, "%013lld", 0); /* TODO: total dívidas ano anterior */
+       fprintf(f, "%013lld", 0); /* TODO: total dívidas ano base */
+       if (dec->ano == 2015) {
+               fprintf(f, "%013lld", dec->conjuge.total); /* conjuge */
+       } else if (dec->ano >= 2016) {
+               fprintf(f, "%013lld", 0); /* FILLER */
+       }
+       fprintf(f, "%013lld", totais_get(dec, "ISENTOS")); /* rendimentos isentos */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS")); /* rendimentos tributação exclusiva */
+       fprintf(f, "%013lld", 0); /* TODO: imposto ganhos de capital */
+       fprintf(f, "%013lld", 0); /* TODO: retido fonte Lei 11.033 */
+       fprintf(f, "%013lld", 0); /* TODO: imposto renda variável */
+
+       fprintf(f, "%013lld", 0); /* TODO: rendimento PJ dependente */
+       fprintf(f, "%013lld", 0); /* TODO: imposto fonte dependente */
+       fprintf(f, "%013lld", 0); /* TODO: imposto moeda estrangeira */
+       fprintf(f, "%013lld", 0); /* TODO: imposto ganhos capital moeda */
+       fprintf(f, "%013lld", totais_get(dec, "ISENTOSTIT")); /* rendimentos isentos titular */
+       fprintf(f, "%013lld", totais_get(dec, "ISENTOSDEP")); /* rendimentos isentos dependentes */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSTIT")); /* TODO: tributação exclusiva titular */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOSDEP")); /* tributação exclusiva dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: doações campanha */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos PF exigibilidade suspensa dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa titular */
+       fprintf(f, "%013lld", 0); /* TODO: depósitos judiciais exigibilidade suspensa dependentes */
+
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: previdencia RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: pensao RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: IRF RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: previdencia RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: pensao RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
+
+       fprintf(f, "%013lld", 0); /* TODO: imposto diferido ganho capital */
+       fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital */
+       fprintf(f, "%013lld", 0); /* TODO: imposto ganho líquido renda variável */
+       fprintf(f, "%013lld", 0); /* TODO: imposto devido ganho capital moeda estrangeira */
+       if (dec->ano >= 2018) {
+               fprintf(f, "%05lld", dec->aliquota_efetiva);
+       }
+}
+
+static void gera_isentos(struct declaracao *dec, FILE *f)
+{
+       fprintf(f, "23");
+       fprintf(f, "%-11.11s", dec->cpf);
+       fprintf(f, "%013lld", 0); /* TODO: bolsa de estudo */
+       fprintf(f, "%013lld", 0); /* TODO: pecúlio de previdência privada */
+       fprintf(f, "%013lld", totais_get(dec, "INDENIZACOES")); /* FGTS, aviso prévio indenizado */
+       fprintf(f, "%013lld", 0); /* TODO: ganho de capital isento */
+       fprintf(f, "%013lld", 0); /* TODO: lucros e dividendos */
+       fprintf(f, "%013lld", 0); /* TODO: atividade rural */
+       fprintf(f, "%013lld", 0); /* TODO: contribuintes com 65 anos ou mais */
+       fprintf(f, "%013lld", 0); /* TODO: pensão por invalidez */
+       fprintf(f, "%013lld", totais_get(dec, "POUPANCA"));
+       fprintf(f, "%013lld", 0); /* TODO: sócio ou titular de empresa */
+       fprintf(f, "%013lld", totais_get(dec, "DOACOES")); /* herança, transferências patrimoniais */
+       fprintf(f, "%013lld", 0); /* TODO: outros rendimentos isentos */
+       fprintf(f, "%-60.60s", ""); /* FILLER1 */
+       fprintf(f, "%-13.13s", ""); /* FILLER2 */
+       fprintf(f, "%013lld", 0); /* TODO: alienação bens pequeno valor */
+       fprintf(f, "%013lld", 0); /* TODO: alienação único imóvel */
+       fprintf(f, "%013lld", 0); /* TODO: redução ganho capital */
+       fprintf(f, "%013lld", 0); /* TODO: total bens pequeno valor, transportado GC */
+       fprintf(f, "%013lld", 0); /* TODO: alienção único imóvel, transportado GC */
+       fprintf(f, "%013lld", 0); /* TODO: redução ganho capital, transportado GC */
+       fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira */
+       fprintf(f, "%013lld", 0); /* TODO: ganho capital - moeda estrangeira, transportado */
+       fprintf(f, "%013lld", 0); /* TODO: GC total informado */
+       fprintf(f, "%013lld", 0); /* TODO: GC total transportado */
+       fprintf(f, "%013lld", 0); /* TODO: imposto renda anos anteriores */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos assalariados moeda estrangeira */
+       fprintf(f, "%013lld", 0); /* TODO: bonificações ações */
+       fprintf(f, "%013lld", 0); /* TODO: médicos residentes */
+       fprintf(f, "%013lld", 0); /* TODO: volutários da Copa */
+       fprintf(f, "%013lld", 0); /* TODO: meação e dissolução */
+       fprintf(f, "%013lld", 0); /* TODO: ganhos líquidos com ações */
+       fprintf(f, "%013lld", 0); /* TODO: ganhos de capital com ouro */
+       fprintf(f, "%013lld", 0); /* TODO: recuperação prejuízos na bolsa */
+       fprintf(f, "%013lld", 0); /* TODO: transportador de cargas */
+       fprintf(f, "%013lld", 0); /* TODO: transportador de passageiros */
+       fprintf(f, "%013lld", 0); /* TODO: retistuição imposto anos anteriores */
+}
+
+static void gera_isentos2(struct declaracao *dec, FILE *f, int codigo, char *nome)
+{
+       long long total = totais_get(dec, nome);
+       if (total == 0)
+               return;
+       fprintf(f, "23");
+       fprintf(f, "%-11.11s", dec->cpf);
+       fprintf(f, "%04d", codigo);
+       fprintf(f, "%013lld", total);
+}
+
+static void gera_23_poupanca(struct declaracao *dec, FILE *f)
+{
+       gera_isentos2(dec, f, 12, "POUPANCA");
+}
+
+static void gera_23_lucrome(struct declaracao *dec, FILE *f)
+{
+       gera_isentos2(dec, f, 13, "LUCROME");
+}
+
+static void gera_23_outrosisentos(struct declaracao *dec, FILE *f)
+{
+       gera_isentos2(dec, f, 26, "OUTROSISENTOS");
+}
+
+static void gera_exclusivos(struct declaracao *dec, FILE *f)
+{
+       fprintf(f, "24");
+       fprintf(f, "%-11.11s", dec->cpf);
+       fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
+       fprintf(f, "%013lld", 0); /* TODO: ganho de capital */
+       fprintf(f, "%013lld", 0); /* TODO: ganho líquido renda variável */
+       fprintf(f, "%013lld", totais_get(dec, "APLICACOES")); /* TODO: aplicações financeiras */
+       fprintf(f, "%013lld", 0); /* TODO: outros */
+       fprintf(f, "%-60.60s", ""); /* FILLER1 */
+       fprintf(f, "%013lld", 0); /* TODO: ganhos de capital alienação de bens */
+       fprintf(f, "%013lld", 0); /* TODO: ganhos de capital moeda estrangeira */
+       fprintf(f, "%013lld", 0); /* TODO: décimo terceiro dependentes */
+       fprintf(f, "%-13.13s", ""); /* FILLER2 */
+       fprintf(f, "%-60.60s", ""); /* FILLER3 */
+       fprintf(f, "%013lld", 0); /* TODO: RRA */
+       fprintf(f, "%013lld", 0); /* TODO: RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: Juros capital próprio */
+       fprintf(f, "%013lld", totais_get(dec, "PLR"));
+}
+
+static void gera_exclusivos2(struct declaracao *dec, FILE *f, int codigo, char *nome)
+{
+       long long total = totais_get(dec, nome);
+       if (total == 0)
+               return;
+       fprintf(f, "24");
+       fprintf(f, "%-11.11s", dec->cpf);
+       fprintf(f, "%04d", codigo);
+       fprintf(f, "%013lld", total); /* TODO: retistuição imposto anos anteriores */
+}
+
+static void gera_24_decimoterceiro(struct declaracao *dec, FILE *f)
+{
+       gera_exclusivos2(dec, f, 1, "DECIMOTERCEIRO");
+}
+
+static void gera_24_aplicacoes(struct declaracao *dec, FILE *f)
+{
+       gera_exclusivos2(dec, f, 6, "APLICACOES");
+}
+
+static void gera_24_plr(struct declaracao *dec, FILE *f)
+{
+       gera_exclusivos2(dec, f, 11, "PLR");
+}
+
+static void gera_conjuge(struct declaracao *dec, FILE *f)
+{
+       fprintf(f, "29");
+       fprintf(f, "%-11.11s", dec->cpf);
+       fprintf(f, "%-11.11s", dec->conjuge.cpf);
+       fprintf(f, "%013lld", dec->conjuge.base);
+       fprintf(f, "%013lld", dec->conjuge.imposto);
+       fprintf(f, "%013lld", dec->conjuge.isento);
+       fprintf(f, "%013lld", dec->conjuge.exclusivo);
+       fprintf(f, "%013lld", dec->conjuge.rendpj_exigibilidade_suspensa);
+       fprintf(f, "%013lld", dec->conjuge.total);
+       fprintf(f, "%c", dec->conjuge.entregou ? 'S' : 'N');
+}
+
+static int is_trailler_filler(int ano, int i)
+{
+       if (ano == 2018) {
+               return i == 29 || i == 31 || i == 33 || i == 36 || i == 37 || i == 44 || i == 82;
+       }
+#if 0
+       if (ano == 2019) {
+               return i == 57 || (i >= 76 && i <= 79);
+       }
+#endif
+       return (ano <= 2018 && i == 44);
+       /* Ano 2016, linha 29 é um FILLER, mas preenchida com múltiplos
+        * 0s. Como esta linha não é gerada na declaração de 2016, não
+        * deve constar aqui, e será contabilizada como 0. */
+       /* O mesmo vale para as linhas de 2019 comentadas acima. */
+       /* || (ano == 2016 && i == 29); */
+}
+
+static int is_trailler_spaces(int ano, int i)
+{
+       return (ano == 2018 && i > 92);
+}
+
+static int is_trailler_empty(int ano, int i)
+{
+       return
+               (ano == 2015 && i == 49) ||
+               (ano <= 2018 &&
+                       (i == 57 || i == 64 || i == 79));
 }
 
 static void gera_trailler(struct declaracao *dec, FILE *f)
@@ -327,15 +696,18 @@ static void gera_trailler(struct declaracao *dec, FILE *f)
        fprintf(f, "T9");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        fprintf(f, "%06d", dec->linhas[0]);
-       for (i = 16; i < 100; i++)
-               if (i == 44)
+       for (i = 16; i < 100; i++) {
+               if (is_trailler_filler(dec->ano, i))
                        fprintf(f, "%-5.5s", "0"); /* FILLER */
-               else if (i == 49 || i == 57 || i == 64 || i == 79)
+               else if (is_trailler_spaces(dec->ano, i))
+                       fprintf(f, "%-5.5s", "");
+               else if (is_trailler_empty(dec->ano, i))
                        ;
+               else if (dec->ano == 2018 && i == 92)
+                       fprintf(f, "%-5s", "0");
                else
                        fprintf(f, "%05d", dec->linhas[i]);
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       }
 }
 
 static void gera_reciboheader(struct declaracao *dec, FILE *f)
@@ -343,8 +715,6 @@ static void gera_reciboheader(struct declaracao *dec, FILE *f)
        fprintf(f, "HR");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        fprintf(f, "%-3.3s", ""); /* FILLER */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
 }
 
 static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
@@ -357,7 +727,7 @@ static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
        fprintf(f, "%-15.15s", dec->contribuinte.tipo_logradouro);
        fprintf(f, "%-40.40s", dec->contribuinte.logradouro);
        fprintf(f, "%-6.6s", dec->contribuinte.numero);
-       fprintf(f, "%-21.21s", dec->contribuinte.complemento);
+       fprintf(f, "%-21.21s", dec->contribuinte.complemento ?: "");
        fprintf(f, "%-19.19s", dec->contribuinte.bairro);
        fprintf(f, "%-9.9s", dec->contribuinte.cep);
        fprintf(f, "%04d", dec->contribuinte.cd_municipio);
@@ -366,25 +736,35 @@ static void gera_recibodetalhe(struct declaracao *dec, FILE *f)
        fprintf(f, "%-100.100s", ""); /* FILLER */
        fprintf(f, "%-4.4s", ""); /* FILLER */
        fprintf(f, "%-8.8s", ""); /* FILLER */
-       fprintf(f, "%-4.4s", dec->contribuinte.ddd);
-       fprintf(f, "%-9.9s", dec->contribuinte.telefone);
+       if (dec->ano >= 2020) {
+               fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
+               fprintf(f, "%-9.9s", "");
+       } else if (dec->ano >= 2018) {
+               fprintf(f, "%-13.13s", "");
+       } else {
+               fprintf(f, "%-4.4s", dec->contribuinte.ddd ?: "");
+               fprintf(f, "%-9.9s", dec->contribuinte.telefone ?: "");
+       }
        fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
-       fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
+       fprintf(f, "%013lld", totais_get(dec, "RENDTRIB")); /* Total tributavel */
        fprintf(f, "%013lld", dec->devido); /* Imposto devido */
        fprintf(f, "%013lld", dec->restituicao); /* Imposto a restituir */
        fprintf(f, "%013lld", dec->pagar); /* Imposto a pagar */
-       fprintf(f, "%d", 0); /* TODO: quotas */
-       fprintf(f, "%013lld", 0); /* TODO: valor quota */
-       fprintf(f, "%-3.3s", dec->banco); /* numero banco */
-       fprintf(f, "%-4.4s", dec->agencia); /* numero agencia */
+       fprintf(f, "%d", dec->pagar ? 1 : 0); /* TODO/FIXME: quotas */
+       fprintf(f, "%013lld", dec->pagar); /* TODO: valor quota */
+       fprintf(f, "%-3.3s", dec->banco ? : "000"); /* numero banco */
+       fprintf(f, "%-4.4s", dec->agencia ? : "0000"); /* numero agencia */
        fprintf(f, " "); /* FILLER */
        fprintf(f, "%d", 0); /* TODO: debito primeira quota */
        fprintf(f, "%013lld", 0); /* TODO: imposto pago ganho de capital */
-       fprintf(f, "%-13.13s", dec->contacorrente); /* numero conta */
-       fprintf(f, "%-2.2s", dec->dvconta); /* DV conta */
+       fprintf(f, "%-13.13s", dec->contacorrente ? : ""); /* numero conta */
+       fprintf(f, "%-2.2s", dec->dvconta ? : ""); /* DV conta */
        fprintf(f, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       if (dec->ano >= 2020) {
+               fprintf(f, "%-11.11s", dec->contribuinte.telefone ?: "");
+       } else if (dec->ano >= 2018) {
+               fprintf(f, "%-2.2s%-9.9s", dec->contribuinte.ddd ?: "", dec->contribuinte.telefone ?: "");
+       }
 }
 
 static void gera_recibotrailler(struct declaracao *dec, FILE *f)
@@ -392,9 +772,7 @@ static void gera_recibotrailler(struct declaracao *dec, FILE *f)
        fprintf(f, "R9");
        fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
        fprintf(f, "%-3.3s", ""); /* FILLER */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: hash */
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       fprintf(f, "%010u", dec->rhash);
 }
 
 static void gera_rendimento(struct declaracao *dec, FILE *f)
@@ -411,8 +789,6 @@ static void gera_rendimento(struct declaracao *dec, FILE *f)
        fprintf(f, "%013lld", r->imposto);
        fprintf(f, "%-8.8s", r->saida);
        fprintf(f, "%013lld", r->imposto_13o);
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
 }
 
 static void gera_pagamento(struct declaracao *dec, FILE *f)
@@ -422,95 +798,432 @@ static void gera_pagamento(struct declaracao *dec, FILE *f)
        fprintf(f, "26");
        fprintf(f, "%s", dec->cpf);
        fprintf(f, "%02d", p->codigo);
-       fprintf(f, "%05d", 0); /* TODO: chave dependente */
+       fprintf(f, "%05d", p->dependente);
        fprintf(f, "%-14.14s", p->cnpj);
        fprintf(f, "%-60.60s", p->nome);
        fprintf(f, "%-11.11s", ""); /* TODO: NIT */
        fprintf(f, "%013lld", p->pagamento);
        fprintf(f, "%013lld", p->reembolso);
-       /* CPF (1?) ou CNPJ (2), FIXME */
-       fprintf(f, "2");
-       /* Titular (T), Dependente (D), Alimentando (A), FIXME */
-       fprintf(f, "T");
-       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
-       fprintf(f, "\r\n");
+       if (dec->ano >= 2016) {
+               /* TODO: contribuição do ente público patrocinador (FUNPRESP?) */
+               fprintf(f, "%013lld", 0);
+       }
+       fprintf(f, "%d", strlen(p->cnpj) == 11 ? 1 : 2);
+       /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
+       fprintf(f, "%c", p->dependente ? 'D' : 'T');
+}
+
+static void gera_isento(struct declaracao *dec, FILE *f, int codigo)
+{
+       struct isento *i;
+       i = isento_get(dec, codigo, dec->linhas[codigo]);
+       fprintf(f, "%02d", codigo);
+       fprintf(f, "%-11.11s", dec->cpf); /* Titular */
+       fprintf(f, "%05d", dec->linhas[codigo] + 1); /* Chave */
+       /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
+       fprintf(f, "%c", i->dependente ? 'D' : 'T');
+       fprintf(f, "%-14.14s", i->cnpj);
+       fprintf(f, "%-60.60s", i->nome);
+       fprintf(f, "%013lld", i->valor);
+       if (i->dependente) {
+               struct dependente *d;
+               d = list_get(dec->dependentes, i->dependente - 1);
+               fprintf(f, "%-11.11s", d ? d->cpf : "");
+       } else {
+               fprintf(f, "%-11.11s", dec->cpf);
+       }
+}
+
+static void gera_isento2(struct declaracao *dec, FILE *f, int codigo,
+                       int subcodigo, int codigoreal)
+{
+       struct isento *i;
+       i = dec->ctx;
+       fprintf(f, "%02d", codigoreal);
+       fprintf(f, "%-11.11s", dec->cpf); /* Titular */
+       /* Titular (T), Dependente (D), Alimentando (A), FIXME Alimentando */
+       fprintf(f, "%c", i->dependente ? 'D' : 'T');
+       if (i->dependente) {
+               struct dependente *d;
+               d = list_get(dec->dependentes, i->dependente - 1);
+               fprintf(f, "%-11.11s", d ? d->cpf : "");
+       } else {
+               fprintf(f, "%-11.11s", dec->cpf);
+       }
+       fprintf(f, "%04d", subcodigo);
+       fprintf(f, "%-14.14s", i->cnpj);
+       fprintf(f, "%-60.60s", i->nome);
+       fprintf(f, "%013lld", i->valor);
+}
+
+static void gera_doacao(struct declaracao *dec, FILE *f)
+{
+       gera_isento(dec, f, 82);
+}
+
+static void gera_indenizacoes(struct declaracao *dec, FILE *f)
+{
+       gera_isento(dec, f, 93);
+}
+
+static void gera_plr(struct declaracao *dec, FILE *f)
+{
+       gera_isento(dec, f, 96);
+}
+
+static void gera_plr2(struct declaracao *dec, FILE *f)
+{
+       gera_isento2(dec, f, 11, 11, 88);
 }
 
+static void gera_lucrome2(struct declaracao *dec, FILE *f)
+{
+       gera_isento2(dec, f, 13, 13, 84);
+}
+
+static void gera_outrosisentos(struct declaracao *dec, FILE *f)
+{
+       struct isento *i;
+       int codigo = 97;
+       i = isento_get(dec, codigo, dec->linhas[codigo]);
+       gera_isento(dec, f, codigo);
+       fprintf(f, "%d", i->exclusivo == 0 ? 1 : 2);
+       fprintf(f, "%-60.60s", i->descricao);
+}
+
+static void gera_outrosisentos2(struct declaracao *dec, FILE *f)
+{
+       struct isento *i;
+       i = dec->ctx;
+       gera_isento2(dec, f, 26, 26, 86);
+       fprintf(f, "%-60.60s", i->descricao);
+}
+
+static void gera_poupanca(struct declaracao *dec, FILE *f)
+{
+       gera_isento(dec, f, 98);
+}
+
+static void gera_poupanca2(struct declaracao *dec, FILE *f)
+{
+       gera_isento2(dec, f, 12, 12, 84);
+}
+
+static void gera_aplicacoes(struct declaracao *dec, FILE *f)
+{
+       gera_isento(dec, f, 99);
+}
+
+static void gera_aplicacoes2(struct declaracao *dec, FILE *f)
+{
+       gera_isento2(dec, f, 6, 6, 88);
+}
+
+static void gera_dependente(struct declaracao *dec, FILE *f)
+{
+       struct dependente *d;
+       d = list_get(dec->dependentes, dec->linhas[25]);
+
+       fprintf(f, "25");
+       fprintf(f, "%s", dec->cpf);
+       fprintf(f, "%05d", dec->linhas[25] + 1);
+       fprintf(f, "%02d", d->codigo);
+       fprintf(f, "%-60.60s", d->nome);
+       fprintf(f, "%-8.8s", d->dn);
+       fprintf(f, "%-11.11s", d->cpf);
+       /* TODO: Indicador de saída */
+       fprintf(f, " ");
+       if (dec->ano >= 2016) {
+               /* TODO: NIT/PIS/PASEP de Pessoa Física no exterior */
+               fprintf(f, "%-11.11s", "");
+       }
+}
+
+static void gera_bem(struct declaracao *dec, FILE *f)
+{
+       struct bem *b;
+       b = list_get(dec->bens, dec->linhas[27]);
+
+       fprintf(f, "27");
+       fprintf(f, "%s", dec->cpf);
+       fprintf(f, "%02d", b->codigo);
+
+       /* FIXME: exterior */
+       fprintf(f, "0");
+       fprintf(f, "105"); /* código Brasil */
+
+       fprintf(f, "%-512.512s", b->descricao);
+       fprintf(f, "%013lld", b->valor_anterior);
+       fprintf(f, "%013lld", b->valor);
+
+       /* Imóvel */
+       attr_out(f, b->attr, "logradouro", 40);
+       attr_out(f, b->attr, "numero", 6);
+       attr_out(f, b->attr, "complemento", 40);
+       attr_out(f, b->attr, "bairro", 40);
+       attr_out(f, b->attr, "cep", 9);
+       attr_out(f, b->attr, "uf", 2);
+       attr_out(f, b->attr, "cd_municipio", 4);
+       attr_out(f, b->attr, "municipio", 40);
+       /* FIXME: Registro de imóveis, Nao (0), Sim (1), Vazio (2) */
+       fprintf(f, "%d", attr_get(b->attr, "registro") ? 1 : 2);
+       attr_out(f, b->attr, "matricula", 40);
+       attr_out(f, b->attr, "registro", 40);
+       attr_out(f, b->attr, "area", 11);
+       /* FIXME: Area, M2 (0), Ha (1), Vazio (2) */
+       fprintf(f, "%d", attr_get(b->attr, "area") ? 0 : 2);
+       attr_out(f, b->attr, "cartorio", 60);
+
+       /* Número de chave */
+       fprintf(f, "%05d", dec->linhas[27] + 1);
+
+       /* Mudanças 2018 */
+       if (dec->ano >= 2018) {
+               fprintf(f, "%-8.8s", "00000000"); /* TODO: Data de aquisição */
+               fprintf(f, "%-20.20s", ""); /* TODO: IPTU, 2019, filler */
+               fprintf(f, "%-8.8s", "00000000"); /* TODO: NIRF */
+               fprintf(f, "%-30.30s", ""); /* TODO: RENAVAN */
+               fprintf(f, "%-30.30s", ""); /* TODO: Registro aviação civil */
+               fprintf(f, "%-30.30s", ""); /* TODO: Registro Capitania dos Portos */
+               fprintf(f, "%04d", 0); /* TODO: Agência bancária */
+               fprintf(f, "%-15.15s", ""); /* TODO: Conta bancária e dígito verificador */
+               fprintf(f, "%-14.14s", ""); /* TODO: CPF ou CNPJ */
+       }
+
+       if (dec->ano >= 2019) {
+               attr_out(f, b->attr, "iptu", 30);
+       }
+}
+
+static void gera_carne(struct declaracao *dec, FILE *f)
+{
+       struct carne *carne;
+       carne = list_get(dec->carne, dec->linhas[22]);
+       fprintf(f, "22");
+       fprintf(f, "%-11.11s", dec->cpf); /* Titular */
+       if (carne->dependente) {
+               struct dependente *d;
+               d = list_get(dec->dependentes, carne->dependente - 1);
+               fprintf(f, "S%-11.11s", d ? d->cpf : ""); /* CPF dependente. */
+       } else {
+               fprintf(f, "N%-11.11s", ""); /* Não é dependente. */
+       }
+       fprintf(f, "%02d", carne->mes);
+       fprintf(f, "%013lld", carne->rendimento);
+       fprintf(f, "%013lld", carne->alugueis); /* Aluguéis. */
+       fprintf(f, "%013lld", carne->outros); /* Outros. */
+       fprintf(f, "%013lld", carne->exterior); /* Exterior. */
+       fprintf(f, "%013lld", carne->caixa); /* Livro-caixa. */
+       fprintf(f, "%013lld", carne->alimentos); /* Pensão alimentícia. */
+       fprintf(f, "%013lld", carne->dependentes); /* Dedução com dependentes. */
+       fprintf(f, "%013lld", carne->previdencia); /* Previdência. */
+       fprintf(f, "%013lld", carne->base); /* Base cálculo. */
+       fprintf(f, "%013lld", carne->imposto); /* Imposto pago. */
+}
 
 typedef void (gera_linha)(struct declaracao *dec, FILE *f);
 
-static int wrap(gera_linha fn, struct declaracao *dec, FILE *f)
+static void update_hash(struct declaracao *dec, char *buf, size_t len)
+{
+       int r;
+       int linha;
+       r = sscanf(buf, "%2d", &linha);
+       if (r == 1 || !strncmp(buf, "T9", 2)) {
+               dec->hash = crc32(dec->hash, buf, len - 2);
+               dec->rhash = crc32(dec->rhash, buf, len - 2);
+               return;
+       } else if (strncmp(buf, "R9", 2) && strncmp(buf, "IRPF", 4)) {
+               dec->rhash = crc32(dec->rhash, buf, len - 2);
+       }
+}
+
+static int wrap(gera_linha fn, struct declaracao *dec, struct list *l)
 {
        FILE *m;
        char *buf = NULL;
        size_t bsize;
        int linha;
        int r;
+       uLong c = crc32(0L, Z_NULL, 0);
        m = open_memstream(&buf, &bsize);
        if (!m) {
                return -errno;
        }
        fn(dec, m);
+       fflush(m);
+       if (bsize == 0) {
+               fclose(m);
+               return 0;
+       }
        dec->linhas[0]++;
+
+       /* Calcula CRC32 para campo de controle dos registros. */
+       c = crc32(c, buf, bsize);
+       fprintf(m, "%010ld\r\n", c);
+
        fclose(m);
        r = sscanf(buf, "%2d", &linha);
        if (r == 1 && linha >= 0 && linha < 100) {
                dec->linhas[linha]++;
        }
-       fwrite(buf, bsize, 1, f);
-       free(buf);
-       return 0;
+       update_hash(dec, buf, bsize);
+       return list_add(&l, buf);
+}
+
+static void insert_hash(struct declaracao *dec, char *irpf)
+{
+       uLong c = crc32(0L, NULL, 0);
+       char cpf[13];
+       char crc[11];
+       snprintf(cpf, 13, "%-8.8s.DEC", dec->cpf);
+       c = crc32(c, cpf, 12);
+       snprintf(crc, 11, "%010ld", dec->hash);
+       memcpy(irpf + 101, crc, 10);
+       c = crc32(c, irpf, strlen(irpf) - 12);
+       snprintf(crc, 11, "%010ld", c);
+       memcpy(irpf + strlen(irpf) - 12, crc, 10);
 }
 
 static int gera(struct declaracao *dec, char *filename)
 {
        FILE *f;
-       int r;
+       int r = 0;
        int i;
        struct rendimento *rendimento;
+       struct carne *carne;
+       struct isento *isento;
        struct pagamento *pagamento;
+       struct bem *bem;
+       struct dependente *dependente;
+       struct list *linhas;
+       char *buf;
+
+       linhas = list_new();
+       if (!linhas)
+               return -ENOMEM;
 
-#define W(fn, dec, f) \
+       dec->hash = crc32(0L, NULL, 0);
+       dec->rhash = crc32(0L, NULL, 0);
+
+#define W(fn) \
        do { \
-               r = wrap(fn, dec, f); \
+               r = wrap(fn, dec, linhas); \
                if (r < 0) \
                        goto out; \
        } while (0);
 
        f = fopen(filename, "w");
-       if (!f)
-               return -errno;
+       if (!f) {
+               r = -errno;
+               dec_set_error(dec, "Não foi possível abrir arquivo %s: %s.",
+                             filename, strerror(errno));
+               goto out_file;
+       }
        memset(dec->linhas, 0, sizeof(dec->linhas));
-       W(gera_header, dec, f);
-       W(gera_contribuinte, dec, f);
+       W(gera_header);
+       W(gera_contribuinte);
        if (dec->tipo == COMPLETA) {
-               W(gera_completa, dec, f);
-               W(gera_totais_completa, dec, f);
+               W(gera_completa);
+               W(gera_totais_completa);
        } else {
-               W(gera_simples, dec, f);
-               W(gera_totais_simples, dec, f);
+               W(gera_simples);
+               W(gera_totais_simples);
        }
        for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
-               W(gera_rendimento, dec, f);
+               W(gera_rendimento);
+       }
+
+       for (i = 0; (carne = list_get(dec->carne, i)); i++) {
+               W(gera_carne);
+       }
+
+       if (dec->ano <= 2017) {
+               if (totais_get(dec, "ISENTOS"))
+                       W(gera_isentos);
+               if (totais_get(dec, "EXCLUSIVOS"))
+                       W(gera_exclusivos);
+       } else {
+               W(gera_23_poupanca);
+               W(gera_23_lucrome);
+               W(gera_23_outrosisentos);
+               W(gera_24_decimoterceiro);
+               W(gera_24_aplicacoes);
+               W(gera_24_plr);
+       }
+
+       for (i = 0; (dependente = list_get(dec->dependentes, i)); i++) {
+               W(gera_dependente);
        }
        for (i = 0; (pagamento = list_get(dec->pagamentos, i)); i++) {
-               W(gera_pagamento, dec, f);
+               W(gera_pagamento);
        }
-       W(gera_trailler, dec, f);
-       W(gera_reciboheader, dec, f);
-       W(gera_recibodetalhe, dec, f);
-       W(gera_recibotrailler, dec, f);
+       for (i = 0; (bem = list_get(dec->bens, i)); i++) {
+               W(gera_bem);
+       }
+
+       if (dec->ano == 2015 && dec->conjuge.cpf)
+               W(gera_conjuge);
+
+       /* Rendimentos isentos e com tributação exclusiva */
+       /* Registros 82 a 89, e 92 a 99 */
+#define IW(fn, codigo) \
+       for (i = 0; ; i++) { \
+               isento = isento_get(dec, codigo, i); \
+               if (!isento) \
+                       break; \
+               dec->ctx = isento; \
+               W(fn); \
+       }
+       if (dec->ano <= 2017) {
+               IW(gera_doacao, 82);
+               IW(gera_indenizacoes, 93);
+               IW(gera_plr, 96);
+               IW(gera_outrosisentos, 97);
+               IW(gera_poupanca, 98);
+               IW(gera_aplicacoes, 99);
+       } else {
+               IW(gera_poupanca2, 12);
+               //dec->linhas[12] = 0;
+               IW(gera_lucrome2, 13);
+               IW(gera_outrosisentos2, 26);
+               IW(gera_aplicacoes2, 6);
+               //dec->linhas[99] = 0;
+               IW(gera_plr2, 11);
+               //dec->linhas[96] = 0;
+       }
+
+       W(gera_trailler);
+       W(gera_reciboheader);
+       W(gera_recibodetalhe);
+       W(gera_recibotrailler);
+
+       insert_hash(dec, list_get(linhas, 0));
+       for (i = 0; (buf = list_get(linhas, i)); i++) {
+               fwrite(buf, strlen(buf), 1, f);
+       }
+
        fclose(f);
+       list_free(linhas, free);
        return 0;
 out:
        fclose(f);
+out_file:
+       list_free(linhas, free);
        return r;
 }
 
 static int run_gera(struct declaracao *dec, char **args, int argc)
 {
-       if (argc != 2)
+       if (argc != 2) {
+               dec_set_error(dec, "Comando %s recebe um nome de arquivo como parâmetro.",
+                             args[0]);
                return -EINVAL;
+       }
+       if (!ANO_VALIDO(dec->ano)) {
+               dec_set_error(dec, "Comando %s não suporta ano %d.",
+                             args[0], dec->ano);
+               return -EINVAL;
+       }
        return gera(dec, args[1]);
 }