Calcula e gera desconto simplificado e base de cálculo.
[cascardo/declara.git] / gera.c
diff --git a/gera.c b/gera.c
index 202a078..ce8c432 100644 (file)
--- a/gera.c
+++ b/gera.c
@@ -22,6 +22,9 @@
 #include "rendimento.h"
 #include <errno.h>
 #include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "totais.h"
 
 static void gera_header(struct declaracao *dec, FILE *f)
 {
@@ -40,30 +43,35 @@ static void gera_header(struct declaracao *dec, FILE *f)
        fprintf(f, "1"); /* TODO: certificavel */
        fprintf(f, "%s", dec->contribuinte.dn);
        fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
-       fprintf(f, "0"); /* TODO: resultado imposto */
+       fprintf(f, "%s", dec->restituicao ? "2" : "0"); /* TODO: resultado imposto, 2 - restituicao */
        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, "%-10.10s", dec->retifica ? : ""); /* TODO: recibo da última declaração transmitida (recibo ou retifica?) */
+       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, "0"); /* TODO: obrigatoria entrega */
-       fprintf(f, "0000000000000"); /* TODO: imposto devido, carne-leao, complementar dos dependentes */
-       fprintf(f, "%-10.10s", dec->recibo); /* recibo ex. anterior */
-       fprintf(f, "2"); /* TODO: indicador seguranca */
-       fprintf(f, "00"); /* TODO: indicador imposto pago */
-       fprintf(f, "0"); /* TODO: indicador imposto antecipado */
+       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 */
+       /* Indicador de segurança: 0 se retificadora, 2 se recibo
+        * 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);
+       /* 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, "0"); /* TODO: debito 1a quota */
-       fprintf(f, "000"); /* TODO: no banco */
-       fprintf(f, "0000"); /* TODO: agencia */
+       fprintf(f, "%-3.3s", dec->banco); /* no banco */
+       fprintf(f, "%-4.4s", dec->agencia); /* agencia */
        fprintf(f, " "); /* TODO: filler */
        fprintf(f, "00000000"); /* transito julgado, gravado apenas se espolio */
-       fprintf(f, "0000000000000"); /* TODO: imposto a pagar */
+       fprintf(f, "%013lld", dec->pagar); /* imposto a pagar */
        fprintf(f, " "); /* RRA1 */
        fprintf(f, "%-11.11s", ""); /* CPF RRA1 */
        fprintf(f, " "); /* RRA2 */
@@ -73,10 +81,10 @@ 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", ""); /* TODO: CNPJ maior */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior 2 */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior 3 */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ maior 4 */
+       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 */
@@ -89,8 +97,10 @@ static void gera_header(struct declaracao *dec, FILE *f)
        fprintf(f, "%-8.8s", ""); /* DN Dependente 5 */
        fprintf(f, "%-11.11s", ""); /* CPF Dependente 6 */
        fprintf(f, "%-8.8s", ""); /* DN Dependente 6 */
-       fprintf(f, "%-14.14s", ""); /* TODO: medico maior */
-       fprintf(f, "%-14.14s", ""); /* TODO: medico maior 2 */
+       /* medico maior, TODO: outros códigos */
+       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 0));
+       /* medico maior 2, TODO: outros códigos */
+       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 26, 1));
        fprintf(f, "%-11.11s", ""); /* CPF pensao */
        fprintf(f, "%-11.11s", ""); /* CPF inventariante */
        fprintf(f, "%-40.40s", dec->contribuinte.municipio);
@@ -99,20 +109,25 @@ static void gera_header(struct declaracao *dec, FILE *f)
        fprintf(f, "000000000000"); /* FIXME: MAC */
        fprintf(f, "%08d", 0); /* Data saída */
        fprintf(f, "%-11.11s", ""); /* CPF procurador */
