 let format =
 "activate application \"Cisco AnyConnect Secure Mobility Client\"\n" +
   "tell application \"System Events\" to tell process \"Cisco AnyConnect Secure Mobility Client\"\n" +
+  "tell combo box 1 of window 1 to set value to \"%@\"\n" +
   "click button \"Connect\" of window 1\n" +
   "repeat until window 2 exists\n" +
   "end repeat\n" +

  case let .Failure(error): printErrorAndExit(error)
  }
}
else if arguments.hasOption(Option.help) {
  print(usage)
}
else {
  if let error = connect(defaults.password, network: arguments.argumentForOption(Option.network)).error {
    printErrorAndExit(error)
  }
}

  exit(EXIT_FAILURE)
}

func storePassword(password: String) -> Result<String, QCError> {
  defaults.password = password
  return .Success(password)
}

func storeNetwork(network: String) -> Result<String, QCError> {
  defaults.network = network
  return .Success(network)
}

func updatePassword(password: String?) -> Result<String, QCError> {
  return updateValue(password,
    validator: validatePassword,
    store: storePassword,
    confirmation: {_ in .Success("Password updated! 🍻") }
  )
}

func updateNetwork(network: String?) -> Result<String, QCError> {
  return updateValue(network,
    validator: validateNetwork,
    store: storeNetwork,
    confirmation: {_ in .Success("Network updated! 🍻")})
}

func updateValue<T>(value: T?, validator validate: T? -> Result<T, QCError>, store storeValue: T -> Result<T, QCError>, confirmation sendConfirmation: T -> Result<String, QCError>) -> Result<String, QCError> {
  return
    validate(value)
    >>- storeValue
    >>- sendConfirmation
}

func validateValue<T>(value: T?, error: QCError) -> Result<T, QCError> {
  switch value {
  case let .Some(value): return .Success(value)
  case .None: return .Failure(error)
  }
}

func validatePassword(password: String?) -> Result<String, QCError> {
  return validateValue(password, error: .PasswordNotSet)
}

func validateNetwork(network: String?) -> Result<String, QCError> {
  return validateValue(network, error: .NetworkNotSet)
}

func createScript(password: String, network: String) -> Result<NSAppleScript, QCError> {
  let source = String(format: format, network, password)
  let script = NSAppleScript(source: source)
  return validateValue(script, error: .CouldNotCreateScript(source))
}

func executeScript(script: NSAppleScript) ->  Result<NSAppleEventDescriptor, QCError> {
