function varargout = mfs_trim(cmp, method)

# usage: varargout = mfs_trim(cmp, method)
#
# Input  cmp         Structure with component data
#        method      Method (optional):
#                     "restrained": restrained trim analysis
#                     "unrestrained": unrestrained trim analysis 
#                     (default)
#
# Output varargout   Output data
#
# The output data depend on the component type:
#
#  - aerodynamic:   varargout = cmp
#  - aeroelastic:   varargout = [cmps, cmpa]
#
#    cmps    Structure with data of solid component
#    cmpa    Structure with data of aerodynamic data
#
# The function performs a trim analysis of a rigid or flexible
# aircraft. The values of the trim parameters are written to the
# output file.
#
# If the function is called with two output values, a structure
# with the values of the trim parameters is returned. The field
# names correspond to the names of the trim parameters.
#
# --------------------------------------------------------------------

# Copyright (c) 2017 by Johannes Wandinger

  t0 = clock();

# Check arguments

  if (nargin < 1 || nargin > 2)
     print_usage();
  end
  if (! isstruct(cmp))
     error("mfs_trim: first argument must be a structure\n");
  end

# Default method

  if (nargin == 1)
     method = "unrestrained";
  end

# Branch on model type

  switch cmp.type

  case "aero"
     if (nargout != 1)
        print_usage();
     end
     time_stamp = ignore_function_time_stamp("all");
     mfs_paths("add", "mfs_trim.m", "aero", "util");
     [cmp, rc] = mfs_rigtrim(cmp);
     varargout{1} = cmp;
     mfs_paths("remove");
     ignore_function_time_stamp(time_stamp);

  case "aeroelastic"
     if (nargout != 2)
        print_usage();
     end
     switch method
     case "restrained"
        meth = 1;
     case "unrestrained"
        meth = 2;
     otherwise
        error("mfs_trim: unknown method \"%s\"\n", method);
     end
     time_stamp = ignore_function_time_stamp("all");
     mfs_paths("add", "mfs_trim.m", "aeroelastic", "solid",
               "aero", "util");
     [cmps, cmpa, rc] = mfs_flextrim(cmp, meth);
     varargout = {cmps, cmpa};
     mfs_paths("remove");
     ignore_function_time_stamp(time_stamp);

  otherwise
     error("mfs_trim: model type \"%s\" not supported\n", cmp.type);
  end

  if (rc)
     error("mfs_trim ended with errors\n");
  end

# End

  elapsed_time = etime(clock(), t0);
  printf("%10.4f seconds needed to perform trim analysis\n", ...
         elapsed_time);
  fflush(stdout);

end
