Example usage for org.apache.commons.csv CSVPrinter printRecord

List of usage examples for org.apache.commons.csv CSVPrinter printRecord

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter printRecord.

Prototype

public void printRecord(final Object... values) throws IOException 

Source Link

Document

Prints the given values a single record of delimiter separated values followed by the record separator.

Usage

From source file:com.apkcategorychecker.writer.WriterCSV.java

@Override
public void Write(AnalyzerResult result, String _csvPath, int _counter) {

    try {//from w w  w. j  a va 2  s. com

        ArrayList<AnalyzerResult> resultList = new ArrayList<AnalyzerResult>();
        resultList.add(result);

        /*--Create the CSVFormat object--*/

        CSVFormat format = CSVFormat.DEFAULT.withHeader();

        /*--Writing in a CSV file--*/

        FileWriter _out = new FileWriter(_csvPath, true);
        CSVPrinter printer;
        printer = new CSVPrinter(_out, format.withDelimiter('#'));

        /*--Retrieve APKResult and Write in file--*/

        Iterator<AnalyzerResult> it = resultList.iterator();
        while (it.hasNext()) {
            AnalyzerResult _resultElement = it.next();
            List<String> resultData = new ArrayList<>();
            resultData.add(String.valueOf(_counter));
            resultData.add(_resultElement.get_APKName());
            resultData.add(_resultElement.get_APKPath());
            resultData.add(_resultElement.get_Package());
            resultData.add(_resultElement.get_APKMainFramework());
            resultData.add(_resultElement.get_APKBaseFramework());
            resultData.add(String.valueOf(_resultElement.get_html()));
            resultData.add(String.valueOf(_resultElement.get_js()));
            resultData.add(String.valueOf(_resultElement.get_css()));
            resultData.add(_resultElement.get_debuggable());
            resultData.add(_resultElement.get_permissions());
            resultData.add(_resultElement.get_minSdkVersion());
            resultData.add(_resultElement.get_maxSdkVersion());
            resultData.add(_resultElement.get_targetSdkVersion());
            resultData.add(_resultElement.get_fileSize());
            resultData.add(String.valueOf(_resultElement.get_startAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_durationAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_decodeSuccess()));
            printer.printRecord(resultData);
        }

        /*--Close the printer--*/
        printer.close();
        System.out.println("Record added to CSV file");
        this.removeBlankLines(_csvPath);

    } catch (IOException ex) {
        Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:canreg.client.gui.analysis.FrequenciesByYearInternalFrame.java

public void createPivot(String fileName) {
    String[] columnNames = new String[resultTable.getColumnCount()];

    // We need 3 columns to work with        
    if (columnNames.length != 3) {
        return;//w w w .  j  a  v  a2 s  .c  o  m
    }
    // TODO Extend this to at least 4
    String[] nextLine = new String[resultTable.getColumnCount()];

    // Find the column names
    for (int j = 0; j < columnNames.length; j++) {
        columnNames[j] = resultTable.getColumnName(j);
    }

    // variable we lock
    String lockVariable = columnNames[1];

    HashMap<String, HashMap> data = new HashMap<String, HashMap>();
    HashMap<String, String> years;
    Set<String> allYears = new TreeSet<String>();

    // load up the data
    for (int i = 0; i < resultTable.getRowCount(); i++) {
        String year, cases, code;

        for (int j = 0; j < nextLine.length; j++) {
            nextLine[j] = resultTable.getValueAt(i, j).toString();
        }
        year = nextLine[0];
        if (year.trim().length() == 0) {
            year = "MISSING";
        }

        allYears.add(year);

        code = nextLine[1];

        if (code.trim().length() == 0) {
            code = "MISSING";
        }

        cases = nextLine[2];

        years = data.get(code);
        if (years == null) {
            years = new HashMap<String, String>();
            data.put(code, years);
        }
        years.put(year, cases);
    }

    // find variables element for the lockedvariable
    DatabaseVariablesListElement lockedDatabaseVariablesListElement = null;
    for (DatabaseVariablesListElement vle : chosenVariables) {
        if (vle.getShortName().compareToIgnoreCase(lockVariable) == 0) {
            lockedDatabaseVariablesListElement = vle;
        }
    }

    if (lockedDatabaseVariablesListElement == null) {
        return;
    } // this happens if user has updated the selection of variables

    int dictionaryID = lockedDatabaseVariablesListElement.getDictionaryID();
    Dictionary dict = null;
    if (dictionaryID >= 0) {
        dict = dictionary.get(dictionaryID);
    }

    String[] allYearsArray = allYears.toArray(new String[0]);
    Writer writer = null;
    try {
        writer = new FileWriter(fileName);

        // Write the column names
        String[] codeArray = { lockedDatabaseVariablesListElement.getFullName(), lockVariable };

        String[] headers = (String[]) ArrayUtils.addAll(codeArray, allYearsArray);

        String[] codes = data.keySet().toArray(new String[0]);
        Arrays.sort(codes);

        CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',').withHeader(headers);

        CSVPrinter csvPrinter = new CSVPrinter(writer, format);

        // write the rows    
        for (String code : codes) {
            LinkedList<String> row = new LinkedList<String>();
            if (dict != null) {
                DictionaryEntry dictionaryEntry = dict.getDictionaryEntry(code);
                if (dictionaryEntry != null) {
                    row.add(dictionaryEntry.getDescription());
                } else {
                    row.add("");
                }
            } else {
                row.add("");
            }
            row.add(code);

            years = data.get(code);
            for (String year : allYears) {
                String cell = years.get(year);
                if (cell == null) {
                    row.add("0");
                } else {
                    row.add(cell);
                }
            }
            csvPrinter.printRecord(row);
        }
        csvPrinter.flush();

    } catch (IOException ex) {
        // JOptionPane.showMessageDialog(this, "File NOT written.\n" + ex.getLocalizedMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:gov.usda.DataCatalogClient.Catalog.java

/**
 * Outputs a Catalog into tab delimited format.
 * <p>/* w w  w. ja v a2s.co m*/
 * Begins the process by listing out the header and calling all datasets to create
 * tab delimitted lines.
 * @param filePath String The output file for the catalog tab delimitted file.
 * @param dataListCode DataListingCode This will either print the Public Data Listing or the Enterprise 
 * Data Inventory
 */
public void toCSV(String filePath, DataListingCode dataListingCode) throws IOException {
    Collections.sort(dataSetList);
    if (filePath == null) {
        throw (new NullPointerException("filepath cannot be null"));
    }
    PrintWriter out = null;
    CSVPrinter csvPrinter = null;
    CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    List<String> catalogString = new ArrayList<String>();
    catalogString.add("Agency Name");
    catalogString.add("Title");
    catalogString.add("Description");
    catalogString.add("MediaType");
    catalogString.add("Download URL");
    catalogString.add("Frequency");
    catalogString.add("Bureau Code");
    catalogString.add("Contact Email");
    catalogString.add("Contact Name");
    catalogString.add("Landing Page");
    catalogString.add("Program Code");
    catalogString.add("Publisher");
    catalogString.add("Public Access Level");
    catalogString.add("Access Level Comment");
    catalogString.add("Tags");
    catalogString.add("Last Update");
    catalogString.add("Release Date");
    catalogString.add("Unique Identifier");
    catalogString.add("Data Dictionary");
    catalogString.add("License");
    catalogString.add("Spatial");
    catalogString.add("Temporal");
    catalogString.add("System of Records");
    catalogString.add("Data Quality");
    catalogString.add("Language");
    catalogString.add("Theme");
    catalogString.add("Reference");
    catalogString.add("CKAN Create Date");
    catalogString.add("CKAN Modified Date");
    catalogString.add("CKAN Revision Timestamp");
    catalogString.add("Is Part Of");

    try {
        out = new PrintWriter(filePath);
        csvPrinter = new CSVPrinter(out, csvFormat);
        csvPrinter.printRecord(catalogString);
        for (Dataset ds : dataSetList) {
            if (dataListingCode.equals(DataListingCode.ENTERPRISE_DATA_INVENTORY)) {
                csvPrinter.printRecord(ds.datasetToListString());
            } else if (dataListingCode.equals(DataListingCode.PUBLIC_DATA_LISTING)) {
                if (ds.getAccessLevel().equals(Dataset.AccessLevel.PUBLIC.toString())
                        || ds.getAccessLevel().equals(Dataset.AccessLevel.RESTRICTED)) {
                    csvPrinter.printRecord(ds.datasetToListString());
                }
            }
        }
    } catch (IOException e) {
        throw (e);
    } finally {
        out.close();
        csvPrinter.close();
    }
}

From source file:GUI.MainWindow.java

/**
 * Writes a row of data to a CSV file. For use with exporting CVE data
 * mainly./*from ww  w . j av  a  2 s  .  com*/
 *
 * @param file
 * @param data
 * @param recordSeparator
 * @throws Exception
 */
public void writeCSVLine(File file, String[] data) throws Exception {
    FileWriter writer = new FileWriter(file, true);
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));
    CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat);
    csvFilePrinter.printRecord(data);
    writer.flush();
    writer.close();
    csvFilePrinter.close();
}