-       fprintf(f, "000"); /* TODO: criterio obrigatoriedade */
-       fprintf(f, "%013lld", dec->totalrendimento); /* Total tributavel */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ previdencia */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ previdencia 2 */
-       fprintf(f, "%013lld", 0); /* TODO: Total isentos */
-       fprintf(f, "%013lld", 0); /* TODO: Total exclusivo */
-       fprintf(f, "%013lld", 0); /* TODO: Total pagamentos */
-       fprintf(f, "%-13.13s", ""); /* TODO: numero conta */
-       fprintf(f, "%-2.2s", ""); /* TODO: DV conta */
+       fprintf(f, "%03d", dec->obrigatoria); /* criterio obrigatoriedade */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* Total tributavel */
+       /* CNPJ previdencia */
+       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 0));
+       /* CNPJ previdencia 2 */
+       fprintf(f, "%-14.14s", pagamento_cnpj_ordenado(dec, 36, 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, "0"); /* TODO: revalidar DV conta */
 
        /* Mudanças de 2015 */
 
-       fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* TODO: natureza ocupacao */
+       fprintf(f, "%02d", dec->contribuinte.natureza_ocupacao); /* natureza ocupacao */
        fprintf(f, "%-11.11s", ""); /* CPF domestica */
        fprintf(f, "%-11.11s", ""); /* NI domestica */
        fprintf(f, "%-11.11s", ""); /* CPF domestica 2 */
@@ -168,32 +183,301 @@ static void gera_contribuinte(struct declaracao *dec, FILE *f)
        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", "000"); /* TODO: banco */
-       fprintf(f, "%-4.4s", "0000"); /* TODO: agência */
+       fprintf(f, "%-3.3s", dec->banco); /* banco */
+       fprintf(f, "%-4.4s", dec->agencia); /* agência */
        fprintf(f, "N"); /* TODO: deficiência */
        fprintf(f, "0"); /* FILLER: pré-preenchida */
-       fprintf(f, "%-13.13s", ""); /* TODO: conta */
-       fprintf(f, "%-2.2s", ""); /* TODO: 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 */
-       fprintf(f, "%-14.14s", ""); /* TODO: CNPJ principal fonte */
-       fprintf(f, "%-10.10s", dec->recibo); /* Recibo última declaração ano anterior */
+       /* CNPJ principal fonte */
+       fprintf(f, "%-14.14s", rendimento_cnpj_ordenado(dec, 0));
+       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");
 }
 
