           # assuming that stringify produces a one-liner
           jsonFile.write JSON.stringify(row) + "\n"
 
+
           if numProcessed >= totalRecordsNum
-            console.log "Read in: #{numProcessed}"
+            console.log "#{numProcessed} records were saved temporarily in #{tempFile}"
+            console.log "Now importing into MongoDB"
             util.run "/usr/bin/mongoimport " +
                         "-d aiddata -c aiddata --upsert --upsertFields aiddata_id " +
                         "-u #{mongoConf.user} -p #{mongoConf.password} "+ 

      cntQuery.on 'row', (row) ->
        
        totalRecordsNum = row.count
        console.log "totalRecordsNum: " + totalRecordsNum

        numProcessed = 0


@run = ->
  
  console.log ">>>>>>>>>> Importing aiddata >>>>>>>>>>"

  fs = require 'fs'
  util = (require '../cakeutils').include()

  mongo = require 'mongodb'
  mongoConf = require('../.dbconf').mongodb

  pg = require 'pg'
  pgurl = require('../.dbconf').postgres

  connectToMongo = (dbName, collName, callback) ->
    ifnot = (err, callback) -> if not err then callback() else console.error err
    mongosrv = new mongo.Server(mongoConf.host, mongoConf.port)
    mongodb = new mongo.Db(dbName, mongosrv)
    mongodb.open (err, p_client) -> ifnot err, -> 
      mongodb.authenticate mongoConf.user, mongoConf.password, (err) -> ifnot err, -> 
        mongodb.collection collName, (err, coll) ->
          unless err?
            callback(mongodb, coll)
          else
            console.log err


  limit = undefined

  connectToMongo 'aiddata', 'aiddata', (mongodb, coll) ->
    coll.ensureIndex { aiddata_id : 1 }, -> 
      console.log "Index for aiddata_id ensured"

      mongodb.close()

      tempDir = "data/temp"
      tempFile = tempDir + "/_aiddata.json" 
      util.mkdir tempDir