From source file:edu.harvard.mcz.imagecapture.RunnableJobReportDialog.java

protected void serializeTableModel() {
    PrintWriter out = null;/*from  w  w  w . j  a v a 2  s.  c om*/
    CSVPrinter writer = null;
    try {
        int cols = jTable.getModel().getColumnCount();
        CSVFormat csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                .withHeaderComments(jTextArea.getText());
        TableModel model = jTable.getModel();
        switch (cols) {
        case 9:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4), model.getColumnName(5),
                            model.getColumnName(6), model.getColumnName(7), model.getColumnName(8))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 6:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4), model.getColumnName(5))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 5:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 4:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        }

        log.debug(jTextArea.getText());
        log.debug(csvFormat.getHeaderComments());

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd_HHmmss");
        String time = dateFormat.format(now);
        String filename = "jobreport_" + time + ".csv";
        out = new PrintWriter(filename);

        writer = new CSVPrinter(out, csvFormat);
        writer.flush();

        int rows = jTable.getModel().getRowCount();
        for (int i = 0; i < rows; i++) {
            ArrayList<String> values = new ArrayList<String>();
            for (int col = 0; col < cols; col++) {
                values.add((String) jTable.getModel().getValueAt(i, col));
            }

            writer.printRecord(values);
        }
        writer.flush();
        writer.close();
        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                "Saved report to file: " + filename, "Report to CSV file", JOptionPane.OK_OPTION);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
        try {
            writer.close();
        } catch (Exception e) {
        }

    }
}

From source file:canreg.client.dataentry.Convert.java

public static boolean convertData(canreg.client.gui.management.CanReg4MigrationInternalFrame.MigrationTask task,
        String filepath, String datafile, String regcode) {
    Connection conn;/*from  w w  w  . j  a  v  a2s. c  o m*/
    Statement stmt;
    ResultSet rs_hdr;
    ResultSet rs_data;
    boolean success = false;
    int totalrowcount = 0;
    int rowsImported = 0;

    String csv = filepath + Globals.FILE_SEPARATOR + regcode + ".csv";
    CSVPrinter printer;
    try {

        debugOut("Migrating data " + datafile);
        pconn = (ParadoxConnection) DriverManager
                .getConnection("jdbc:paradox:///" + filepath.replaceAll("\\\\", "/"));
        final ParadoxTable table = TableData.listTables(pconn, datafile).get(0);
        totalrowcount = table.getRowCount();

        SystemDescription sd = new SystemDescription(
                Globals.CANREG_SERVER_SYSTEM_CONFIG_FOLDER + Globals.FILE_SEPARATOR + regcode + ".xml");
        DatabaseVariablesListElement[] variableListElements;
        variableListElements = sd.getDatabaseVariableListElements();
        ArrayList<String> dbvle = new ArrayList();
        ArrayList<String> cols = new ArrayList();

        // Handling variables names with reservered word by replacing underscore after variable name.
        for (DatabaseVariablesListElement variable : variableListElements) {
            if (variable.getShortName().endsWith("_")) {
                dbvle.add(variable.getShortName().replace("_", ""));
            } else {
                dbvle.add(variable.getShortName());
            }
        }

        conn = DriverManager.getConnection("jdbc:paradox:///" + filepath.replaceAll("\\\\", "/"));

        final DatabaseMetaData meta = conn.getMetaData();
        rs_hdr = meta.getColumns("", "", datafile, "%");

        //Comparing variables in file and database
        while (rs_hdr.next()) {
            for (String dbvar : dbvle) {
                if (rs_hdr.getString("COLUMN_NAME").equals(dbvar)
                        || rs_hdr.getString("COLUMN_NAME").replaceAll(" ", "_").equals(dbvar)) {
                    cols.add(rs_hdr.getString("COLUMN_NAME"));
                }
            }
        }

        String[] strheader = new String[cols.size()];

        String query = "SELECT ";

        for (int i = 0; i < cols.size(); i++) {
            strheader[i] = cols.get(i).toString();
            if (i == cols.size() - 1) {
                query += "\"" + strheader[i] + "\"";
            } else {
                query += "\"" + strheader[i] + "\",";
            }
        }

        query += " FROM  \"" + datafile + "\"";
        CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withHeader(strheader).withDelimiter(',');

        debugOut(query);
        printer = new CSVPrinter(new FileWriter(csv), format);

        int hdrsize = strheader.length;

        Object[] strdata = new String[hdrsize];

        stmt = conn.createStatement();
        rs_data = stmt.executeQuery(query);

        if (Globals.DEBUG) {
            Statement stmt2 = conn.createStatement();
            String q = "SELECT RecNum FROM \"" + datafile + "\"";
            ResultSet rs_all_data = stmt2.executeQuery(q);
            debugOut(rs_all_data.toString());
        }

        while (rs_data.next()) {
            for (int i = 1; i < rs_data.getMetaData().getColumnCount() + 1; i++) {
                switch (rs_data.getMetaData().getColumnType(i)) {
                case 4:
                    strdata[i - 1] = Integer.toString(rs_data.getShort(i));
                    break;
                case 12:
                    strdata[i - 1] = StringEscapeUtils.escapeCsv(rs_data.getString(i));
                    break;
                }
            }
            printer.printRecord(strdata);
            rowsImported++;
        }
        printer.flush();
        printer.close();
        success = true;
    } catch (SQLException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    }
    success = success && (rowsImported == totalrowcount);
    return success;
}

From source file:canreg.client.analysis.AgeSpecificCasesTableBuilder.java