+static void gera_simples(struct declaracao *dec, FILE *f)
+{
+       fprintf(f, "17");
+       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 tributação exclusiva, exceto décimo terceiro */
+       fprintf(f, "%013lld", totais_get(dec, "EXCLUSIVOS_SEM_13o"));
+       /* 13o. */
+       fprintf(f, "%013lld", totais_get(dec, "DECIMOTERCEIRO"));
+       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 */
+       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", 0); /* TODO: previdência RRA */
+       fprintf(f, "%013lld", 0); /* TODO: previdência RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: pensão RRA */
+       fprintf(f, "%013lld", 0); /* TODO: pensão RRA dependentes */
+       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 */
+       /* desconto simplificado */
+       fprintf(f, "%013lld", totais_get(dec, "DESCONTO"));
+        /* base de cálculo */
+       fprintf(f, "%013lld", totais_get(dec, "BASE"));
+       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", 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, "%013lld", 0); /* TODO: rendimentos isentos */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos tributação exclusiva */
+       fprintf(f, "%013lld", 0); /* TODO: conjuge */
+       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", 0); /* TODO: rendimento tributável PJ titular */
+       fprintf(f, "%013lld", 0); /* TODO: total rural */
+       fprintf(f, "%013lld", dec->retido); /* imposto retido titular */
+       fprintf(f, "%013lld", 0); /* TODO: total bens ano anterior */
+       fprintf(f, "%013lld", 0); /* TODO: total bens ano base */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos isentos titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos isentos dependentes */
+       fprintf(f, "%013lld", 0); /* 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", 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 */
+       fprintf(f, "%013lld", 0); /* TODO: isentos e não tributáveis */
+       fprintf(f, "%013lld", 0); /* TODO: tributação exclusiva */
+       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", 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: IRF RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: imposto RRA titular */
+       fprintf(f, "%013lld", 0); /* TODO: rendimentos RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: IRF RRA dependentes */
+       fprintf(f, "%013lld", 0); /* TODO: imposto RRA dependentes */
+       fprintf(f, "%013lld", dec->devido); /* imposto devido */
+       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 */
+       fprintf(f, "%013lld", 0); /* TODO: imposto pago exterior */
+       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
+       fprintf(f, "\r\n");
+}
+
+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");
+}
+
+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");
+}
+
+static void gera_trailler(struct declaracao *dec, FILE *f)
+{
+       int i;
+       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)
+                       fprintf(f, "%-5.5s", "0"); /* FILLER */
+               else if (i == 49 || i == 57 || i == 64 || i == 79)
+                       ;
+               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)
+{
+       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)
+{
+       fprintf(f, "DR");
+       fprintf(f, "%s", dec->cpf); /* CPF: 11 dígitos */
+       fprintf(f, "%-3.3s", ""); /* FILLER */
+       fprintf(f, "%s", dec->tipo == COMPLETA ? "S" : "N");
+       fprintf(f, "%-60.60s", dec->nome);
+       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, "%-19.19s", dec->contribuinte.bairro);
+       fprintf(f, "%-9.9s", dec->contribuinte.cep);
+       fprintf(f, "%04d", dec->contribuinte.cd_municipio);
+       fprintf(f, "%-40.40s", dec->contribuinte.municipio);
+       fprintf(f, "%-2.2s", dec->contribuinte.uf);
+       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);
+       fprintf(f, "%s", dec->retifica ? "S" : "N"); /* Retificadora */
+       fprintf(f, "%013lld", totais_get(dec, "RENDPJ")); /* 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, " "); /* 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, "%013lld", 0); /* TODO: imposto alienacao moeda estrangeira em especie */
+       fprintf(f, "%-10.10s", "0000000000"); /* FIXME: controle */
+       fprintf(f, "\r\n");
+}
+
+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");
+}
+
+static void gera_rendimento(struct declaracao *dec, FILE *f)
+{
+       struct rendimento *r;
+       r = list_get(dec->rendimento, dec->linhas[21]);
+       fprintf(f, "21");
+       fprintf(f, "%s", dec->cpf);
+       fprintf(f, "%-14.14s", r->cnpj);
+       fprintf(f, "%-60.60s", r->nome);
+       fprintf(f, "%013lld", r->rendimento);
+       fprintf(f, "%013lld", r->previdencia);
+       fprintf(f, "%013lld", r->decimoterceiro);
+       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");
+}
+
+typedef void (gera_linha)(struct declaracao *dec, FILE *f);
+
+static int wrap(gera_linha fn, struct declaracao *dec, FILE *f)
+{
+       FILE *m;
+       char *buf = NULL;
+       size_t bsize;
+       int linha;
+       int r;
+       m = open_memstream(&buf, &bsize);
+       if (!m) {
+               return -errno;
+       }
+       fn(dec, m);
+       dec->linhas[0]++;
+       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;
+}
+
 static int gera(struct declaracao *dec, char *filename)
 {
        FILE *f;
+       int r;
+       int i;
+       struct rendimento *rendimento;
+
+#define W(fn, dec, f) \
+       do { \
+               r = wrap(fn, dec, f); \
+               if (r < 0) \
+                       goto out; \
+       } while (0);
+
        f = fopen(filename, "w");
        if (!f)
                return -errno;
-       gera_header(dec, f);
-       gera_contribuinte(dec, f);
+       memset(dec->linhas, 0, sizeof(dec->linhas));
+       W(gera_header, dec, f);
+       W(gera_contribuinte, dec, f);
+       if (dec->tipo == COMPLETA) {
+               W(gera_completa, dec, f);
+               W(gera_totais_completa, dec, f);
+       } else {
+               W(gera_simples, dec, f);
+               W(gera_totais_simples, dec, f);
+       }
+       for (i = 0; rendimento = list_get(dec->rendimento, i); i++) {
+               W(gera_rendimento, dec, f);
+       }
+       W(gera_trailler, dec, f);
+       W(gera_reciboheader, dec, f);
+       W(gera_recibodetalhe, dec, f);
+       W(gera_recibotrailler, dec, f);
        fclose(f);
        return 0;
+out:
+       fclose(f);
+       return r;
 }
 
 static int run_gera(struct declaracao *dec, char **args, int argc)