;;+
; NAME:
;   inms_idl_species_label - forms a string with imbedded format control
;
;  Created by  on .
;  Copyright (c)  __Southwest Research Institute__. All rights reserved.
;
function inms_idl_species_label, sFormula
;
; PURPOSE:
;  converts a formula string to a text string suitable for output with xyouts
;  with atomic numbers shown as superscripts and atom counts as subscripts
;
; RETURNS;
;   a character string for display
;
; ARGUMENTS:
;  sFormula - a character string with superscript numbers denoted by ^nn
;             and subscript numbers denoted nn. Example ^13CH4 is the formulat
;             for methane with the carbon 13 isotope
;
; RESTRUCTIONS:
;   Input argument must be a scalar
;
;
; MODIFICATION HISTORY:
;  date         by         description
;  30-Nov-2006  D. Gell    Initial coding
;-
;=================================================================================
    nError = 0
    catch, nError
    if nError ne 0 then begin
        catch, /cancel
        !p = psave
        inms_post_message
        return, ''
    endif 

    bSubscript=0            ;; set when a subscript is encountered
    bSuperscript=0          ;; set when superscript is encountered
    sResult=''              ;; resultant string
    
	if n_elements(sFormula) ne 1 then begin 
		message, 'invalid or missing input string, must be a scalar'
	endif
		
    for nI=0,strlen(sFormula)-1 do begin
        sChar=strmid(sFormula, nI, 1)
        case 1 of
            sChar eq '^': begin
                bSuperscript=1
                sResult=sResult + '!u'
            end 

            stregex(sChar,'[0-9]',/boolean): begin
                if ~bSuperScript && ~bSubscript then begin
                    bSubscript=1
                    sResult=sResult + '!d'
                end 
                sResult=sResult+sChar
            end

            stregex(sChar,'[a-zA-Z]',/boolean): begin
                if bSubscript|| bSuperscript then sResult=sResult + '!n'
                bSuperscript=0
                bSubscript=0
                sResult=sResult + sChar                 
            end 
            else:  sResult=sResult + sChar
        endcase
    endfor
    if bSuperscript || bSubscript then sResult=sResult + '!n'
    return, sResult
end


