# File raggle, line 5587
def main
  Raggle::HTML::init_tagset

  # load config files (config.rb, and feeds.yaml)
  opts = Raggle::Engine::load_config
  
  # create cache lock
  Raggle::Engine::create_cache_lock if $config['use_cache_lock']
  
  # handle command-line mode
  $config['raggle_mode'] = opts['mode']
  Raggle::CLI::handle_mode(opts)

  # load theme
  puts $config['msg_load_theme']
  if $config['load_theme'] && test(?e, $config['theme_path'])
    $config['theme'] = YAML::load(File::open($config['theme_path']))
  end

  $config['run_http_server'] = true unless $HAVE_LIB['ncurses'] ||
                                           $HAVE_LIB['drb']
  # initialize default globals
  $view_source = false
  $update_wins = false
  $old_win = [0]

  # Draw windows and such.
  # (unless we're running as a daemon)
  Raggle::Interfaces::NcursesInterface::init unless \
    $config['run_http_server'] || $config['run_drb_server']
  
  # load feed cache
  Raggle::Engine::load_feed_cache if $config['load_feed_cache'] &&
                                     test(?e, $config['feed_cache_path'])
  
  # set up Net::HTTP module
  Net::HTTP.version_1_1

  # start feed grabbing thread
  $feed_thread = Raggle::Engine::start_feed_thread

  # start config saving thread
  $save_thread = Raggle::Engine::start_save_thread

  # set up HTTP or DRb server
  if $HAVE_LIB['webrick'] && $config['run_http_server']
    $http_thread = Raggle::Interfaces::HTTPServerInterface::init
  elsif $HAVE_LIB['drb'] && $config['run_drb_server']
    $drb_thread = Raggle::Interfaces::DRbServerInterface::init
  end

  # set thread priorities
  Raggle::Engine::set_thread_priorities

  begin
    if $config['run_http_server']
      Raggle::Interfaces::HTTPServerInterface::main_loop
    elsif $config['run_drb_server']
      Raggle::Interfaces::DRbServerInterface::main_loop
    else # ncurses interface
      Raggle::Interfaces::NcursesInterface::main_loop
    end
    
    # clean up screen on exit (unless running HTTP server)
    Ncurses::endwin unless $config['run_http_server'] ||
                           $config['run_drb_server']

    # stop feed grabbing thread
    $feed_thread.exit if $feed_thread.alive?

    # stop config-saving thread
    $save_thread.exit if $save_thread.alive?

    # save feed cache, feed list, and theme
    Raggle::Engine::save_config
  ensure
    unless $done # if done is set then we're exiting cleanly
      # clean up either screen or HTTP server on exit
      if $config['run_http_server']
        $http_server.shutdown
      elsif $config['run_drb_server']
        nil
      else
        Ncurses::endwin 
      end
      
      # save feed cache, feed list, and theme (if requested)
      Raggle::Engine::save_config if $config['save_on_crash']
    end
      
    # unlock everything
    Raggle::Engine::destroy_cache_lock if $config['use_cache_lock'] &&
                                          $config['cache_lock']
    
    $stdout.puts $config['msg_thanks']
  end
end