@Override
public LinkedList<String> buildTable(String registryLabel, String reportFileName, int startYear, int endYear,
        Object[][] incidenceData, PopulationDataset[] populations, PopulationDataset[] standardPopulations,
        LinkedList<ConfigFields> configList, String[] engineParameters, FileTypes fileType)
        throws NotCompatibleDataException {

    LinkedList<String> generatedFiles = new LinkedList<String>();

    String footerString = java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
            .getString("TABLE BUILT ")
            + new Date()
            + java.util.ResourceBundle
                    .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                    .getString(" BY CANREG5.");

    String notesString = "";

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                .getString("FILTER USED:") + " " + populations[0].getFilter();
    }/*from w  ww.j  a  va2 s  .  c om*/

    double tableFontSize = 7.5;
    String font = "Times";

    int[] years = { startYear, endYear };

    //      double RegPop[][];
    double totalCases[][];

    String sexLabel[] = null;
    String tableLabel[] = null;
    String icdLabel[] = null;

    LinkedList cancerGroupsLocal[] = null;

    boolean showSeeNotesNote = true;

    char Childc[][] = new char[2][3];

    double casesPerHundredThousand[][][];

    double cumRate64[][];
    double cumRate74[][];

    tableLabel = ConfigFieldsReader.findConfig("table_label", configList);
    // sexLabel = ConfigFieldsReader.findConfig("sex_label", configList);
    sexLabel = new String[] {
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("MALE"),
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("FEMALE") };

    icdLabel = ConfigFieldsReader.findConfig("ICD_groups_labels", configList);
    icd10GroupDescriptions = ConfigFieldsReader.findConfig("ICD10_groups", configList);

    cancerGroupsLocal = EditorialTableTools.generateICD10Groups(icd10GroupDescriptions);

    allCancerGroupsIndex = EditorialTableTools.getICD10index("ALL", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    skinCancerGroupIndex = EditorialTableTools.getICD10index("C44", icd10GroupDescriptions);

    bladderCancerGroupIndex = EditorialTableTools.getICD10index("C67", icd10GroupDescriptions);

    mesotheliomaCancerGroupIndex = EditorialTableTools.getICD10index("C45", icd10GroupDescriptions);

    kaposiSarkomaCancerGroupIndex = EditorialTableTools.getICD10index("C46", icd10GroupDescriptions);

    myeloproliferativeDisordersCancerGroupIndex = EditorialTableTools.getICD10index("MPD",
            icd10GroupDescriptions);

    myelodysplasticSyndromesCancerGroupIndex = EditorialTableTools.getICD10index("MDS", icd10GroupDescriptions);

    allCancerGroupsButSkinIndex = EditorialTableTools.getICD10index("ALLbC44", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    brainAndCentralNervousSystemCancerGroupIndex = EditorialTableTools.getICD10index("C70-72",
            icd10GroupDescriptions);

    ovaryCancerGroupIndex = EditorialTableTools.getICD10index(569, cancerGroupsLocal);

    otherCancerGroupsIndex = EditorialTableTools.getICD10index("O&U", icd10GroupDescriptions);

    numberOfCancerGroups = cancerGroupsLocal.length;

    lineBreaks = parseLineBreaks(ConfigFieldsReader.findConfig("line_breaks", configList));

    numberOfYears = years[1] - years[0] + 1;

    minimumCasesLimit = minimumCasesPerYearLimit * numberOfYears;

    noOldData = true;

    casesPerHundredThousand = new double[numberOfSexes][numberOfAgeGroups][numberOfCancerGroups];

    casesArray = new double[numberOfCancerGroups][numberOfSexes][numberOfAgeGroups];

    // cumRate64 = new double[numberOfSexes][numberOfCancerGroups];
    // cumRate74 = new double[numberOfSexes][numberOfCancerGroups];
    populationArray = new double[numberOfSexes][numberOfAgeGroups];
    foundAgeGroups = new boolean[numberOfAgeGroups];

    if (areThesePopulationDatasetsCompatible(populations)) {
        for (PopulationDataset population : populations) {
            population.addPopulationDataToArrayForTableBuilder(populationArray, foundAgeGroups,
                    new AgeGroupStructure(5, 85, 1));
        }
    } else {
        throw new NotCompatibleDataException();
    }

    populationString = populations[0].getPopulationDatasetName();

    int lastCommaPlace = populationString.lastIndexOf(",");

    if (lastCommaPlace != -1) {
        populationString = populationString.substring(0, lastCommaPlace);
    }

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                .getString("FILTER USED:") + populations[0].getFilter();
    }

    standardPopulationArray = new double[numberOfSexes][numberOfAgeGroups];

    for (PopulationDataset stdPopulation : standardPopulations) {
        stdPopulation.addPopulationDataToArrayForTableBuilder(standardPopulationArray, null,
                new AgeGroupStructure(5, 85, 1));
    }

    // standardize population array
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int ageGroupNumber = 0; ageGroupNumber < numberOfAgeGroups; ageGroupNumber++) {
            standardPopulationArray[sexNumber][ageGroupNumber] = (standardPopulationArray[sexNumber][ageGroupNumber]
                    / standardPopulationArray[sexNumber][numberOfAgeGroups - 1]) * 100000;
        }
    }

    highestPopulationAgeGroup = findHighestAgeGroup(foundAgeGroups);
    lowestPopulationAgeGroup = findLowestAgeGroup(foundAgeGroups);

    int records = 0;
    // generate statistics

    String sexString;
    String icdString;
    String yearString;
    String ageString;
    String basisString;

    int sex, icdNumber, year, icdIndex, yearIndex, ageGroup, ageInt, basis, cases;

    if (incidenceData != null) {
        for (Object[] line : incidenceData) {
            try {
                // Set default
                icdIndex = -1;
                cases = 0;

                // Unknown sex group = 3
                sex = 3;
                // Extract data
                sexString = (String) line[SEX_COLUMN];
                sex = Integer.parseInt(sexString.trim());

                // sex = 3 is unknown sex
                if (sex > 2) {
                    sex = 3;
                }

                // morphologyString = (String) line[MORPHOLOGY_COLUMN];

                /*
                if (morphologyString.length() > 0) {
                int morphology = Integer.parseInt(morphologyString);
                if (morphology == 9140) {
                String behaviourString = getContentOfField(
                incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = kaposiSarkomaCancerGroupIndex;
                }
                        
                } else if ((int)(morphology/10) == 905) {
                String behaviourString = getContentOfField(incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = mesotheliomaCancerGroupIndex;
                }
                }
                }
                 */
                if (icdIndex < 0) {
                    icdString = (String) line[ICD10_COLUMN];
                    if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("C")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        icdIndex = EditorialTableTools.getICD10index(icdNumber, cancerGroupsLocal);
                        if (icdIndex == -1) {
                            icdIndex = -1;
                        }
                    } else if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("D")) {
                        icdIndex = DONT_COUNT; // set don't count as default
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        if (icdNumber == 90 || icdNumber == 414) {
                            icdIndex = bladderCancerGroupIndex;
                        } else if (((int) (icdNumber / 10)) == 45 || ((int) (icdNumber / 10)) == 47) {
                            icdIndex = myeloproliferativeDisordersCancerGroupIndex;
                        } else if (((int) (icdNumber / 10)) == 46) {
                            icdIndex = myelodysplasticSyndromesCancerGroupIndex;
                        }
                    }
                }

                yearString = line[YEAR_COLUMN].toString();
                year = Integer.parseInt(yearString);
                yearIndex = year - years[0];
                ageString = line[AGE_COLUMN].toString();
                ageInt = Integer.parseInt(ageString);

                if (ageInt == unknownAgeInt) {
                    ageGroup = unknownAgeGroupIndex;
                } else {
                    ageGroup = populations[yearIndex].getAgeGroupIndex(ageInt);
                    // Adjust age group
                    if (populations[yearIndex].getAgeGroupStructure().getSizeOfFirstGroup() != 1) {
                        ageGroup += 1;
                    }
                }

                // Extract cases
                cases = (Integer) line[CASES_COLUMN];

                if (icdIndex != DONT_COUNT && year <= years[1] && year >= years[0]) {

                    // Basis of diagnosis
                    basisString = line[BASIS_DIAGNOSIS_COLUMN].toString();
                    if (basisString != null) {
                        basis = Integer.parseInt(basisString.trim());
                    } else {
                        basis = -1;
                    }

                    if (sex <= numberOfSexes && icdIndex >= 0 && icdIndex <= cancerGroupsLocal.length) {

                        casesArray[icdIndex][sex - 1][ageGroup] += cases;

                    } else if (otherCancerGroupsIndex >= 0) {
                        casesArray[otherCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsIndex >= 0) {
                        casesArray[allCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsButSkinIndex >= 0 && skinCancerGroupIndex >= 0
                            && icdIndex != skinCancerGroupIndex) {
                        casesArray[allCancerGroupsButSkinIndex][sex - 1][ageGroup] += cases;
                    }
                    records += cases;
                    if (records % recordsPerFeedback == 0) {
                        System.out.println(java.util.ResourceBundle
                                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                                .getString("PROCESSING RECORD NUMBER: ") + records);
                    }
                }
            } catch (NumberFormatException nfe) {
                Logger.getLogger(AgeSpecificCasesTableBuilder.class.getName()).log(Level.WARNING, null, nfe);
            }
            // Read next line
        }
    }
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder").getString("PROCESSED ")
            + records
            + java.util.ResourceBundle
                    .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                    .getString(" RECORDS."));

    // Total casesPerHundredThousand
    totalCases = new double[numberOfSexes][numberOfCancerGroups];
    // Crude rate
    // crudeRate = new double[numberOfSexes][numberOfCancerGroups];

    for (int sexNumber = 0; sexNumber < 2; sexNumber++) {

        // The age groups
        ageLabel[lowestPopulationAgeGroup] = "0-";

        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {
            if (icdLabel[icdGroup].substring(0 + sexNumber, 1 + sexNumber).equalsIgnoreCase("1")) {
                // The age groups

                double previousAgeGroupCases = 0;
                double previousAgeGroupPopulation = 0;
                double previousAgeGroupWstdPopulation = 0;

                double lastAgeGroupCases = 0;
                double lastAgeGroupPopulation = 0;
                double lastAgeGroupWstdPopulation = 0;

                for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                    if (ageGroupNumber == 1) {
                        for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                            previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                            previousAgeGroupPopulation += populationArray[sexNumber][ag];
                            previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                        }
                    }
                    if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup) {
                        casesPerHundredThousand[sexNumber][ageGroupNumber][icdGroup] = 100000
                                * (casesArray[icdGroup][sexNumber][ageGroupNumber] + previousAgeGroupCases)
                                / (populationArray[sexNumber][ageGroupNumber] + previousAgeGroupPopulation);

                        previousAgeGroupCases = 0;
                        previousAgeGroupPopulation = 0;
                        previousAgeGroupWstdPopulation = 0;

                    } else {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                        previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                    }
                }
                // We calculate the "leftovers" from the last age group
                if (previousAgeGroupPopulation > 0) {
                    casesPerHundredThousand[sexNumber][highestPopulationAgeGroup][icdGroup] = 100000
                            * (previousAgeGroupCases) / (previousAgeGroupPopulation);

                }

                previousAgeGroupCases = 0;
                previousAgeGroupPopulation = 0;
                previousAgeGroupWstdPopulation = 0;

            }
        }
    }

    // ASR, vASR, MV, MI, DCO
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {

            double previousAgeGroupCases = 0;
            double previousAgeGroupPopulation = 0;
            double previousAgeGroupWstdPopulation = 0;

            double lastAgeGroupCases = 0;
            double lastAgeGroupPopulation = 0;
            double lastAgeGroupWstdPopulation = 0;

            totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][0];

            for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                if (ageGroupNumber == 1) {
                    for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                        previousAgeGroupPopulation += populationArray[sexNumber][ag];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                    }
                }
                if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup
                        && (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber] > 0)) {
                    double asr = calculateASR(
                            (previousAgeGroupCases + casesArray[icdGroup][sexNumber][ageGroupNumber]),
                            (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber]),
                            (previousAgeGroupWstdPopulation
                                    + standardPopulationArray[sexNumber][ageGroupNumber]));

                    previousAgeGroupCases = 0;
                    previousAgeGroupPopulation = 0;
                    previousAgeGroupWstdPopulation = 0;

                } else if (ageGroupNumber < highestPopulationAgeGroup) {
                    previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];

                } else {
                    lastAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    lastAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    lastAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                }

                totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][ageGroupNumber];
            }

            // We calculate the "leftovers" from the last age group
            if (lastAgeGroupPopulation > 0) {
                double asr = calculateASR(lastAgeGroupCases, lastAgeGroupPopulation,
                        lastAgeGroupWstdPopulation);

            }

            // and take the unknown age group into account
            totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][unknownAgeGroupIndex];

            if (totalCases[sexNumber][icdGroup] > 0) {

                /* We don't use confidence intervals so this was removed 16.07.07
                double[] asrlul = calculateASRluL(ASR[sex][icdGroup],
                variL[sex][icdGroup], wstdPop[allAgeGroupsIndex]);
                        
                ASRluL[sex][icdGroup][0] = asrlul[0];
                ASRluL[sex][icdGroup][1] = asrlul[1];
                 */
                // Cum. Rates
                if (highestPopulationAgeGroup > 13) {
                    for (int k = 1; k <= 13; k++) {
                        // cumRate64[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup] * cumPop18[k] / 1000.0;
                    }
                }
                if (highestPopulationAgeGroup > 15) {
                    for (int k = 1; k <= 15; k++) {
                        // cumRate74[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup] * cumPop18[k] / 1000.0;
                    }
                }

                /*                    if (!isSpecialized) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                if (icdGroup!=skinCancerGroupIndex) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                }
                }
                 */
            }
        }
    }

    // Adjust the age labels
    ageLabel[1] = "0-";
    ageLabel[highestPopulationAgeGroup] = ageLabel[highestPopulationAgeGroup].substring(0,
            ageLabel[highestPopulationAgeGroup].length() - 1) + "+";

    // Write it out
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    Writer reportFileWriter;

    if (fileType.equals(FileTypes.csv)) {
        // write tab separated stuff here
        CSVPrinter csvOut;
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            try {
                String tabReportFileName = "";
                try {
                    tabReportFileName = reportFileName + sexLabel[sexNumber] + ".csv";
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("WRITING TO ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(new FileOutputStream(tabReportFileName), "UTF-8");
                } catch (IOException ioe) {
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("ERROR IN REPORTFILE: ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(System.out);
                }
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                LinkedList<String> headers = new LinkedList<String>();
                headers.add("SITE");
                headers.add("ALL AGES");
                headers.add("AGE UNK");
                // add age groups

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    headers.add(ageLabel[age]);
                }

                // headers.add("CRUDE RATE");
                headers.add("(%)");
                //                    headers.add("CUM 0-64");
                //                    headers.add("CUM 0-74");
                //                    headers.add("ASR");
                headers.add("ICD (10th)");

                CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',')
                        .withHeader(headers.toArray(new String[0]));

                csvOut = new CSVPrinter(reportFileWriter, format);

                LinkedList<String> line = new LinkedList<String>();

                // write the data
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        line.add(icdLabel[j].substring(3));
                        line.add(formatNumber(totalCases[sexNumber][j], 0));
                        line.add(formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0));
                        for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                            if (casesArray[j][sexNumber][age] > 0) {
                                line.add(formatNumber(casesArray[j][sexNumber][age], 0));
                            } else {
                                line.add("0");
                            }
                        }
                        // line.add(formatNumber(crudeRate[sexNumber][j], 2));
                        line.add(formatNumber(100 * totalCases[sexNumber][j]
                                / totalCases[sexNumber][allCancerGroupsButSkinIndex]));
                        // line.add(formatNumber(cumRate64[sexNumber][j], 2));
                        // line.add(formatNumber(cumRate74[sexNumber][j], 2));
                        // line.add(formatNumber(ASR[sexNumber][j]));
                        line.add(icd10GroupDescriptions[j]);
                        csvOut.printRecord(line);
                        line.clear();
                    }
                }

                try {
                    csvOut.flush();
                    csvOut.close();
                } catch (IOException ex) {
                    Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                generatedFiles.add(tabReportFileName);
            } catch (IOException ex) {
                Logger.getLogger(AgeSpecificCasesTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {

        // Make PS-file
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            String psFileName = reportFileName + "-" + sexLabel[sexNumber] + ".ps";
            generatedFiles.add(psFileName);
            try {
                Writer fw = new OutputStreamWriter(new FileOutputStream(psFileName), "UTF-8");

                nf.setMaximumFractionDigits(1);
                nf.setMinimumFractionDigits(1);

                fw.write("/RLT {rlineto} def\n");
                fw.write("/LT {lineto} def\n");
                fw.write("/MT {moveto} def\n");
                fw.write("/SCF {scalefont} def\n");
                fw.write("/SF {setfont} def\n");
                fw.write("/SG {setgray} def\n");
                fw.write("/FF {findfont} def\n");
                fw.write("/SLW {setlinewidth} def\n");
                fw.write("/CP {closepath} def\n");
                fw.write("/Mainfont\n");
                fw.write("/Helvetica-Bold FF " + (int) (tableFontSize * 2 - 3) + " SCF def\n");
                fw.write("/Titlefont\n");
                fw.write("/Helvetica FF " + tableFontSize + " SCF def\n");
                fw.write("/Tablefont\n");
                fw.write("/" + font + " FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRfont\n");
                fw.write("/" + font + "-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/ICDfont\n");
                fw.write("/" + font + "-Italic FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRitalicsfont\n");
                fw.write("/" + font + "-Italic-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/col 735 def\n");
                fw.write("/RS {dup stringwidth pop col exch sub 0 rmoveto show} def\n");
                fw.write("/CS {dup stringwidth pop 810 exch sub 2 div 0 rmoveto show} def\n");
                fw.write("/nstr 1 string def\n");
                fw.write("/prtchar {nstr 0 3 -1 roll put nstr show} def\n");
                fw.write("newpath\n");
                fw.write("90 rotate -20 -570 translate\n"); //  Landscape
                fw.write("Mainfont SF\n");
                fw.write("0 535 MT (" + registryLabel + ") CS\n");
                fw.write("Titlefont SF\n");
                fw.write("0 525 MT (" + populationString + ") CS\n");
                fw.write("0 513 MT (" + tableLabel[0] + " - " + sexLabel[sexNumber] + ") CS\n");
                //                                                                                              draw the grey frame
                fw.write("0.85 SG 27 510 translate\n");
                fw.write("0 -5 MT 785 -5 LT 785 -27 LT 0 -27 LT  CP fill\n");
                fw.write("0 -510 translate 0.95 SG\n");
                double k = 475;

                for (int icd = 0; icd < numberOfCancerGroups; icd++) {
                    if ((icd + 1) < numberOfCancerGroups && icdLabel[icd + 1].charAt(sexNumber) == '1') {
                        int lines = (isLineBreak(icd));
                        if (lines > 0) {
                            k -= 2;
                            fw.write("0 " + (k - 2) + " MT 785 " + (k - 2) + " LT 785 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT 0 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT CP fill\n");
                        } else if (lines < 0) {
                            k -= 2;
                        }
                        k -= tableFontSize;
                    }
                }

                /*
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                        
                int lines = (isLineBreak(j));
                if (lines > 0) {
                k -= 2;
                        
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - lines * tableFontSize) + " LT 0 " + (k - lines * tableFontSize) +
                " LT CP fill\n");
                        
                } else if (lines > 0)
                k -= 2;
                k -= lines * tableFontSize;
                        
                        
                        
                        
                if (IsLineBreak(j)) {
                k -= 2;
                }
                //  draw the grey frames
                if (j == 8) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 35) + " LT 0 " + (k - 35) +
                " LT CP fill\n");
                } else if (j == 34) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 26) + " LT 0 " + (k - 26) +
                " LT CP fill\n");
                } else if (j == 16 || j == 22 || j == 40) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 18) + " LT 0 " + (k - 18) +
                " LT CP fill\n");
                } else if (j == 27) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 42) + " LT 0 " + (k - 42) +
                " LT CP fill\n");
                } else if (j == 47) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 34) + " LT 0 " + (k - 34) +
                " LT CP fill\n");
                } else if (j == 53) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 12) + " LT 0 " + (k - 12) +
                " LT CP fill\n");
                }
                k -= (tableFontSize);
                }
                        
                }
                 */
                fw.write("0 SG\n");

                fw.write("ICDfont SF\n");
                fw.write(" 740 496 MT (ICD) show\n");
                fw.write(" 740 487 MT ((10th)) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("ICDfont SF\n");
                        }

                        fw.write("745 " + k + " MT (" + icd10GroupDescriptions[j] + ") show\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("0 491 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }

                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        if (j != allCancerGroupsIndex && allCancerGroupsButSkinIndex >= 0) {
                            fw.write(
                                    "0 " + k + " MT ("
                                            + formatNumber(100 * totalCases[sexNumber][j]
                                                    / totalCases[sexNumber][allCancerGroupsButSkinIndex])
                                            + ") RS\n");
                        }
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col 119 def\n");
                fw.write("0 496 MT (ALL) RS\n");
                fw.write("0 487 MT (AGES) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(totalCases[sexNumber][j], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 add def\n");
                fw.write("0 496 MT (AGE) RS\n");
                fw.write("0 487 MT (UNK) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                if (highestPopulationAgeGroup == numberOfAgeGroups - 4) {
                    fw.write("/col 145 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 5) {
                    fw.write("/col 176 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 6) {
                    fw.write("/col 208 def\n");
                } else {
                    fw.write("/col 145 def\n");
                }

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    fw.write("/col col 26 add def\n");
                    fw.write("0 491 MT (" + ageLabel[age] + ") RS\n");
                    // fw.write("/col col 5 sub def\n");
                    k = 475;
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }

                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            if (casesArray[j][sexNumber][age] > 0) {
                                fw.write("0 " + k + " MT (" + formatNumber(casesArray[j][sexNumber][age], 0)
                                        + ") RS\n");
                            } else {
                                fw.write("0 " + k + " MT (    -  ) RS\n");
                            }
                            k -= (tableFontSize);
                        }
                    }
                }
                fw.write("3 492 MT ( S I T E) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("3 " + k + " MT (" + icdLabel[j].substring(3) + ") show\n");
                        k -= (tableFontSize);
                    }
                }
                if (showSeeNotesNote) {
                    fw.write("3 0 MT (" + notesString + ") show\n");
                }

                // Write the footer
                fw.write("0 0 MT (" + footerString + ") CS\n");

                fw.write("showpage\n");
                System.out.println("Wrote " + psFileName + ".");
                fw.close();
            } catch (IOException ioe) {
                System.out.println(ioe);
            }
        }
    }

    if (fileType == FileTypes.pdf) {
        LinkedList<String> newlyGeneratedFiles = new LinkedList<String>();
        for (String fileN : generatedFiles) {
            PsToPdfConverter pstopdf = new PsToPdfConverter(gspath);
            newlyGeneratedFiles.add(pstopdf.convert(fileN));
            // delete the ps file
            File file = new File(fileN);
            file.delete();
        }
        generatedFiles = newlyGeneratedFiles;
    }

    System.out.println("Fini!");

    return generatedFiles;
}

