public function exportCsv($filename, $data, $options = array())
    {
        $config = $this->getConfig();
        $options = array_merge($config, $options);

        if (!$this->_trigger('beforeExportCsv', array($filename, $data, $options))) {
            return false;
        }

        // open the file
        if ($file = fopen($filename, 'w')) {
            // Add BOM for proper display UTF-8 in EXCEL
            if($options['excel_bom']) {
                fputs($file, chr(239) . chr(187) . chr(191));
            }
            // Iterate through and format data
            $firstRecord = true;
            foreach ($data as $record) {
                $record = $record->toArray();
                $row = array();
                foreach ($record as $field => $value) {
                    if ( !is_array($value) ) {
                        $row[] = $value;
                        if ($firstRecord) {
                            $headers[] = $field;
                        }
                        continue;
                    }
                    $table = $field;
                    $fields = $value;
                    // TODO add parsing for HABTM
                    foreach ($fields as $field => $value) {
                        if (!is_array($value)) {
                            if ($firstRecord) {
                                $headers[] = $table . '.' . $field;
                            }
                            $row[] = $value;
                        } // TODO due to HABTM potentially being huge, creating an else might not be plausible
                    }
                }
                $rows[] = $row;
                $firstRecord = false;
            }

            if ($options['headers']) {
                // write the 1st row as headings
                fputcsv($file, $headers, $options['delimiter'], $options['enclosure']);
            }
            // Row counter
            $r = 0;
            foreach ($rows as $row) {
                fputcsv($file, $row, $options['delimiter'], $options['enclosure']);
                $r++;
            }

            // close the file
            fclose($file);

            $this->_trigger('afterExportCsv', array());

            return $r;
        } else {
            return false;
        }
    }