1
0
mirror of https://github.com/saitohirga/WSJT-X.git synced 2024-12-20 18:01:15 -05:00
WSJT-X/lib/options.f90

338 lines
10 KiB
Fortran
Raw Normal View History

Added support for use of "Standard" locations for writable files. This allows writable files to be located in the "correct" location for each platform rather than in the directory of the executable which, in general, is not recommended or allowed in some cases. A preprocessor macro WSJT_STANDARD_FILE_LOCATIONS is used to switch be tween old and new functionality, currently it is on by default. It can be turned off by defining it to a false value (0) or more simply with cmake-gui setting the option with the same name. JTAlert can only work with the old non-standard file locations until Laurie VK3AMA chooses to support the new file locations. Even if the above is not enabled; the QSettings file is written to a user specific location so it will be shared by all instances of the program (i.e. across upgrades). See below for multiple concurrent instance support changes. Added a command line parser module for Fortran. Added 'lib/options.f90' to facilitate more complex argument passing to jt9 to cover explicit file locations. Changed the way multiple concurrent instances are handled. This is to allow the program to be run multiple times from the same installation directory. A new wsjtx command line optional argument is available "-r" or "--rig" which enables multiple concurrent instance support. The parameter of the new option is a unique name signifying a rig or equivalent. The name is used as the shared memory segment key and in window titles. The name is also used to access unique settings files and writable data files like ALL.TXT and log files. No attempt has been made to share these files between concurrent instances. If "-r" or "--rig" is used without a parameter it still enables multiple concurrent instance support for that instance. All instances must use a unique parameter, one of which may be empty. The rig name is appended the QCoreApplication::applicationName() for convenient usage like window titles. Set non Qt locale to "C". This ensures that C library functions give consistent results whatever the system locale is set to. QApplication follows the system locale as before. Thus using QApplication and its descendants like widgets and QString for all user visible formating will give correct l10n and using C/C++ library will give consistent formatting across locales. Added top level C++ exception handling to main.cpp. Because the new transceiver framework uses exceptions internally, the main function now handles any exceptions that aren't caught. Retired devsetup, replaced with Configuration. Configuration is a class that encapsulates most of the configuration behavior. Because rig configuration is so closely coupled with rig operation, Configuration serves as a proxy for access to the rig control functions. See Configuration.hpp for more details of the Configuration interface. Menu changes. Various checkable menu actions moved from main menu to the Configuration dialog. The whole settings menu has been retired with the single "Settings..." action moved to the file menu for consistency on Mac where it appears as "Preferences" in line with Mac guidelines. New data models for data used by the application. ADIF amateur band parameters, free text message macros, spot working frequencies and, station information (station descriptions and transverter offsets per band) each implement the QAbstractItemModel interface allowing them to be used directly with Qt view widgets (Bands.hpp, FrequencyList.hpp and, StationList.hpp). Configuration manages maintenance of an instance of all but the former of the above models. The ADIF band model is owned by Configuration but requires no user maintenance as it is immutable. Band combo box gets more functionality. This widget is now an editable QComboBox with some extra input capabilities. The popup list is still the list of spot working frequencies, now showing the actual frequency decorated with the band name. This allows multiple spot frequencies on a band if required. The line edit allows direct frequency entry in mega-Hertz with a completer built in to suggest the available spot working frequencies. It also allows band name entry where the first available spot working frequency is selected. Recognized band names are those that are defined by the ADIF specification and can be found in in the implementation of the ADIF bands model (Bands.cpp). If an out of band frequency is chosen, the line edit shows a warning red background and the text "OOB". Out of band is only defined by the ADIF band limits which in general are wider than any entities regulations. Qt 5.2 now supports default audio i/p and o/p devices. These devices are placeholders for whatever the user defines as the default device. Because of this they need special treatment as the actual device used is chosen at open time behind the scenes. Close-down behavior is simplified. The close-down semantics were broken such that some objects were not being shut down cleanly, this required amendments to facilitate correct close down of threads. User font selection added to Configuration UI. Buttons to set the application font and the font for the band and Rx frequency activity widgets have been added to the Configuration UI to replace the file based font size control. Free text macros now selected directly. The free text line edit widgets are now editable combo boxes that have the current free text macro definitions as their popup list. The old context menu to do this has been retired. Astronomical data window dynamically formatted and has font a chooser. This window is now autonomous, has its own font chooser and, dynamically resizes to cover the contents. Double click to Tx enabled now has its own widget in the status bar. QDir used for portable path and file name handling throughout. The "Monitor", "Decode", "Enable Tx" and, "Tune" buttons are now checkable. Being checkable allows these buttons control their own state and rendering. Calls to PSK Reporter interface simplified. In mainwindow.cpp the calls to this interface are rationalized to just 3 locations. Manipulation of ALL.TXT simplified. Moved, where possible, to common functions. Elevated frequency types to be Qt types. Frequency and FrequencyDelta defined as Qt types in their meta-type system (Radio.hpp). They are integral types for maximum accuracy. Re-factored rig control calls in mainwindow.cpp. The new Configuration proxy access to rig control required many changes (mostly simplifications) to the MainWindow rig control code. Some common code has been gathered in member functions like qsy(), monitor(), band_changed() and auto_tx_mode(). Rig control enhancements. The rig control for clients interface is declared as an abstract interface (See Transceiver.hpp). Concrete implementations of this interface are provided for the Hamlib rig control library, DX Lab Suite Commander via a TCP/IP command channel, Ham Radio Deluxe also via a TCP/IP command channel and, OmniRig via its Windows COM server interface. Concrete Transceiver implementations are expected to be moved to a separate thread after construction since many operations are blocking and not suitable for running in a GUI thread. To facilitate this all instantiation of concrete Transceiver instances are handled by Configuration using a factory class (TransceiverFactory) for configuration parameter based instantiation. Various common functionality shared by different rig interface implementations are factored out into helper base classes that implement or delegate parts of the Transceiver interface. They are TransceiverBase which caches state to minimize expensive rig commands, it also maps the Transceiver interface into a more convenient form for implementation (template methods). PollingTransceiver that provides a state polling mechanism that only reports actual changes. EmulateSplitTransceiver that provides split operation by QSYing on PTT state changes. EmulateSplitTransceiver can be used with any implementation as it follows the GoF Decorator pattern and can wrap any Transceiver implementation. OmniRigTransceiver is derived directly from TransceiverBase since it doesn't require polling due to its asynchronous nature. OmniRigTransceiver is only built on Windows as it is a COM server client. To build it you must first install the OmniRig client on the development machine (http://www.dxatlas.com/omnirig/). DXLabSuiteCommanderTransceiver derives from PollingTransceiver since it is a synchronous communications channel. No third party library is required for this interface. HRDTransceiver also derives from PollingTransceiver. The HRD interface library has been reverse engineered to provide functionality with all available versions of HRD. No third party libraries are required. HamlibTransceiver likewise derives from PollingTransceiver since the Hamlib asynchronous interface is non-functional. Although this class will interface with the release version of Hamlib (1.2.15.3); for correct operation on most rigs it needs to run with the latest master branch code of Hamlib. During development many changes to Hamlib have been submitted and accepted, hence this requirement. Hamlib source can be obtained from git://git.code.sf.net/p/hamlib/code and at the time of writing he master branch was at SHA 6e4432. The Hamlib interface directly calls the "C" interface and the modified rigclass.{h,cpp} files have been retired. There is a rig type selection of "None" which may be used for non-CAT rigs, this is actually a connection to the dummy Hamlib device. PollingTransvceiver derives from TransceiverBase and TransceiverBase derives from the Transceiver interface. Each interface implementation offers some possibility of PTT control via a different serial port than the CAT port. We also support PTT control directly via a second serial port. This is done by delegating to a dummy Hamlib instance which is only used for PTT control. This means that DXLabSuiteCommanderTransceiver, HRDTransceiver and OmniRigTransceiver always wrap a dummy HamlibTransceiver instance. The factory class TransceiverFactory manages all these constructional complexities. Serial port selection combo boxes are now editable with a manually entered value being saved to the settings file. This allows a non-standard port device to be used without having to edit the settings file manually. For TCP/IP network CAT interfaces; the network address and port may be specified allowing the target device to be located on a different machine from the one running wsjtx if required. The default used when the address field is left blank is the correct one for normal usage on the local host. Selecting a polling interval of zero is no longer possible, this is because the rig control capability can no longer support one way connection. This is in line with most other CAT control software. In the Configuration dialog there are options to select split mode control by the software and mode control by the software. For the former "None", "Rig" and "Fake it" are available, for the latter "None", "USB" and, "Data" are available. Because tone generation is implicitly linked to split mode operation; it is no longer possible to have the software in split mode and the rig not or vice versa. This may mean some rigs cannot be used in split mode and therefore not in dual JT65+JT9 until issues with CAT control with that rig are resolved. Single mode with VOX keying and no CAT control are still possible so even the most basic transceiver setup is supported as before. Configuration now supports a frequency offset suitable for transverter operation. The station details model (StationList.hpp) includes a column to store an offset for each band if required. CMake build script improvements. The CMakeLists.txt from the 'lib' directory has been retired with its contents merged into the top level CMakeLists.txt. Install target support has been greatly improved with the Release build configuration now building a fully standalone installation on Mac and Windows. The Debug configuration still builds an installation that has environment dependencies for external libraries, which is desirable for testing and debugging. Package target support is largely complete for Mac, Windows and, Linux, it should be possible to build release installers directly from CMake/CPack. Cmake FindXXXX.cmake modules have been added to improve the location of fftw-3 and Hamlib packages. Version numbers are now stored in Versions.cmake and work in concert with automatic svn revision lookup during build. The version string becomes 'rlocal'± if there are any uncommitted changes in the build source tree. Moved resource like files to Qt resources. Because location of resource files (when they cannot go into the installation directory because of packaging rules) is hard to standardize. I have used the Qt resource system for all ancillary data files. Some like kvasd.dat are dumped out to the temp (working directory) because they are accessed by an external program, others like the audio samples are copied out so they appear in the data directory under the default save directory. git-svn-id: svn+ssh://svn.code.sf.net/p/wsjt/wsjt/branches/wsjtx@3929 ab8295b8-cf94-4d9e-aec4-7959e3be5d79
2014-03-26 09:21:00 -04:00
module options
!
! Source code copied from:
! http://fortranwiki.org/fortran/show/Command-line+arguments
!
implicit none
type option
!> Long name.
character(len=100) :: name
!> Does the option require an argument?
logical :: has_arg
!> Corresponding short name.
character :: chr
!> Description.
character(len=500) :: descr
!> Argument name, if required.
character(len=20) :: argname
contains
procedure :: print => print_opt
end type option
contains
!> Parse command line options. Options and their arguments must come before
!> all non-option arguments. Short options have the form "-X", long options
!> have the form "--XXXX..." where "X" is any character. Parsing can be
!> stopped with the option '--'.
!> The following code snippet illustrates the intended use:
!> \code
!> do
!> call getopt (..., optchar=c, ...)
!> if (stat /= 0) then
!> ! optional error handling
!> exit
!> end if
!> select case (c)
!> ! process options
!> end select
!> end do
!> \endcode
subroutine getopt (options, longopts, optchar, optarg, arglen, stat, &
offset, remain, err)
use iso_fortran_env, only: error_unit
!> String containing the characters that are valid short options. If
!> present, command line arguments are scanned for those options.
!> If a character is followed by a colon (:) its corresponding option
!> requires an argument. E.g. "vn:" defines two options -v and -n with -n
!> requiring an argument.
character(len=*), intent(in), optional :: options
!> Array of long options. If present, options of the form '--XXXX...' are
!> recognised. Each option has an associated option character. This can be
!> any character of default kind, it is just an identifier. It can, but
!> doesn't have to, match any character in the options argument. In fact it
!> is possible to only pass long options and no short options at all.
!> Only name, has_arg and chr need to be set.
type(option), intent(in), optional :: longopts(:)
!> If stat is not 1, optchar contains the option character that was parsed.
!> Otherwise its value is undefined.
character, intent(out), optional :: optchar
!> If stat is 0 and the parsed option requires an argument, optarg contains
!> the first len(optarg) (but at most 500) characters of that argument.
!> Otherwise its value is undefined. If the arguments length exceeds 500
!> characters and err is .true., a warning is issued.
character(len=*), intent(out), optional :: optarg
!> If stat is 0 and the parsed option requires an argument, arglen contains
!> the actual length of that argument. Otherwise its value is undefined.
!> This can be used to make sure the argument was not truncated by the
!> limited length of optarg.
integer, intent(out), optional :: arglen
!> Status indicator. Can have the following values:
!> - 0: An option was successfully parsed.
!> - 1: Parsing stopped successfully because a non-option or '--' was
!> encountered.
!> - -1: An unrecognised option was encountered.
!> - -2: A required argument was missing.
!> .
!> Its value is never undefined.
integer, intent(out), optional :: stat
!> If stat is 1, offset contains the number of the argument before the
!> first non-option argument, i.e. offset+n is the nth non-option argument.
!> If stat is not 1, offset contains the number of the argument that would
!> be parsed in the next call to getopt. This number can be greater than
!> the actual number of arguments.
integer, intent(out), optional :: offset
!> If stat is 1, remain contains the number of remaining non-option
!> arguments, i.e. the non-option arguments are in the range
!> (offset+1:offset+remain). If stat is not 1, remain is undefined.
integer, intent(out), optional :: remain
!> If err is present and .true., getopt prints messages to the standard
!> error unit if an error is encountered (i.e. whenever stat would be set
!> to a negative value).
logical, intent(in), optional :: err
integer, save :: pos = 1, cnt = 0
character(len=500), save :: arg
integer :: chrpos, length, st, id = 0
Added support for use of "Standard" locations for writable files. This allows writable files to be located in the "correct" location for each platform rather than in the directory of the executable which, in general, is not recommended or allowed in some cases. A preprocessor macro WSJT_STANDARD_FILE_LOCATIONS is used to switch be tween old and new functionality, currently it is on by default. It can be turned off by defining it to a false value (0) or more simply with cmake-gui setting the option with the same name. JTAlert can only work with the old non-standard file locations until Laurie VK3AMA chooses to support the new file locations. Even if the above is not enabled; the QSettings file is written to a user specific location so it will be shared by all instances of the program (i.e. across upgrades). See below for multiple concurrent instance support changes. Added a command line parser module for Fortran. Added 'lib/options.f90' to facilitate more complex argument passing to jt9 to cover explicit file locations. Changed the way multiple concurrent instances are handled. This is to allow the program to be run multiple times from the same installation directory. A new wsjtx command line optional argument is available "-r" or "--rig" which enables multiple concurrent instance support. The parameter of the new option is a unique name signifying a rig or equivalent. The name is used as the shared memory segment key and in window titles. The name is also used to access unique settings files and writable data files like ALL.TXT and log files. No attempt has been made to share these files between concurrent instances. If "-r" or "--rig" is used without a parameter it still enables multiple concurrent instance support for that instance. All instances must use a unique parameter, one of which may be empty. The rig name is appended the QCoreApplication::applicationName() for convenient usage like window titles. Set non Qt locale to "C". This ensures that C library functions give consistent results whatever the system locale is set to. QApplication follows the system locale as before. Thus using QApplication and its descendants like widgets and QString for all user visible formating will give correct l10n and using C/C++ library will give consistent formatting across locales. Added top level C++ exception handling to main.cpp. Because the new transceiver framework uses exceptions internally, the main function now handles any exceptions that aren't caught. Retired devsetup, replaced with Configuration. Configuration is a class that encapsulates most of the configuration behavior. Because rig configuration is so closely coupled with rig operation, Configuration serves as a proxy for access to the rig control functions. See Configuration.hpp for more details of the Configuration interface. Menu changes. Various checkable menu actions moved from main menu to the Configuration dialog. The whole settings menu has been retired with the single "Settings..." action moved to the file menu for consistency on Mac where it appears as "Preferences" in line with Mac guidelines. New data models for data used by the application. ADIF amateur band parameters, free text message macros, spot working frequencies and, station information (station descriptions and transverter offsets per band) each implement the QAbstractItemModel interface allowing them to be used directly with Qt view widgets (Bands.hpp, FrequencyList.hpp and, StationList.hpp). Configuration manages maintenance of an instance of all but the former of the above models. The ADIF band model is owned by Configuration but requires no user maintenance as it is immutable. Band combo box gets more functionality. This widget is now an editable QComboBox with some extra input capabilities. The popup list is still the list of spot working frequencies, now showing the actual frequency decorated with the band name. This allows multiple spot frequencies on a band if required. The line edit allows direct frequency entry in mega-Hertz with a completer built in to suggest the available spot working frequencies. It also allows band name entry where the first available spot working frequency is selected. Recognized band names are those that are defined by the ADIF specification and can be found in in the implementation of the ADIF bands model (Bands.cpp). If an out of band frequency is chosen, the line edit shows a warning red background and the text "OOB". Out of band is only defined by the ADIF band limits which in general are wider than any entities regulations. Qt 5.2 now supports default audio i/p and o/p devices. These devices are placeholders for whatever the user defines as the default device. Because of this they need special treatment as the actual device used is chosen at open time behind the scenes. Close-down behavior is simplified. The close-down semantics were broken such that some objects were not being shut down cleanly, this required amendments to facilitate correct close down of threads. User font selection added to Configuration UI. Buttons to set the application font and the font for the band and Rx frequency activity widgets have been added to the Configuration UI to replace the file based font size control. Free text macros now selected directly. The free text line edit widgets are now editable combo boxes that have the current free text macro definitions as their popup list. The old context menu to do this has been retired. Astronomical data window dynamically formatted and has font a chooser. This window is now autonomous, has its own font chooser and, dynamically resizes to cover the contents. Double click to Tx enabled now has its own widget in the status bar. QDir used for portable path and file name handling throughout. The "Monitor", "Decode", "Enable Tx" and, "Tune" buttons are now checkable. Being checkable allows these buttons control their own state and rendering. Calls to PSK Reporter interface simplified. In mainwindow.cpp the calls to this interface are rationalized to just 3 locations. Manipulation of ALL.TXT simplified. Moved, where possible, to common functions. Elevated frequency types to be Qt types. Frequency and FrequencyDelta defined as Qt types in their meta-type system (Radio.hpp). They are integral types for maximum accuracy. Re-factored rig control calls in mainwindow.cpp. The new Configuration proxy access to rig control required many changes (mostly simplifications) to the MainWindow rig control code. Some common code has been gathered in member functions like qsy(), monitor(), band_changed() and auto_tx_mode(). Rig control enhancements. The rig control for clients interface is declared as an abstract interface (See Transceiver.hpp). Concrete implementations of this interface are provided for the Hamlib rig control library, DX Lab Suite Commander via a TCP/IP command channel, Ham Radio Deluxe also via a TCP/IP command channel and, OmniRig via its Windows COM server interface. Concrete Transceiver implementations are expected to be moved to a separate thread after construction since many operations are blocking and not suitable for running in a GUI thread. To facilitate this all instantiation of concrete Transceiver instances are handled by Configuration using a factory class (TransceiverFactory) for configuration parameter based instantiation. Various common functionality shared by different rig interface implementations are factored out into helper base classes that implement or delegate parts of the Transceiver interface. They are TransceiverBase which caches state to minimize expensive rig commands, it also maps the Transceiver interface into a more convenient form for implementation (template methods). PollingTransceiver that provides a state polling mechanism that only reports actual changes. EmulateSplitTransceiver that provides split operation by QSYing on PTT state changes. EmulateSplitTransceiver can be used with any implementation as it follows the GoF Decorator pattern and can wrap any Transceiver implementation. OmniRigTransceiver is derived directly from TransceiverBase since it doesn't require polling due to its asynchronous nature. OmniRigTransceiver is only built on Windows as it is a COM server client. To build it you must first install the OmniRig client on the development machine (http://www.dxatlas.com/omnirig/). DXLabSuiteCommanderTransceiver derives from PollingTransceiver since it is a synchronous communications channel. No third party library is required for this interface. HRDTransceiver also derives from PollingTransceiver. The HRD interface library has been reverse engineered to provide functionality with all available versions of HRD. No third party libraries are required. HamlibTransceiver likewise derives from PollingTransceiver since the Hamlib asynchronous interface is non-functional. Although this class will interface with the release version of Hamlib (1.2.15.3); for correct operation on most rigs it needs to run with the latest master branch code of Hamlib. During development many changes to Hamlib have been submitted and accepted, hence this requirement. Hamlib source can be obtained from git://git.code.sf.net/p/hamlib/code and at the time of writing he master branch was at SHA 6e4432. The Hamlib interface directly calls the "C" interface and the modified rigclass.{h,cpp} files have been retired. There is a rig type selection of "None" which may be used for non-CAT rigs, this is actually a connection to the dummy Hamlib device. PollingTransvceiver derives from TransceiverBase and TransceiverBase derives from the Transceiver interface. Each interface implementation offers some possibility of PTT control via a different serial port than the CAT port. We also support PTT control directly via a second serial port. This is done by delegating to a dummy Hamlib instance which is only used for PTT control. This means that DXLabSuiteCommanderTransceiver, HRDTransceiver and OmniRigTransceiver always wrap a dummy HamlibTransceiver instance. The factory class TransceiverFactory manages all these constructional complexities. Serial port selection combo boxes are now editable with a manually entered value being saved to the settings file. This allows a non-standard port device to be used without having to edit the settings file manually. For TCP/IP network CAT interfaces; the network address and port may be specified allowing the target device to be located on a different machine from the one running wsjtx if required. The default used when the address field is left blank is the correct one for normal usage on the local host. Selecting a polling interval of zero is no longer possible, this is because the rig control capability can no longer support one way connection. This is in line with most other CAT control software. In the Configuration dialog there are options to select split mode control by the software and mode control by the software. For the former "None", "Rig" and "Fake it" are available, for the latter "None", "USB" and, "Data" are available. Because tone generation is implicitly linked to split mode operation; it is no longer possible to have the software in split mode and the rig not or vice versa. This may mean some rigs cannot be used in split mode and therefore not in dual JT65+JT9 until issues with CAT control with that rig are resolved. Single mode with VOX keying and no CAT control are still possible so even the most basic transceiver setup is supported as before. Configuration now supports a frequency offset suitable for transverter operation. The station details model (StationList.hpp) includes a column to store an offset for each band if required. CMake build script improvements. The CMakeLists.txt from the 'lib' directory has been retired with its contents merged into the top level CMakeLists.txt. Install target support has been greatly improved with the Release build configuration now building a fully standalone installation on Mac and Windows. The Debug configuration still builds an installation that has environment dependencies for external libraries, which is desirable for testing and debugging. Package target support is largely complete for Mac, Windows and, Linux, it should be possible to build release installers directly from CMake/CPack. Cmake FindXXXX.cmake modules have been added to improve the location of fftw-3 and Hamlib packages. Version numbers are now stored in Versions.cmake and work in concert with automatic svn revision lookup during build. The version string becomes 'rlocal'± if there are any uncommitted changes in the build source tree. Moved resource like files to Qt resources. Because location of resource files (when they cannot go into the installation directory because of packaging rules) is hard to standardize. I have used the Qt resource system for all ancillary data files. Some like kvasd.dat are dumped out to the temp (working directory) because they are accessed by an external program, others like the audio samples are copied out so they appear in the data directory under the default save directory. git-svn-id: svn+ssh://svn.code.sf.net/p/wsjt/wsjt/branches/wsjtx@3929 ab8295b8-cf94-4d9e-aec4-7959e3be5d79
2014-03-26 09:21:00 -04:00
character :: chr
logical :: long
if (cnt == 0) cnt = command_argument_count()
long = .false.
! no more arguments left
if (pos > cnt) then
pos = pos - 1
st = 1
goto 10
end if
call get_command_argument (pos, arg, length)
! is argument an option?
if (arg(1:1) == '-') then
chr = arg(2:2)
! too long ('-xxxx...') for one dash?
if (chr /= '-' .and. len_trim(arg) > 2) then
st = -1
goto 10
end if
! forced stop ('--')
if (chr == '-' .and. arg(3:3) == ' ') then
st = 1
goto 10
end if
! long option ('--xxx...')
if (chr == '-') then
long = .true.
! check if valid
id = lookup(arg(3:))
! option is invalid, stop
if (id == 0) then
st = -1
goto 10
end if
chr = longopts(id)%chr
! check if option requires an argument
if (.not. longopts(id)%has_arg) then
st = 0
goto 10
end if
! check if there are still arguments left
if (pos == cnt) then
st = -2
goto 10
end if
! go to next position
pos = pos + 1
! get argument
call get_command_argument (pos, arg, length)
! make sure it is not an option
if (arg(1:1) == '-') then
st = -2
pos = pos - 1
goto 10
end if
end if
! short option
! check if valid
if (present(options)) then
chrpos = scan(options, chr)
else
chrpos = 0
end if
! option is invalid, stop
if (chrpos == 0) then
st = -1
goto 10
end if
! look for argument requirement
if (chrpos < len_trim(options)) then
if (options(chrpos+1:chrpos+1) == ':') then
! check if there are still arguments left
if (pos == cnt) then
st = -2
goto 10
end if
! go to next position
pos = pos + 1
! get argument
call get_command_argument (pos, arg, length)
! make sure it is not an option
if (arg(1:1) == '-') then
st = -2
pos = pos - 1
goto 10
end if
end if
end if
! if we get to this point, no error happened
! return option and the argument (if there is one)
st = 0
goto 10
end if
! not an option, parsing stops
st = 1
! we are already at the first non-option argument
! go one step back to the last option or option argument
pos = pos - 1
! error handling and setting of return values
10 continue
if (present(err)) then
if (err) then
select case (st)
case (-1)
write (error_unit, *) "error: unrecognised option: " // trim(arg)
case (-2)
if (.not. long) then
write (error_unit, *) "error: option -" // chr &
// " requires an argument"
else
write (error_unit, *) "error: option --" &
// trim(longopts(id)%name) // " requires an argument"
end if
end select
end if
end if
if (present(optchar)) optchar = chr
if (present(optarg)) optarg = arg
if (present(arglen)) arglen = length
if (present(stat)) stat = st
if (present(offset)) offset = pos
if (present(remain)) remain = cnt-pos
! setup pos for next call to getopt
pos = pos + 1
contains
integer function lookup (name)
character(len=*), intent(in) :: name
integer :: i
! if there are no long options, skip the loop
if (.not. present(longopts)) goto 10
do i = 1, size(longopts)
if (name == longopts(i)%name) then
lookup = i
return
end if
end do
! if we get to this point, the option was not found
10 lookup = 0
end function lookup
end subroutine getopt
!============================================================================
!> Print an option in the style of a man page. I.e.
!> \code
!> -o arg
!> --option arg
!> description.................................................................
!> ............................................................................
!> \endcode
subroutine print_opt (opt, unit)
!> the option
class(option), intent(in) :: opt
!> logical unit number
integer, intent(in) :: unit
integer :: l, c1, c2
if (opt%has_arg) then
write (unit, '(1x,"-",a,1x,a)') opt%chr, trim(opt%argname)
write (unit, '(1x,"--",a,1x,a)') trim(opt%name), trim(opt%argname)
else
write (unit, '(1x,"-",a)') opt%chr
write (unit, '(1x,"--",a)') trim(opt%name)
end if
l = len_trim(opt%descr)
! c1 is the first character of the line
! c2 is one past the last character of the line
c1 = 1
do
if (c1 > l) exit
! print at maximum 4+76 = 80 characters
c2 = min(c1 + 76, 500)
! if not at the end of the whole string
if (c2 /= 500) then
! find the end of a word
do
if (opt%descr(c2:c2) == ' ') exit
c2 = c2-1
end do
end if
write (unit, '(4x,a)') opt%descr(c1:c2-1)
c1 = c2+1
end do
end subroutine print_opt
end module options