From source file:canreg.client.analysis.AgeSpecificCasesPerHundredThousandTableBuilder.java

@Override
public LinkedList<String> buildTable(String tableHeader, String reportFileName, int startYear, int endYear,
        Object[][] incidenceData, PopulationDataset[] populations, PopulationDataset[] standardPopulations,
        LinkedList<ConfigFields> configList, String[] engineParameters, FileTypes fileType)
        throws NotCompatibleDataException {

    LinkedList<String> generatedFiles = new LinkedList<String>();

    String footerString = java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("TABLE BUILT ")
            + new Date()
            + java.util.ResourceBundle
                    .getBundle(/*from   ww  w.j  ava  2s .  com*/
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" BY CANREG5.");

    String notesString = "";

    double tableFontSize = 7.5;
    String font = "Times";

    int[] years = { startYear, endYear };

    double casesArray[][][] = null; // a 3D array of sex, icd and agegroup - with one extra layer in all dimensions containing a sum of all
    double populationArray[][] = null; // contains population count in the following format: [sex][agegroup]

    //      double RegPop[][];
    double totalCasesPerHundredThousand[][];
    double crudeRate[][];
    double MV[][];
    double ASR[][];
    double ASRbyAgeGroup[][][];
    double ratei[][];
    //      double vASR[][];
    double ASRluL[][][];
    double variL[][];
    double variLbyAgeGroup[][][];
    double DCO[][];

    char ASRf[][];
    double ASRratio[][];
    char MVf[][];

    String sexLabel[] = null;
    String tableLabel[] = null;
    String icdLabel[] = null;

    LinkedList cancerGroupsLocal[] = null;

    LinkedList<FieldDescription> incidenceFieldDescriptionList = null;

    boolean showSeeNotesNote = true;

    char Childc[][] = new char[2][3];

    double casesPerHundredThousand[][][];

    double cumRate64[][];
    double cumRate74[][];

    tableLabel = ConfigFieldsReader.findConfig("table_label", configList);
    // sexLabel = ConfigFieldsReader.findConfig("sex_label", configList);

    sexLabel = new String[] {
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("MALE"),
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("FEMALE") };

    icdLabel = ConfigFieldsReader.findConfig("ICD_groups_labels", configList);
    icd10GroupDescriptions = ConfigFieldsReader.findConfig("ICD10_groups", configList);

    cancerGroupsLocal = EditorialTableTools.generateICD10Groups(icd10GroupDescriptions);

    allCancerGroupsIndex = EditorialTableTools.getICD10index("ALL", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    skinCancerGroupIndex = EditorialTableTools.getICD10index("C44", icd10GroupDescriptions);

    bladderCancerGroupIndex = EditorialTableTools.getICD10index("C67", icd10GroupDescriptions);

    mesotheliomaCancerGroupIndex = EditorialTableTools.getICD10index("C45", icd10GroupDescriptions);

    kaposiSarkomaCancerGroupIndex = EditorialTableTools.getICD10index("C46", icd10GroupDescriptions);

    myeloproliferativeDisordersCancerGroupIndex = EditorialTableTools.getICD10index("MPD",
            icd10GroupDescriptions);

    myelodysplasticSyndromesCancerGroupIndex = EditorialTableTools.getICD10index("MDS", icd10GroupDescriptions);

    allCancerGroupsButSkinIndex = EditorialTableTools.getICD10index("ALLbC44", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    brainAndCentralNervousSystemCancerGroupIndex = EditorialTableTools.getICD10index("C70-72",
            icd10GroupDescriptions);

    ovaryCancerGroupIndex = EditorialTableTools.getICD10index(569, cancerGroupsLocal);

    otherCancerGroupsIndex = EditorialTableTools.getICD10index("O&U", icd10GroupDescriptions);

    numberOfCancerGroups = cancerGroupsLocal.length;

    lineBreaks = parseLineBreaks(ConfigFieldsReader.findConfig("line_breaks", configList));

    numberOfYears = years[1] - years[0] + 1;

    minimumCasesLimit = minimumCasesPerYearLimit * numberOfYears;

    noOldData = true;

    casesPerHundredThousand = new double[numberOfSexes][numberOfAgeGroups][numberOfCancerGroups];

    casesArray = new double[numberOfCancerGroups][numberOfSexes][numberOfAgeGroups];

    cumRate64 = new double[numberOfSexes][numberOfCancerGroups];
    cumRate74 = new double[numberOfSexes][numberOfCancerGroups];

    populationArray = new double[numberOfSexes][numberOfAgeGroups];
    foundAgeGroups = new boolean[numberOfAgeGroups];

    if (areThesePopulationDatasetsCompatible(populations)) {
        for (PopulationDataset population : populations) {
            population.addPopulationDataToArrayForTableBuilder(populationArray, foundAgeGroups,
                    new AgeGroupStructure(5, 85, 1));
        }
    } else {
        throw new NotCompatibleDataException();
    }

    populationString = populations[0].getPopulationDatasetName();

    int lastCommaPlace = populationString.lastIndexOf(",");

    if (lastCommaPlace != -1) {
        populationString = populationString.substring(0, lastCommaPlace);
    }

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                .getString("FILTER USED:") + " " + populations[0].getFilter();
    }

    if (populations.length > 0) {
        notesString += ", "
                + java.util.ResourceBundle.getBundle(
                        "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                        .getString("REFERENCE POPULATION:")
                + " " + populations[0].getReferencePopulation().getPopulationDatasetName();
    }

    standardPopulationArray = new double[numberOfSexes][numberOfAgeGroups];
    for (PopulationDataset stdPopulation : standardPopulations) {
        stdPopulation.addPopulationDataToArrayForTableBuilder(standardPopulationArray, null,
                new AgeGroupStructure(5, 85, 1));
    }

    // standardize population array
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int ageGroupNumber = 0; ageGroupNumber < numberOfAgeGroups; ageGroupNumber++) {
            standardPopulationArray[sexNumber][ageGroupNumber] = (standardPopulationArray[sexNumber][ageGroupNumber]
                    / standardPopulationArray[sexNumber][numberOfAgeGroups - 1]) * 100000;
        }
    }

    highestPopulationAgeGroup = findHighestAgeGroup(foundAgeGroups);
    lowestPopulationAgeGroup = findLowestAgeGroup(foundAgeGroups);

    int records = 0;
    // generate statistics

    // Generate based on death certificate only
    DCO = new double[numberOfSexes][numberOfCancerGroups];

    // and microscopical verification
    MV = new double[numberOfSexes][numberOfCancerGroups];

    String sexString;
    String icdString;
    String morphologyString;
    String yearString;
    String ageString;
    String basisString;
    String casesString;

    int sex, icdNumber, year, icdIndex, yearIndex, ageGroup, ageInt, basis, cases;

    if (incidenceData != null) {
        for (Object[] line : incidenceData) {
            try {

                // Set default
                icdIndex = -1;
                cases = 0;

                // Unknown sex group = 3
                sex = 3;
                // Extract data
                sexString = (String) line[SEX_COLUMN];
                sex = Integer.parseInt(sexString.trim());

                // sex = 3 is unknown sex
                if (sex > 2) {
                    sex = 3;
                }

                morphologyString = (String) line[MORPHOLOGY_COLUMN];

                /*
                if (morphologyString.length() > 0) {
                int morphology = Integer.parseInt(morphologyString);
                if (morphology == 9140) {
                String behaviourString = getContentOfField(
                incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = kaposiSarkomaCancerGroupIndex;
                }
                        
                } else if ((int)(morphology/10) == 905) {
                String behaviourString = getContentOfField(incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = mesotheliomaCancerGroupIndex;
                }
                }
                }
                 */
                if (icdIndex < 0) {
                    icdString = (String) line[ICD10_COLUMN];
                    if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("C")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        icdIndex = EditorialTableTools.getICD10index(icdNumber, cancerGroupsLocal);
                        if (icdIndex == -1) {
                            icdIndex = -1;
                        }
                    } else if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("D")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        if (icdNumber == 90 || icdNumber == 414) {
                            icdIndex = bladderCancerGroupIndex;
                        } else if ((int) (icdNumber / 10) == 45 || (int) (icdNumber / 10) == 47) {
                            icdIndex = myeloproliferativeDisordersCancerGroupIndex;
                        } else if ((int) (icdNumber / 10) == 46) {
                            icdIndex = myelodysplasticSyndromesCancerGroupIndex;
                        } else {
                            icdIndex = DONT_COUNT;
                        }
                    }

                }

                yearString = line[YEAR_COLUMN].toString();
                year = Integer.parseInt(yearString);
                yearIndex = year - years[0];
                ageString = line[AGE_COLUMN].toString();
                ageInt = Integer.parseInt(ageString);

                if (ageInt == unknownAgeInt) {
                    ageGroup = unknownAgeGroupIndex;
                } else {
                    ageGroup = populations[yearIndex].getAgeGroupIndex(ageInt);
                    // Adjust age group
                    if (populations[yearIndex].getAgeGroupStructure().getSizeOfFirstGroup() != 1) {
                        ageGroup += 1;
                    }
                }

                // Extract cases
                cases = (Integer) line[CASES_COLUMN];

                if (icdIndex != DONT_COUNT && year <= years[1] && year >= years[0]) {

                    // Basis of diagnosis
                    basisString = line[BASIS_DIAGNOSIS_COLUMN].toString();
                    if (basisString != null) {
                        basis = Integer.parseInt(basisString.trim());
                    } else {
                        basis = -1;
                    }

                    if (sex <= numberOfSexes && icdIndex >= 0 && icdIndex <= cancerGroupsLocal.length) {

                        casesArray[icdIndex][sex - 1][ageGroup] += cases;

                        //
                        if (basis == 00) {
                            DCO[sex - 1][icdIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][icdIndex] += cases;
                        }
                    } else if (otherCancerGroupsIndex >= 0) {
                        casesArray[otherCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsIndex >= 0) {
                        casesArray[allCancerGroupsIndex][sex - 1][ageGroup] += cases;
                        if (basis == 0) {
                            DCO[sex - 1][allCancerGroupsIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][allCancerGroupsIndex] += cases;
                        }
                    }
                    if (allCancerGroupsButSkinIndex >= 0 && skinCancerGroupIndex >= 0
                            && icdIndex != skinCancerGroupIndex) {
                        casesArray[allCancerGroupsButSkinIndex][sex - 1][ageGroup] += cases;
                        if (basis == 0) {
                            DCO[sex - 1][allCancerGroupsButSkinIndex] += cases;
                        } else if (basis >= 10 && basis <= 19) {
                            MV[sex - 1][allCancerGroupsButSkinIndex] += cases;
                        }
                    }
                    records += cases;
                    if (records % recordsPerFeedback == 0) {
                        System.out.println(java.util.ResourceBundle.getBundle(
                                "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                                .getString("PROCESSING RECORD NUMBER: ") + records);
                    }
                }
            } catch (NumberFormatException nfe) {
                Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                        .log(Level.WARNING, null, nfe);
            }
            // Read next line

        }
    }
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("PROCESSED ")
            + records
            + java.util.ResourceBundle
                    .getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" RECORDS."));

    // Get our matrixes ready
    // Age standarized rate
    ASR = new double[numberOfSexes][numberOfCancerGroups];
    ASRbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];
    ASRluL = new double[numberOfSexes][numberOfCancerGroups][2];
    variL = new double[numberOfSexes][numberOfCancerGroups];
    variLbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];

    // Total casesPerHundredThousand
    totalCasesPerHundredThousand = new double[numberOfSexes][numberOfCancerGroups];
    // Crude rate
    crudeRate = new double[numberOfSexes][numberOfCancerGroups];

    for (int sexNumber = 0; sexNumber < 2; sexNumber++) {

        // The age groups
        ageLabel[lowestPopulationAgeGroup] = "0-";

        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {
            if (icdLabel[icdGroup].substring(0 + sexNumber, 1 + sexNumber).equalsIgnoreCase("1")) {
                // The age groups

                double previousAgeGroupCases = 0;
                double previousAgeGroupPopulation = 0;
                double previousAgeGroupWstdPopulation = 0;

                double lastAgeGroupCases = 0;
                double lastAgeGroupPopulation = 0;
                double lastAgeGroupWstdPopulation = 0;

                for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                    if (ageGroupNumber == 1) {
                        for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                            previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                            previousAgeGroupPopulation += populationArray[sexNumber][ag];
                            previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                        }
                    }
                    if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup) {
                        casesPerHundredThousand[sexNumber][ageGroupNumber][icdGroup] = 100000
                                * (casesArray[icdGroup][sexNumber][ageGroupNumber] + previousAgeGroupCases)
                                / (populationArray[sexNumber][ageGroupNumber] + previousAgeGroupPopulation);

                        previousAgeGroupCases = 0;
                        previousAgeGroupPopulation = 0;
                        previousAgeGroupWstdPopulation = 0;

                    } else {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                        previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                    }
                }
                // We calculate the "leftovers" from the last age group
                if (previousAgeGroupPopulation > 0) {
                    casesPerHundredThousand[sexNumber][highestPopulationAgeGroup][icdGroup] = 100000
                            * (previousAgeGroupCases) / (previousAgeGroupPopulation);

                }

                previousAgeGroupCases = 0;
                previousAgeGroupPopulation = 0;
                previousAgeGroupWstdPopulation = 0;

            }
        }
    }

    // ASR, vASR, MV, MI, DCO
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {

            double previousAgeGroupCases = 0;
            double previousAgeGroupPopulation = 0;
            double previousAgeGroupWstdPopulation = 0;

            double lastAgeGroupCases = 0;
            double lastAgeGroupPopulation = 0;
            double lastAgeGroupWstdPopulation = 0;

            totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][0];

            for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                if (ageGroupNumber == 1) {
                    for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                        previousAgeGroupPopulation += populationArray[sexNumber][ag];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                    }
                }
                if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup
                        && (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber] > 0)) {
                    double asr = calculateASR(
                            (previousAgeGroupCases + casesArray[icdGroup][sexNumber][ageGroupNumber]),
                            (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber]),
                            (previousAgeGroupWstdPopulation
                                    + standardPopulationArray[sexNumber][ageGroupNumber]));

                    ASR[sexNumber][icdGroup] += asr;

                    ASRbyAgeGroup[sexNumber][icdGroup][ageGroupNumber] = asr;

                    /* We don't use confidence intervals so this was removed 16.07.07
                    double varil =
                    calculateVariL((previousAgeGroupCases +
                    casesArray[icdGroup][sex][
                    ageGroup]),
                    (previousAgeGroupWstdPopulation +
                    wstdPop[ageGroup]),
                    (previousAgeGroupPopulation +
                    populationArray[sex][ageGroup])
                    );
                            
                    variL[sex][icdGroup] += varil;
                    variLbyAgeGroup[sex][icdGroup][ageGroup] = varil;
                     */
                    previousAgeGroupCases = 0;
                    previousAgeGroupPopulation = 0;
                    previousAgeGroupWstdPopulation = 0;

                } else if (ageGroupNumber < highestPopulationAgeGroup) {
                    previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];

                } else {
                    lastAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    lastAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    lastAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                }

                totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][ageGroupNumber];
            }

            // We calculate the "leftovers" from the last age group
            if (lastAgeGroupPopulation > 0) {
                double asr = calculateASR(lastAgeGroupCases, lastAgeGroupPopulation,
                        lastAgeGroupWstdPopulation);
                ASR[sexNumber][icdGroup] += asr;

                ASRbyAgeGroup[sexNumber][icdGroup][highestPopulationAgeGroup] = asr;
                /* We don't use confidence intervals so this was removed 16.07.07
                double varil = calculateVariL(lastAgeGroupCases,
                lastAgeGroupWstdPopulation, lastAgeGroupPopulation);
                        
                variL[sex][icdGroup] += varil;
                        
                variLbyAgeGroup[sex][icdGroup][highestPopulationAgeGroup] =
                varil;
                 */

            }

            // and take the unknown age group into account
            totalCasesPerHundredThousand[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][unknownAgeGroupIndex];

            if (totalCasesPerHundredThousand[sexNumber][icdGroup] > 0) {

                DCO[sexNumber][icdGroup] = 100 * (int) DCO[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                MV[sexNumber][icdGroup] = 100 * (int) MV[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                crudeRate[sexNumber][icdGroup] = totalCasesPerHundredThousand[sexNumber][icdGroup]
                        * standardPopulationArray[sexNumber][allAgeGroupsIndex]
                        / (populationArray[sexNumber][allAgeGroupsIndex]);

                /* We don't use confidence intervals so this was removed 16.07.07
                double[] asrlul = calculateASRluL(ASR[sex][icdGroup],
                variL[sex][icdGroup], wstdPop[allAgeGroupsIndex]);
                        
                ASRluL[sex][icdGroup][0] = asrlul[0];
                ASRluL[sex][icdGroup][1] = asrlul[1];
                 */
                // Cum. Rates
                if (highestPopulationAgeGroup > 13) {
                    for (int k = 1; k <= 13; k++) {
                        cumRate64[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup]
                                * cumPop18[k] / 1000.0;
                    }
                }
                if (highestPopulationAgeGroup > 15) {
                    for (int k = 1; k <= 15; k++) {
                        cumRate74[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup]
                                * cumPop18[k] / 1000.0;
                    }
                }

                // adjust the ASR and cum rates for unknown ages
                if (ASR[sexNumber][icdGroup] > 0) {
                    double ratio = totalCasesPerHundredThousand[sexNumber][icdGroup]
                            / (totalCasesPerHundredThousand[sexNumber][icdGroup]
                                    - casesArray[icdGroup][sexNumber][unknownAgeGroupIndex]);
                    ASR[sexNumber][icdGroup] *= ratio;
                    cumRate64[sexNumber][icdGroup] *= ratio;
                    cumRate74[sexNumber][icdGroup] *= ratio;

                }
                /*                    if (!isSpecialized) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                if (icdGroup!=skinCancerGroupIndex) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                }
                }
                 */
            }
        }
    }

    // Get our matrixes ready
    ASRf = new char[numberOfSexes][numberOfCancerGroups];

    // Adjust the age labels
    ageLabel[1] = "0-";
    ageLabel[highestPopulationAgeGroup] = ageLabel[highestPopulationAgeGroup].substring(0,
            ageLabel[highestPopulationAgeGroup].length() - 1) + "+";

    // Write it out
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    // Writing
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("WRITING DATA...\\N"));

    Writer reportFileWriter;

    if (fileType.equals(FileTypes.csv)) {
        // write tab separated stuff here
        // CSVWriter csvOut;
        CSVPrinter csvOut;

        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            try {
                String tabReportFileName = "";
                try {
                    tabReportFileName = reportFileName + sexLabel[sexNumber] + ".csv";
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("WRITING TO ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(new FileOutputStream(tabReportFileName), "UTF-8");
                } catch (IOException ioe) {
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("ERROR IN REPORTFILE: ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(System.out);
                }
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                LinkedList<String> headers = new LinkedList<String>();
                headers.add("SITE");
                headers.add("ALL AGES");
                headers.add("AGE UNK");
                // add age groups

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    headers.add(ageLabel[age]);
                }

                headers.add("CRUDE RATE");
                headers.add("(%)");
                headers.add("CUM 0-64");
                headers.add("CUM 0-74");
                headers.add("ASR");
                headers.add("ICD (10th)");
                //                csvOut.writeNext(line.toArray(new String[0]));
                CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',')
                        .withHeader(headers.toArray(new String[0]));

                csvOut = new CSVPrinter(reportFileWriter, format);
                //                    csvOut.printRecord(headers);

                LinkedList<String> line = new LinkedList<String>();
                // write the data
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        line.add(icdLabel[j].substring(3));
                        line.add(formatNumber(totalCasesPerHundredThousand[sexNumber][j], 0));
                        line.add(formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0));
                        for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                            if (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                line.add(formatNumber(casesPerHundredThousand[sexNumber][age][j]));
                            } else {
                                line.add("0.0");
                            }
                        }
                        line.add(formatNumber(crudeRate[sexNumber][j], 2));
                        line.add(formatNumber(100 * totalCasesPerHundredThousand[sexNumber][j]
                                / totalCasesPerHundredThousand[sexNumber][allCancerGroupsButSkinIndex]));
                        line.add(formatNumber(cumRate64[sexNumber][j], 2));
                        line.add(formatNumber(cumRate74[sexNumber][j], 2));
                        line.add(formatNumber(ASR[sexNumber][j]));
                        line.add(icd10GroupDescriptions[j]);
                        csvOut.printRecord(line);
                        line.clear();
                    }
                }

                csvOut.flush();
                csvOut.close();
                generatedFiles.add(tabReportFileName);
            } catch (IOException ex) {
                Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    } // Make PS-file
    else {
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            String psFileName = reportFileName + "-" + sexLabel[sexNumber] + ".ps";
            generatedFiles.add(psFileName);
            try {
                Writer fw = new OutputStreamWriter(new FileOutputStream(psFileName), "UTF-8");
                nf.setMaximumFractionDigits(1);
                nf.setMinimumFractionDigits(1);

                fw.write("/RLT {rlineto} def\n");
                fw.write("/LT {lineto} def\n");
                fw.write("/MT {moveto} def\n");
                fw.write("/SCF {scalefont} def\n");
                fw.write("/SF {setfont} def\n");
                fw.write("/SG {setgray} def\n");
                fw.write("/FF {findfont} def\n");
                fw.write("/SLW {setlinewidth} def\n");
                fw.write("/CP {closepath} def\n");
                fw.write("/Mainfont\n");
                fw.write("/Helvetica-Bold FF " + (int) (tableFontSize * 2 - 3) + " SCF def\n");
                fw.write("/Titlefont\n");
                fw.write("/Helvetica FF " + tableFontSize + " SCF def\n");
                fw.write("/Tablefont\n");
                fw.write("/" + font + " FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRfont\n");
                fw.write("/" + font + "-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/ICDfont\n");
                fw.write("/" + font + "-Italic FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRitalicsfont\n");
                fw.write("/" + font + "-Italic-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/col 735 def\n");
                fw.write("/RS {dup stringwidth pop col exch sub 0 rmoveto show} def\n");
                fw.write("/CS {dup stringwidth pop 810 exch sub 2 div 0 rmoveto show} def\n");
                fw.write("/nstr 1 string def\n");
                fw.write("/prtchar {nstr 0 3 -1 roll put nstr show} def\n");
                fw.write("newpath\n");
                fw.write("90 rotate -20 -570 translate\n"); //  Landscape
                fw.write("Mainfont SF\n");
                fw.write("0 535 MT (" + tableHeader + ") CS\n");
                fw.write("Titlefont SF\n");
                fw.write("0 525 MT (" + populationString + ") CS\n");
                fw.write("0 513 MT (" + tableLabel[0] + " - " + sexLabel[sexNumber] + ") CS\n");
                //                                                                                              draw the grey frame
                fw.write("0.85 SG 27 510 translate\n");
                fw.write("0 -5 MT 785 -5 LT 785 -27 LT 0 -27 LT  CP fill\n");
                fw.write("0 -510 translate 0.95 SG\n");
                double k = 475;

                for (int icd = 0; icd < numberOfCancerGroups; icd++) {
                    if ((icd + 1) < numberOfCancerGroups && icdLabel[icd + 1].charAt(sexNumber) == '1') {
                        int lines = (isLineBreak(icd));
                        if (lines > 0) {
                            k -= 2;
                            fw.write("0 " + (k - 2) + " MT 785 " + (k - 2) + " LT 785 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT 0 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT CP fill\n");
                        } else if (lines < 0) {
                            k -= 2;
                        }
                        k -= tableFontSize;
                    }
                }

                /*
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                        
                int lines = (isLineBreak(j));
                if (lines > 0) {
                k -= 2;
                        
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - lines * tableFontSize) + " LT 0 " + (k - lines * tableFontSize) +
                " LT CP fill\n");
                        
                } else if (lines > 0)
                k -= 2;
                k -= lines * tableFontSize;
                        
                        
                        
                        
                if (IsLineBreak(j)) {
                k -= 2;
                }
                //  draw the grey frames
                if (j == 8) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 35) + " LT 0 " + (k - 35) +
                " LT CP fill\n");
                } else if (j == 34) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 26) + " LT 0 " + (k - 26) +
                " LT CP fill\n");
                } else if (j == 16 || j == 22 || j == 40) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 18) + " LT 0 " + (k - 18) +
                " LT CP fill\n");
                } else if (j == 27) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 42) + " LT 0 " + (k - 42) +
                " LT CP fill\n");
                } else if (j == 47) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 34) + " LT 0 " + (k - 34) +
                " LT CP fill\n");
                } else if (j == 53) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 12) + " LT 0 " + (k - 12) +
                " LT CP fill\n");
                }
                k -= (tableFontSize);
                }
                        
                }
                 */
                fw.write("0 SG\n");

                fw.write("ICDfont SF\n");
                fw.write(" 740 496 MT (ICD) show\n");
                fw.write(" 740 487 MT ((10th)) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("ICDfont SF\n");
                        }

                        fw.write("745 " + k + " MT (" + icd10GroupDescriptions[j] + ") show\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 0 sub def\n");
                fw.write("ASRfont SF\n");
                fw.write("0 496 MT (ASR) RS\n");
                fw.write("0 487 MT ( ) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ASRitalicsfont SF\n");
                        } else {
                            fw.write("ASRfont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(ASR[sexNumber][j]) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-74) RS\n");
                k = 475;
                if (cumRate74[sexNumber][allCancerGroupsIndex] > 0) {
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }
                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            fw.write("0 " + k + " MT (" + formatNumber(cumRate74[sexNumber][j], 2) + ") RS\n");
                            k -= (tableFontSize);
                        }
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-64) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(cumRate64[sexNumber][j], 2) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                /* No MVs shown
                fw.write("Tablefont SF\n");
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (MV) RS\n");
                fw.write("0 487 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                if (isLineBreak(j - 1)!=0) {
                k -= 2;
                }
                        
                if (j==skinCancerGroupIndex || j == ovaryCancerGroupIndex || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex ||
                j == myeloproliferativeDisordersCancerGroupIndex || j == brainAndCentralNervousSystemCancerGroupIndex) {
                fw.write("ICDfont SF\n");
                } else fw.write("Tablefont SF\n");
                        
                if (CA[sex][j] >= 0) {
                fw.write("0 " + k + " MT (" +
                formatNumber(MV[sex][j]) + ") RS\n");
                } else {
                fw.write("0 " + k + " MT (      -) RS\n");
                }
                k -= (tableFontSize);
                }
                }
                 */
                fw.write("/col col 20 sub def\n");
                fw.write("0 491 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }

                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        if (j != allCancerGroupsIndex && allCancerGroupsButSkinIndex >= 0) {
                            fw.write("0 " + k + " MT (" + formatNumber(100
                                    * totalCasesPerHundredThousand[sexNumber][j]
                                    / totalCasesPerHundredThousand[sexNumber][allCancerGroupsButSkinIndex])
                                    + ") RS\n");
                        }
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (CRUDE) RS\n");
                fw.write("0 487 MT (RATE) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(crudeRate[sexNumber][j]) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col 119 def\n");
                fw.write("0 496 MT (ALL) RS\n");
                fw.write("0 487 MT (AGES) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(totalCasesPerHundredThousand[sexNumber][j], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 add def\n");
                fw.write("0 496 MT (AGE) RS\n");
                fw.write("0 487 MT (UNK) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                if (highestPopulationAgeGroup == numberOfAgeGroups - 4) {
                    fw.write("/col 145 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 5) {
                    fw.write("/col 176 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 6) {
                    fw.write("/col 208 def\n");
                } else {
                    fw.write("/col 145 def\n");
                }

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    fw.write("/col col 26 add def\n");
                    fw.write("0 491 MT (" + ageLabel[age] + ") RS\n");
                    // fw.write("/col col 5 sub def\n");
                    k = 475;
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }

                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            if (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                fw.write("0 " + k + " MT ("
                                        + formatNumber(casesPerHundredThousand[sexNumber][age][j]) + ") RS\n");
                            } else {
                                fw.write("0 " + k + " MT (    -  ) RS\n");
                            }
                            k -= (tableFontSize);
                        }
                    }
                }
                fw.write("3 492 MT ( S I T E) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("3 " + k + " MT (" + icdLabel[j].substring(3) + ") show\n");
                        k -= (tableFontSize);
                    }
                }
                if (showSeeNotesNote) {
                    fw.write("3 0 MT (" + notesString + ") show\n");
                }

                // Write the footer
                fw.write("0 0 MT (" + footerString + ") CS\n");

                fw.write("showpage\n");
                System.out.println("Wrote " + psFileName + ".");
                fw.close();
            } catch (IOException ioe) {
                System.out.println(ioe);
            }
        }
    }

    if (fileType == FileTypes.pdf) {
        LinkedList<String> newlyGeneratedFiles = new LinkedList<String>();
        for (String fileN : generatedFiles) {
            PsToPdfConverter pstopdf = new PsToPdfConverter(gspath);
            newlyGeneratedFiles.add(pstopdf.convert(fileN));
            // delete the ps file
            File file = new File(fileN);
            file.delete();
        }
        generatedFiles = newlyGeneratedFiles;
    }

    System.out.println("Fini!");

    return generatedFiles;
}

From source file:nl.mpi.tg.eg.frinex.rest.CsvController.java

@RequestMapping(value = "/groupdatacsv", method = RequestMethod.GET)
@ResponseBody/*from ww  w  .j  a  v a  2  s  .c o m*/
public void getGroupData(HttpServletResponse response) throws IOException, CsvExportException {
    //        response.setContentType("application/text");
    //        response.addHeader("Content-Disposition", "attachment; filename=\"groupdata.csv\"");
    //        response.addHeader("Content-Transfer-Encoding", "text");
    CSVPrinter printer = new CSVPrinter(response.getWriter(), CSVFormat.DEFAULT);
    List<String> headerList = new ArrayList();
    headerList.add("Event Date");
    headerList.add("Screen Name");
    headerList.add("Group Name");
    headerList.add("Member Codes");
    headerList.add("Communication Channels");
    headerList.add("Sender Code");
    headerList.add("Respondent Code");
    headerList.add("Index");
    final StimuliTagExpander stimuliTagExpander = new StimuliTagExpander();
    for (String columnTag : stimuliTagExpander.getTagColumns()) {
        headerList.add("Target-" + columnTag);
    }
    headerList.add("Target");
    for (String columnTag : stimuliTagExpander.getTagColumns()) {
        headerList.add("Response-" + columnTag);
    }
    headerList.add("Response");
    for (int distractorIndex : stimuliTagExpander.getDistractorColumns()) {
        for (String columnTag : stimuliTagExpander.getTagColumns()) {
            headerList.add("Distractor-" + (distractorIndex + 1) + "-" + columnTag);
        }
        headerList.add("Distractor-" + (distractorIndex + 1));
    }
    headerList.add("Message");
    headerList.add("ms");
    printer.printRecord(headerList);
    for (GroupData groupData : groupDataRepository.findAll()) {
        List<Object> rowList = new ArrayList();
        rowList.add(groupData.getEventDate());
        rowList.add(groupData.getScreenName());
        rowList.add(groupData.getGroupName());
        rowList.add(groupData.getAllMemberCodes());
        rowList.add(groupData.getGroupCommunicationChannels());
        rowList.add(groupData.getSenderMemberCode());
        rowList.add(groupData.getRespondentMemberCode());
        rowList.add(groupData.getStimulusIndex());
        for (String tagColumn : stimuliTagExpander.getTagColumns(groupData.getStimulusId(), ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getStimulusId());
        for (String tagColumn : stimuliTagExpander.getTagColumns(groupData.getResponseStimulusId(), ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getResponseStimulusId());
        for (String tagColumn : stimuliTagExpander.getDistractorTagColumns(groupData.getStimulusOptionIds(),
                ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getMessageString());
        rowList.add(groupData.getEventMs());
        printer.printRecord(rowList);
    }
    printer.close();
}

From source file:org.apache.ambari.server.api.services.serializers.CsvSerializer.java

@Override
public Object serializeError(ResultStatus error) {
    CSVPrinter csvPrinter = null;
    try {//  w  w w . j ava 2s.c om
        StringBuffer buffer = new StringBuffer();
        csvPrinter = new CSVPrinter(buffer, CSVFormat.DEFAULT);

        csvPrinter.printRecord(Arrays.asList("status", "message"));
        csvPrinter.printRecord(Arrays.asList(error.getStatus().getStatus(), error.getMessage()));

        return buffer.toString();
    } catch (IOException e) {
        //todo: exception handling.  Create ResultStatus 500 and call serializeError
        throw new RuntimeException("Unable to serialize to csv: " + e, e);
    } finally {
        if (csvPrinter != null) {
            try {
                csvPrinter.close();
            } catch (IOException ex) {
            }
        }
    }
}