Debian Codegraph @

src/asciiutils.f90

raw
1 !-----------------------------------------------------------------
2 !
3 ! This file is (or was) part of SPLASH, a visualisation tool
4 ! for Smoothed Particle Hydrodynamics written by Daniel Price:
5 !
6 ! http://users.monash.edu.au/~dprice/splash
7 !
8 ! SPLASH comes with ABSOLUTELY NO WARRANTY.
9 ! This is free software; and you are welcome to redistribute
10 ! it under the terms of the GNU General Public License
11 ! (see LICENSE file for details) and the provision that
12 ! this notice remains intact. If you modify this file, please
13 ! note section 2a) of the GPLv2 states that:
14 !
15 ! a) You must cause the modified files to carry prominent notices
16 ! stating that you changed the files and the date of any change.
17 !
18 ! Copyright (C) 2005-2023 Daniel Price. All rights reserved.
19 ! Contact: [email protected]
20 !
21 !-----------------------------------------------------------------
22
23 !---------------------------------------------------------------------------
24 ! module containing various utility subroutines
25 ! related to reading from ascii files and dealing with string variables
26 !
27 ! written by Daniel Price, University of Exeter 2007 24th April '07
28 ! revised at Monash University, 2008 -
29 ! [email protected]
30 !
31 ! this is a standalone module with no dependencies
32 !---------------------------------------------------------------------------
33 module asciiutils
34 implicit none
35 public :: read_asciifile,get_ncolumns,get_nrows,ncolumnsline,safename,basename,numfromfile
36 public :: cstring,fstring,add_escape_chars
37 public :: string_replace,string_delete,get_nheaderlines,string_sub
38 public :: ucase,lcase,strip
39 public :: get_line_containing
40 public :: enumerate,isdigit,get_digits,integer_to_string,split
41 public :: get_column_labels,read_column_labels
42 public :: match_tag,match_taglist,append_number,make_tags_unique,get_value
43 public :: match_column,match_tag_start,match_integer,match_lists
44 public :: count_non_blank,find_repeated_tags,count_char
45 public :: get_extensions,readline_csv,extension
46 public :: sort_filenames_for_comparison
47 public :: read_var_from_file
48 integer, parameter :: max_line_length = 10000 ! for finding number of columns
49
50 private
51
52 !--------------------------------------------------
53 ! Generic interface to ascii file read for either
54 ! character arrays (ie. each line is an element)
55 ! or an array of real numbers
56 !--------------------------------------------------
57 interface read_asciifile
58 module procedure read_asciifile_char, read_asciifile_real,&
59 read_asciifile_real_string, read_asciifile_realarr, &
60 read_asciifile_int
61 end interface read_asciifile
62
63 interface string_delete
64 module procedure string_delete1,string_delete_array
65 end interface string_delete
66
67 contains
68
69 !---------------------------------------------------------------------------
70 ! Generic subroutine to read all lines of an ascii file
71 ! returns array of character strings (one per line)
72 ! up to a maximum corresponding to the size of the array
73 !---------------------------------------------------------------------------
74 subroutine read_asciifile_char(filename,nlinesread,charline,ierror,skip)
75 character(len=*), intent(in) :: filename
76 integer, intent(out) :: nlinesread
77 character(len=*), dimension(:), intent(out) :: charline
78 integer, intent(out), optional :: ierror
79 logical, intent(in), optional :: skip
80 integer :: ierr,i,j,maxlines,iunit
81 logical :: iexist,do_skip
82 character(len=1) :: temp
83
84 nlinesread = 0
85 if (present(ierror)) ierror = 0
86
87 !--if file does not exist, do nothing and return
88 inquire(file=filename,exist=iexist)
89 if (.not.iexist) then
90 if (present(ierror)) ierror = -1
91 return
92 endif
93
94 open(newunit=iunit,file=filename,status='old',form='formatted',iostat=ierr)
95 !--error opening file (but file does exist)
96 if (ierr /= 0) then
97 print "(a)",' ERROR opening '//trim(filename)
98 if (present(ierror)) ierror = ierr
99 return
100 endif
101
102 ! read lines from file, skipping blank lines
103 maxlines = size(charline)
104 i = 0
105 j = 1
106 ierr = 0
107 do_skip = .false.
108 if (present(skip)) do_skip = skip
109 over_lines: do while(j <= maxlines .and. ierr == 0)
110 i = i + 1
111 read(iunit,"(a)",iostat=ierr) charline(j)
112 ! skip blank and comment lines
113 if (ierr == 0) then
114 if (do_skip) then
115 temp = adjustl(charline(j))
116 if (len_trim(charline(j)) > 0 .and. temp(1:1) /= '#') j = j + 1
117 else
118 j = j + 1
119 endif
120 endif
121 enddo over_lines
122 nlinesread = j-1
123
124 ! emit warnings if errors or reached array limits
125 if (nlinesread >= maxlines) then
126 !--end of array limits
127 ! check to see if there is anything more in the file. Report error if there is.
128 read(iunit,"(a)",iostat=ierr)
129 if (ierr==0) then
130 print "(/,a,i6,/)",' WARNING: array limits reached reading '//trim(filename)//', max = ',maxlines
131 endif
132 nlinesread = min(maxlines,nlinesread-1)
133 elseif (ierr > 0) then
134 print "(a,i6)",' ERROR reading '//trim(filename)//' at line ',i
135 if (present(ierror)) ierror = 1
136 endif
137 close(unit=iunit)
138
139 end subroutine read_asciifile_char
140
141 !---------------------------------------------------------------------------
142 ! Generic subroutine to read all lines of an ascii file
143 ! returns array of real numbers (either one per line or all on same line)
144 ! up to a maximum corresponding to the size of the array
145 !---------------------------------------------------------------------------
146 subroutine read_asciifile_real(filename,nlinesread,realarr,ierror)
147 character(len=*), intent(in) :: filename
148 integer, intent(out) :: nlinesread
149 real, dimension(:), intent(out) :: realarr
150 integer, intent(out), optional :: ierror
151 integer, parameter :: iunit = 66 ! logical unit number for read operation
152 integer :: ierr,i,maxlines
153 logical :: iexist
154
155 i = 0
156 nlinesread = 0
157 if (present(ierror)) ierror = 0
158
159 !--if file does not exist, do nothing and return
160 inquire(file=filename,exist=iexist)
161 if (.not.iexist) then
162 if (present(ierror)) ierror = -1
163 return
164 endif
165
166 open(unit=iunit,file=filename,status='old',form='formatted',iostat=ierr)
167 !--error opening file (but file does exist)
168 if (ierr /= 0) then
169 print "(a)",' ERROR opening '//trim(filename)
170 if (present(ierror)) then
171 ierror = ierr
172 endif
173 return
174 endif
175
176 realarr(:) = -666.
177 maxlines = size(realarr)
178 read(iunit,*,err=66,end=99) (realarr(i),i=1,maxlines)
179
180 !--end of array limits
181 print "(a,i6)",' WARNING: array limits reached reading '//trim(filename)//', max = ',maxlines
182 nlinesread = maxlines
183 close(unit=iunit)
184 return
185
186 !--error encountered
187 66 continue
188 print "(a,i6)",' ERROR reading '//trim(filename)//' at line ',i-1
189 if (present(ierror)) ierror = 1
190 do i=1,maxlines
191 if (abs(realarr(i)+666.) > tiny(0.)) nlinesread = nlinesread + 1
192 enddo
193 close(unit=iunit)
194 return
195
196 !--reached end of file (the expected behaviour)
197 99 continue
198 do i=1,maxlines
199 if (abs(realarr(i)+666.) > tiny(0.)) nlinesread = nlinesread + 1
200 enddo
201 close(unit=iunit)
202 return
203
204 end subroutine read_asciifile_real
205
206 !---------------------------------------------------------------------------
207 ! Generic subroutine to read all lines of an ascii file
208 ! returns array of real numbers (either one per line or all on same line)
209 ! up to a maximum corresponding to the size of the array
210 !---------------------------------------------------------------------------
211 subroutine read_asciifile_int(filename,nlinesread,intarr,ierror)
212 character(len=*), intent(in) :: filename
213 integer, intent(out) :: nlinesread
214 integer, dimension(:), intent(out) :: intarr
215 integer, intent(out), optional :: ierror
216 integer, parameter :: iunit = 66 ! logical unit number for read operation
217 integer :: ierr,i,maxlines
218 logical :: iexist
219
220 i = 0
221 nlinesread = 0
222 if (present(ierror)) ierror = 0
223
224 !--if file does not exist, do nothing and return
225 inquire(file=filename,exist=iexist)
226 if (.not.iexist) then
227 if (present(ierror)) ierror = -1
228 return
229 endif
230
231 open(unit=iunit,file=filename,status='old',form='formatted',iostat=ierr)
232 !--error opening file (but file does exist)
233 if (ierr /= 0) then
234 print "(a)",' ERROR opening '//trim(filename)
235 if (present(ierror)) then
236 ierror = ierr
237 endif
238 return
239 endif
240
241 intarr(:) = -666
242 maxlines = size(intarr)
243 read(iunit,*,err=66,end=99) (intarr(i),i=1,maxlines)
244
245 !--end of array limits
246 print "(a,i6)",' WARNING: array limits reached reading '//trim(filename)//', max = ',maxlines
247 nlinesread = maxlines
248 close(unit=iunit)
249 return
250
251 !--error encountered
252 66 continue
253 print "(a,i6)",' ERROR reading '//trim(filename)//' at line ',i-1
254 if (present(ierror)) ierror = 1
255 do i=1,maxlines
256 if (abs(intarr(i)+666) > 0) nlinesread = nlinesread + 1
257 enddo
258 close(unit=iunit)
259 return
260
261 !--reached end of file (the expected behaviour)
262 99 continue
263 do i=1,maxlines
264 if (abs(intarr(i)+666) > 0) nlinesread = nlinesread + 1
265 enddo
266 close(unit=iunit)
267 return
268
269 end subroutine read_asciifile_int
270
271 !---------------------------------------------------------------------------
272 ! Generic subroutine to read all lines of an ascii file
273 ! returns 2D array of real numbers (i.e. tabulated data)
274 !---------------------------------------------------------------------------
275 subroutine read_asciifile_realarr(filename,nlinesread,realarr,ierror)
276 character(len=*), intent(in) :: filename
277 integer, intent(out) :: nlinesread
278 real, dimension(:,:), intent(out) :: realarr
279 integer, intent(out), optional :: ierror
280 integer, parameter :: iunit = 66 ! logical unit number for read operation
281 integer :: ierr,i,ncols,ncolsfile,nheader
282 logical :: iexist
283
284 nlinesread = 0
285 if (present(ierror)) ierror = 0
286
287 !--if file does not exist, do nothing and return
288 inquire(file=filename,exist=iexist)
289 if (.not.iexist) then
290 if (present(ierror)) ierror = -1
291 return
292 endif
293
294 open(unit=iunit,file=filename,status='old',form='formatted',iostat=ierr)
295 !--error opening file (but file does exist)
296 if (ierr /= 0) then
297 print "(a)",' ERROR opening '//trim(filename)
298 if (present(ierror)) ierror = ierr
299 return
300 else
301 ! get number of columns
302 call get_ncolumns(iunit,ncolsfile,nheader)
303 ! skip header lines
304 do i=1,nheader
305 read(iunit,*,iostat=ierr)
306 enddo
307 ! read 2D array from file
308 ncols = min(ncolsfile,size(realarr(:,1)))
309 nlinesread = 0
310 do while (ierr==0)
311 nlinesread = nlinesread + 1
312 read(iunit,*,iostat=ierr) realarr(1:ncols,nlinesread)
313 enddo
314 nlinesread = max(nlinesread - 1,0)
315 close(iunit)
316 endif
317
318 end subroutine read_asciifile_realarr
319
320 !---------------------------------------------------------------------------
321 ! Generic subroutine to read all lines of an ascii file
322 ! returns array of real numbers and corresponding string
323 ! up to a maximum corresponding to the size of the array
324 !---------------------------------------------------------------------------
325 subroutine read_asciifile_real_string(filename,nlinesread,realarr,charline,ierror)
326 character(len=*), intent(in) :: filename
327 integer, intent(out) :: nlinesread
328 real, dimension(:), intent(out) :: realarr
329 character(len=*), dimension(:), intent(out) :: charline
330 integer, intent(out), optional :: ierror
331 integer, parameter :: iunit = 66 ! logical unit number for read operation
332 integer :: ierr,i,maxlines
333 logical :: iexist
334
335 nlinesread = 0
336 if (present(ierror)) ierror = 0
337
338 !--if file does not exist, do nothing and return
339 inquire(file=filename,exist=iexist)
340 if (.not.iexist) then
341 if (present(ierror)) ierror = -1
342 return
343 endif
344
345 open(unit=iunit,file=filename,status='old',form='formatted',iostat=ierr)
346 !--error opening file (but file does exist)
347 if (ierr /= 0) then
348 print "(a)",' ERROR opening '//trim(filename)
349 if (present(ierror)) then
350 ierror = ierr
351 endif
352 return
353 endif
354
355 if (size(realarr) /= size(charline)) then
356 print "(a)",' WARNING: array size mismatch in call to read_asciifile'
357 endif
358
359 realarr(:) = -666.
360 maxlines = min(size(realarr),size(charline))
361 read(iunit,*,err=66,end=99) (realarr(i),charline(i),i=1,maxlines)
362
363 !--end of array limits
364 print "(a,i6)",' WARNING: array limits reached reading '//trim(filename)//', max = ',maxlines
365 nlinesread = maxlines
366 close(unit=iunit)
367 return
368
369 !--error encountered
370 66 continue
371 print "(a,i6)",' ERROR reading '//trim(filename)//' at line ',i-1
372 if (present(ierror)) ierror = 1
373 do i=1,maxlines
374 if (abs(realarr(i)+666.) > tiny(0.)) nlinesread = nlinesread + 1
375 enddo
376 close(unit=iunit)
377 return
378
379 !--reached end of file (the expected behaviour)
380 99 continue
381 do i=1,maxlines
382 if (abs(realarr(i)+666.) > tiny(0.)) nlinesread = nlinesread + 1
383 enddo
384
385 close(unit=iunit)
386 return
387
388 end subroutine read_asciifile_real_string
389
390 !---------------------------------------------------------------------------
391 ! utility to work out number of columns of real numbers
392 ! in an ascii file
393 !
394 ! file must already be open and at the start
395 ! slightly ad-hoc but its the best way I could think of!
396 !---------------------------------------------------------------------------
397 subroutine get_ncolumns(lunit,ncolumns,nheaderlines,csv,maxheaderlines)
398 integer, intent(in) :: lunit
399 integer, intent(out) :: ncolumns,nheaderlines
400 integer, intent(in), optional :: maxheaderlines
401 logical, intent(in), optional :: csv
402 integer :: ierr,ncolprev,ncolprev2,ncolsthisline,maxlines,ncolstot
403 character(len=max_line_length) :: line
404 logical :: nansinfile,infsinfile,is_csv
405
406 if (present(maxheaderlines)) then
407 maxlines = maxheaderlines
408 else
409 maxlines = 1000
410 endif
411 nheaderlines = 0
412 line = ' '
413 ierr = 0
414 ncolumns = 0
415 ncolprev = -100
416 ncolprev2 = -200
417 ncolsthisline = 0
418 ncolstot = 0
419 nansinfile = .false.
420 infsinfile = .false.
421 is_csv = .false.
422 if (present(csv)) is_csv = csv
423 !
424 !--loop until we find two consecutive lines with the same number of columns (but non zero)
425 ! if ncolumns==1 then we must find 3 consecutive lines
426 !
427 do while ((len_trim(line)==0 .or. ncolsthisline /= ncolprev .or. ncolumns < 1 .or. &
428 (ncolumns==1 .and. ncolsthisline /= ncolprev2)) &
429 .and. ierr==0 .and. nheaderlines <= maxlines)
430 ncolprev2 = ncolprev
431 ncolprev = ncolumns
432 read(lunit,"(a)",iostat=ierr) line
433 if (index(line,'NaN') > 0) nansinfile = .true.
434 if (index(line,'Inf') > 0) infsinfile = .true.
435 if (len_trim(line)==0) then
436 ncolsthisline = -1
437 else
438 if (ierr==0) ncolsthisline = ncolumnsline(line,csv=is_csv,ntot=ncolstot)
439 ncolumns = ncolsthisline
440 endif
441 nheaderlines = nheaderlines + 1
442 !print*,'DEBUG: header line ',nheaderlines,' ncols = ',ncolsthisline,'"'//trim(line)//'"'
443 enddo
444 !--subtract 2 from the header line count (the last two lines which were the same)
445 nheaderlines = max(nheaderlines - 2,0)
446 if (ncolumns==1) nheaderlines = max(nheaderlines - 1,0)
447 if (is_csv) ncolumns = ncolstot
448
449 if (ierr > 0 .or. ncolumns <= 0) then
450 ncolumns = 0
451 elseif (ierr < 0) then
452 !print*,ncolumns,ncolprev
453 endif
454 if (nansinfile) print "(a)",' INDIAN BREAD WARNING!! NaNs in file!!'
455 if (infsinfile) print "(a)",' WARNING!! Infs in file!!'
456 rewind(lunit)
457
458 if (ncolumns==0) print "(a)",' ERROR: no columns of real numbers found'
459
460 end subroutine get_ncolumns
461
462 !---------------------------------------------------------------------------
463 ! utility to work out number of rows in file
464 !---------------------------------------------------------------------------
465 subroutine get_nrows(lunit,nheaderlines,nlines)
466 integer, intent(in) :: lunit,nheaderlines
467 integer, intent(out) :: nlines
468 integer :: ierr,i
469
470 rewind(lunit)
471 ierr = 0
472 do i=1,nheaderlines
473 read(lunit,*,iostat=ierr)
474 enddo
475 nlines = 0
476 do while (ierr==0)
477 read(lunit,*,iostat=ierr)
478 if (ierr==0) nlines = nlines + 1
479 enddo
480
481 end subroutine get_nrows
482
483 !---------------------------------------------------------------------------
484 !
485 ! function returning the number of columns of real numbers from a given line
486 !
487 !---------------------------------------------------------------------------
488 integer function ncolumnsline(line,csv,ntot)
489 character(len=*), intent(in) :: line
490 logical, intent(in), optional :: csv
491 integer, intent(out), optional :: ntot
492 real :: dummyreal(1000)
493 integer :: ierr,i
494 logical :: use_commas
495
496 use_commas= .false.
497 if (present(csv)) use_commas = csv
498 if (use_commas) then
499 if (present(ntot)) then
500 ncolumnsline = ncolumnsline_csv(line,ntot)
501 else
502 ncolumnsline = ncolumnsline_csv(line)
503 endif
504 return
505 endif
506
507 dummyreal = -666666.0
508
509 ierr = 0
510 read(line,*,iostat=ierr) (dummyreal(i),i=1,size(dummyreal))
511
512 i = 1
513 ncolumnsline = 0
514 do while(abs(dummyreal(i)+666666.) > tiny(0.) .or. dummyreal(i) /= dummyreal(i))
515 ncolumnsline = ncolumnsline + 1
516 i = i + 1
517 if (i > size(dummyreal)) then
518 print "(a)",'*** ERROR: too many columns in file'
519 ncolumnsline = size(dummyreal)
520 return
521 endif
522 enddo
523
524 end function ncolumnsline
525
526 !---------------------------------------------------------------------------
527 !
528 ! function returning the number of columns of real numbers from a given line
529 !
530 !---------------------------------------------------------------------------
531 integer function ncolumnsline_csv(line,ntot) result(ncols)
532 character(len=*), intent(in) :: line
533 integer, parameter :: lenf = 15
534 character(len=lenf) :: fields(len(line)/lenf)
535 integer, intent(out), optional :: ntot
536 integer :: i,ierr,nfields
537 real :: dum
538
539 ! split line by commas
540 call split(line,',',fields,nfields)
541
542 ! report how many columns contain real numbers
543 ! or blank (non-text) entries
544 ncols = 0
545 do i=1,nfields
546 if (len_trim(fields(i))==0) then
547 ncols = ncols + 1
548 else
549 dum = -666666.
550 read(fields(i),*,iostat=ierr) dum
551 if (ierr==0) then
552 ncols = ncols + 1
553 endif
554 endif
555 enddo
556
557 if (present(ntot)) ntot = nfields
558
559 end function ncolumnsline_csv
560
561 !---------------------------------------------------------------------------
562 !
563 ! read a line from a csv file and parse for real numbers
564 !
565 !---------------------------------------------------------------------------
566 subroutine readline_csv(line,ncols,datcol)
567 character(len=*), intent(in) :: line
568 integer, intent(in) :: ncols
569 real, intent(out) :: datcol(ncols)
570 integer, parameter :: lenf = 15
571 character(len=lenf) :: fields(ncols)
572 !logical, intent(in) :: mask(ncols)
573 integer :: nfields,i,icol,ierr
574
575 ! split line by commas
576 call split(line,',',fields,nfields)
577
578 ! read only columns that contain real numbers
579 icol = 0
580 do i=1,min(nfields,ncols)
581 icol = icol + 1
582 read(fields(i),*,iostat=ierr) datcol(icol)
583 enddo
584
585 end subroutine readline_csv
586
587 !----------------------------------------------------------------------
588 !
589 ! Small utility to return the number of comment lines in an ascii
590 ! file. These are lines that do not begin with a number.
591 !
592 ! This is slightly different to what is done in the get_ncolumns
593 ! routine, where header lines are any lines not having the same number
594 ! of columns. Here we do not attempt to evaluate the number of data
595 ! columns.
596 !
597 ! File must be open and at the desired starting position
598 !----------------------------------------------------------------------
599 integer function get_nheaderlines(lunit) result(nheaderlines)
600 integer, intent(in) :: lunit
601 real :: dum
602 integer :: ierr
603
604 dum = -666.
605 nheaderlines = 0
606 ierr = -1
607 do while (abs(dum+666.) < tiny(0.) .or. ierr /= 0)
608 nheaderlines = nheaderlines + 1
609 read(lunit,*,iostat=ierr) dum
610 enddo
611 nheaderlines = nheaderlines - 1
612
613 end function get_nheaderlines
614
615 !---------------------------------------------------------------------------
616 !
617 ! function stripping '/', '\' and spaces out of filenames
618 !
619 !---------------------------------------------------------------------------
620 function safename(string)
621 character(len=*), intent(in) :: string
622 character(len=len(string)) :: safename
623 integer :: ipos
624
625 safename = string
626
627 !--remove forward slashes which can be mistaken for directories: replace with '_'
628 call string_replace(safename,'/','_')
629 call string_replace(safename,' ','_')
630
631 !--delete brackets and operators of all kinds
632 call string_delete(safename,'{')
633 call string_delete(safename,'}')
634 call string_delete(safename,'(')
635 call string_delete(safename,')')
636 call string_delete(safename,'[')
637 call string_delete(safename,']')
638 call string_delete(safename,'<')
639 call string_delete(safename,'>')
640 call string_delete(safename,'*')
641 call string_delete(safename,'?')
642 call string_delete(safename,'^')
643 call string_delete(safename,'''')
644 call string_delete(safename,'"')
645 call string_delete(safename,'&')
646 call string_delete(safename,'#')
647 call string_delete(safename,'|')
648
649 !--remove escape sequences: remove '\' and position following
650 ipos = index(trim(safename),'\')
651 do while (ipos /= 0)
652 safename = safename(1:ipos-1)//safename(ipos+2:len_trim(safename))
653 ipos = index(trim(safename),'\')
654 enddo
655
656 end function safename
657
658 !---------------------------------------------------------------------------
659 !
660 ! function to insert escape characters so filenames appear correctly in legend
661 !
662 !---------------------------------------------------------------------------
663 function add_escape_chars(string)
664 character(len=*), intent(in) :: string
665 character(len=len(string)) :: add_escape_chars
666
667 add_escape_chars = string
668 call string_replace(add_escape_chars,'_','\_')
669 call string_replace(add_escape_chars,'^','\^')
670
671 end function add_escape_chars
672
673 !---------------------------------------------------------------------------
674 !
675 ! function to strip spaces out of a string
676 !
677 !---------------------------------------------------------------------------
678 function nospaces(string)
679 character(len=*), intent(in) :: string
680 character(len=len(string)) :: nospaces
681
682 nospaces = string
683 call string_delete(nospaces,' ')
684
685 end function nospaces
686
687 !---------------------------------------------------------------------------
688 !
689 ! function stripping the directory off a filename
690 !
691 !---------------------------------------------------------------------------
692 function basename(string)
693 character(len=*), intent(in) :: string
694 character(len=len(string)) :: basename
695 integer :: i,iposmax
696
697 basename = string
698
699 !--find the last forward slash
700 iposmax = 0
701 i = len_trim(string)
702 do while(i >= 2 .and. iposmax==0)
703 i = i - 1
704 if (string(i:i)=='/') iposmax = i
705 enddo
706 basename = trim(string(iposmax+1:))
707
708 end function basename
709
710 !---------------------------------------------------------------------------
711 !
712 ! function to get file extension
713 !
714 !---------------------------------------------------------------------------
715 function extension(string) result(ext)
716 character(len=*), intent(in) :: string
717 character(len=len(string)) :: ext
718 integer :: idot
719
720 idot = index(string,'.',back=.true.)
721 if (idot > 2 .and. idot+1 <= len(string)) then
722 ext = string(idot:)
723 else
724 ext = ''
725 endif
726
727 end function extension
728
729 !---------------------------------------------------------------------------
730 !
731 ! function to safely convert a string to c format (ie. with a terminating
732 ! ascii null character)
733 !
734 !---------------------------------------------------------------------------
735 function cstring(string)
736 character(len=*), intent(in) :: string
737 character(len=len(string)+1) :: cstring
738
739 cstring = trim(string)//achar(0)
740
741 end function cstring
742
743 !---------------------------------------------------------------------------
744 !
745 ! function to safely convert a string from c format (ie. with a terminating
746 ! ascii null character) back to a normal Fortran string
747 !
748 !---------------------------------------------------------------------------
749 function fstring(array)
750 use, intrinsic :: iso_c_binding, only:c_char
751 character(kind=c_char), dimension(:), intent(in) :: array
752 character(len=size(array)-1) :: fstring
753 integer :: i
754
755 fstring = ''
756 do i=1,size(array)
757 if (array(i)==achar(0)) exit
758 fstring(i:i) = array(i)
759 enddo
760
761 end function fstring
762
763 !---------------------------------------------------------------------------
764 !
765 ! subroutine to replace a matching section of a string with another
766 ! string, possibly of differing length
767 !
768 !---------------------------------------------------------------------------
769 subroutine string_replace(string,skey,sreplacewith)
770 character(len=*), intent(inout) :: string
771 character(len=*), intent(in) :: skey,sreplacewith
772 character(len=len(string)) :: remstring
773 integer :: ipos,imax,lensub,i,iposnext
774
775 ipos = index(trim(string),skey)
776 lensub = len(skey)
777 imax = len(string)
778 i = 0
779 do while (ipos > 0 .and. i <= imax)
780 iposnext = ipos + len(sreplacewith)
781 i = i + 1 ! only allow as many replacements as characters
782 remstring = string(ipos+lensub:len_trim(string))
783 string = string(1:ipos-1)//sreplacewith//remstring
784 ipos = index(trim(string(iposnext:)),skey)
785 if (ipos > 0) ipos = ipos + iposnext
786 !print*,ipos,' string = ',trim(string),'iposnext = ',trim(string(iposnext:))
787 enddo
788
789 end subroutine string_replace
790
791 !---------------------------------------------------------------------------
792 !
793 ! subroutine to replace a specified section of a string with a
794 ! replacement string, possibly of differing length
795 !
796 !---------------------------------------------------------------------------
797 subroutine string_sub(string,i1,i2,sreplacewith)
798 character(len=*), intent(inout) :: string
799 integer, intent(in) :: i1,i2
800 character(len=*), intent(in) :: sreplacewith
801 character(len=len(string)) :: oldstring
802
803 oldstring = string
804 if (i2 < len_trim(string)) then
805 string = oldstring(1:i1-1)//sreplacewith//oldstring(i2+1:len_trim(oldstring))
806 else
807 string = oldstring(1:i1-1)//sreplacewith
808 endif
809
810 end subroutine string_sub
811
812 !---------------------------------------------------------------------------
813 !
814 ! subroutine to delete all matching occurrences of key from string
815 !
816 !---------------------------------------------------------------------------
817 pure subroutine string_delete1(string,skey)
818 character(len=*), intent(inout) :: string
819 character(len=*), intent(in) :: skey
820 integer :: ipos,lensub
821
822 ipos = index(string,skey)
823 lensub = len(skey)
824 do while(ipos > 0)
825 string = string(1:ipos-1)//string(ipos+lensub:len_trim(string))
826 ipos = index(trim(string),skey)
827 enddo
828
829 end subroutine string_delete1
830
831 !---------------------------------------------------------------------------
832 !
833 ! alternate version of above for arrays of keys
834 !
835 !---------------------------------------------------------------------------
836 pure subroutine string_delete_array(string,skeys)
837 character(len=*), intent(inout) :: string
838 character(len=*), intent(in) :: skeys(:)
839 integer :: i
840
841 do i=1,size(skeys)
842 call string_delete(string,skeys(i))
843 enddo
844
845 end subroutine string_delete_array
846 !---------------------------------------------------------------------------
847 !
848 ! function version of string_delete
849 !
850 !---------------------------------------------------------------------------
851 pure elemental function strip(string,skey)
852 character(len=*), intent(in) :: string,skey
853 character(len=len(string)) :: strip
854
855 strip = string
856 call string_delete(strip,skey)
857
858 end function strip
859
860 !---------------------------------------------------------------------------
861 !
862 ! Converts a string to upper case
863 !
864 !---------------------------------------------------------------------------
865 pure elemental function ucase(string)
866 character(len=*), intent(in) :: string
867 character(len=len(string)) :: ucase
868 integer :: is,ia
869 integer, parameter :: aoffset = 32
870
871 ucase = string
872 do is = 1, len(ucase)
873 ia = iachar(ucase(is:is))
874 if (ia >= iachar('a').and.ia <= iachar('z')) &
875 ucase(is:is) = achar(ia-aoffset)
876 enddo
877
878 end function ucase
879
880 !---------------------------------------------------------------------------
881 !
882 ! Converts a string to lower case
883 !
884 !---------------------------------------------------------------------------
885 pure elemental function lcase(string)
886 character(len=*), intent(in) :: string
887 character(len=len(string)) :: lcase
888 integer :: is,ia
889 integer, parameter :: aoffset = 32
890
891 lcase = string
892 do is = 1, len(lcase)
893 ia = iachar(lcase(is:is))
894 if (ia >= iachar('A').and.ia <= iachar('Z')) &
895 lcase(is:is) = achar(ia+aoffset)
896 enddo
897
898 end function lcase
899
900 !---------------------------------------------------------------------------
901 !
902 ! indicate if a character is a digit (number) or not
903 !
904 !---------------------------------------------------------------------------
905 pure elemental logical function isdigit(string)
906 character(len=1), intent(in) :: string
907 integer :: ia
908
909 isdigit = .false.
910 ia = iachar(string)
911 if (ia >= iachar('0').and.ia <= iachar('9')) isdigit = .true.
912
913 end function isdigit
914
915 !------------------------------------------------------------------------
916 ! get_digits: for an integer i returns number of digits it contains
917 ! and a list of these *without* using write statements
918 !
919 ! i : integer to split into digits
920 ! nmax : dimensions of digits array
921 ! digits(nmax) : array of digits
922 ! ndigits : number of digits in i
923 !------------------------------------------------------------------------
924 pure subroutine get_digits(i,digits,ndigits)
925 integer, intent(in) :: i
926 integer, intent(out) :: ndigits
927 integer, intent(out), dimension(:) :: digits
928 integer :: j,isubtract,idigit
929
930 ndigits = 0
931
932 isubtract = 0
933
934 do j=size(digits),0,-1
935 if (i >= 10**j) then
936 ndigits = ndigits + 1
937 idigit = (i - isubtract)/10**j
938 digits(ndigits) = idigit
939 isubtract = isubtract + digits(ndigits)*10**j
940 endif
941 enddo
942
943 end subroutine get_digits
944
945 !---------------------------------------------------------------------------
946 !
947 ! convert a string to an integer WITHOUT using write statement
948 ! (so this can be used in a write or print statement)
949 !
950 !---------------------------------------------------------------------------
951 pure elemental function integer_to_string(i) result(string)
952 integer, intent(in) :: i
953 character(len=12) :: string
954 integer :: i0,ndigits,j
955 integer :: idigit(12)
956
957 string = ''
958 i0 = iachar('0')
959 call get_digits(i,idigit,ndigits)
960 do j=2,ndigits
961 string(j:j) = achar(i0+idigit(j))
962 enddo
963
964 end function integer_to_string
965
966 !---------------------------------------------------------------------------
967 !
968 ! search a file for the line containing a particular string
969 !
970 !---------------------------------------------------------------------------
971 integer function get_line_containing(filename,string)
972 character(len=*), intent(in) :: filename, string
973 character(len=130) :: line
974 integer :: i,ierr
975 integer, parameter :: lu=95
976
977 get_line_containing = 0
978 open(unit=lu,file=filename,status='old',iostat=ierr)
979 i = 0
980 do while(ierr==0)
981 i = i + 1
982 read(lu,"(a)",iostat=ierr) line
983 if (index(line,string) /= 0) get_line_containing = i
984 enddo
985 close(lu)
986
987 end function get_line_containing
988
989 !---------------------------------------------------------------------------
990 !
991 ! Convert an integer into the corresponding entry in a list of strings
992 !
993 !---------------------------------------------------------------------------
994 function enumerate(i,stringarr,default) result(string)
995 integer, intent(in) :: i
996 character(len=*), intent(in), dimension(:) :: stringarr
997 integer, intent(in), optional :: default
998 character(len=len(stringarr)) :: string
999
1000 string = ''
1001 if (i >= 1 .and. i <= size(stringarr)) then
1002 string = trim(stringarr(i))
1003 elseif (present(default)) then
1004 if (default >= 1 .and. i <= size(stringarr)) then
1005 string = trim(stringarr(default))
1006 endif
1007 endif
1008
1009 end function enumerate
1010
1011 !---------------------------------------------------------------------------
1012 !
1013 ! Split a string into substrings based on a delimiter
1014 !
1015 !---------------------------------------------------------------------------
1016 pure subroutine split(string,delim,stringarr,nsplit)
1017 character(len=*), intent(in) :: string
1018 character(len=*), intent(in) :: delim
1019 character(len=*), intent(out), dimension(:), optional :: stringarr
1020 integer, intent(out) :: nsplit
1021 integer :: i,j,imax,iend,nmax
1022
1023 i = 1
1024 nsplit = 0
1025 imax = len(string)
1026 nmax = imax
1027 if (present(stringarr)) nmax = size(stringarr)
1028
1029 do while(nsplit < nmax .and. i <= imax)
1030 ! find next non-blank character
1031 if (string(i:i)==' ') then
1032 do while (string(i:i)==' ')
1033 i = i + 1
1034 if (i > imax) exit
1035 enddo
1036 if (i > imax) exit
1037 endif
1038
1039 ! look for next occurrence of delimiter
1040 j = index(string(i:),delim) - 1
1041 ! if no delimiter found, use whole rest of string
1042 if (j < 0) j = imax
1043 ! set end of substring
1044 iend = min(i+j-1,imax)
1045 ! extract the substring
1046 nsplit = nsplit + 1
1047 if (nsplit <= nmax .and. present(stringarr)) then
1048 stringarr(nsplit) = string(i:iend)
1049 endif
1050 i = iend + len(delim) + 1
1051 enddo
1052
1053 end subroutine split
1054
1055 !---------------------------------------------------------------------------
1056 !
1057 ! extract a list of labels from the header line of a file
1058 !
1059 !---------------------------------------------------------------------------
1060 subroutine get_column_labels(line,nlabels,labels,method,ndesired,csv)
1061 character(len=*), intent(in) :: line
1062 integer, intent(out) :: nlabels
1063 character(len=*), dimension(:), intent(out) :: labels
1064 integer, intent(out), optional :: method
1065 integer, intent(in), optional :: ndesired
1066 logical, intent(in), optional :: csv
1067 integer :: i1,i2,i,nlabelstmp,nlabels_prev,istyle,ntarget
1068 character(len=1) :: leadingchar
1069 character(len=4), parameter :: spaces = ' '
1070 logical :: is_csv
1071
1072 nlabels = 0
1073 i1 = 1
1074 istyle = 0
1075 ntarget = -1
1076 is_csv = .false.
1077 if (present(csv)) is_csv = csv
1078 if (present(ndesired)) ntarget = ndesired
1079 !
1080 ! strip leading comment character ('#')
1081 !
1082 leadingchar = trim(adjustl(line))
1083 if (leadingchar=='#') then
1084 i1 = index(line,'#') + 1
1085 endif
1086 ! strip anything preceding an equals sign
1087 i1 = max(i1,index(line,'=')+1)
1088 i2 = i1
1089
1090 if (index(nospaces(line),'][') > 0 .and. .not.is_csv) then
1091 !
1092 ! format style 1: # [ mylabel1 ] [ mylabel2 ] [ mylabel3 ]
1093 !
1094 istyle = 1
1095 i1 = max(index(line,'[')+1,i1) ! strip leading square bracket
1096 ! try with different number of spaces between brackets (if labels not found)
1097 over_spaces1: do i=4,0,-1
1098 call split(line(i1:),']'//spaces(1:i)//'[',labels,nlabels)
1099 if (nlabels > 1) exit over_spaces1
1100 enddo over_spaces1
1101 elseif (index(line,',') > 1 .or. is_csv) then
1102 !
1103 ! format style 2: mylabel1,mylabel2,mylabel3
1104 !
1105 istyle = 2
1106 call split(line(i1:),',',labels,nlabelstmp)
1107 if (is_csv) then
1108 nlabels = nlabelstmp ! allow blank/arbitrary labels in csv format
1109 else
1110 nlabels = count_sensible_labels(nlabelstmp,labels)
1111 endif
1112 else
1113 !
1114 ! format style 3: # mylabel1 mylabel2 mylabel3
1115 !
1116 istyle = 3
1117 ! try splitting with 4, then 3, then 2 spaces until the number of labels decreases
1118 nlabels_prev = 0
1119 over_spaces: do i=4,2,-1
1120 call split(line(i1:),spaces(1:i),labels,nlabelstmp)
1121 ! quit if we already have the target number of labels
1122 if (nlabelstmp == ntarget) exit over_spaces
1123
1124 ! if the number of labels is > 1 but has decreased, quit, unless nlabels
1125 ! still exceeds the number of labels we are hoping for (ntarget)
1126 if ((nlabelstmp < nlabels_prev .or. nlabelstmp >= max(nlabels_prev,2) &
1127 .and. i < 4 .and. .not. (ntarget > 0 .and. nlabelstmp > ntarget))) then
1128 ! take the answer with the previous number of spaces
1129 call split(line(i1:),spaces(1:i+1),labels,nlabelstmp)
1130 exit over_spaces
1131 endif
1132 nlabels_prev = nlabelstmp
1133 enddo over_spaces
1134 !
1135 ! this style is dangerous, so perform sanity checks
1136 ! on the labels to ensure they are sensible
1137 !
1138 nlabels = count_sensible_labels(nlabelstmp,labels)
1139 if (nlabels <= 1) then
1140 !
1141 ! format style 4: x y z vx vy vz
1142 ! (this style is also dangerous)
1143 !
1144 istyle = 4
1145 call split(line(i1:),' ',labels,nlabelstmp)
1146 nlabels = count_sensible_labels(nlabelstmp,labels)
1147 endif
1148 endif
1149 if (present(method)) method = istyle
1150 !
1151 ! clean up
1152 !
1153 do i=1,nlabels
1154 ! delete brackets
1155 if (nlabels <= size(labels)) then
1156 call string_delete(labels(i),',')
1157 if (istyle==1 .or. istyle==2) then
1158 labels(i) = trim(adjustl(labels(i)))
1159 ! delete leading numbers
1160 i1 = 1
1161 do while (isdigit(labels(i)(i1:i1)))
1162 labels(i)(i1:i1) = ' '
1163 i1 = i1 + 1
1164 enddo
1165 endif
1166 labels(i) = trim(adjustl(labels(i)))
1167 endif
1168 enddo
1169 ! delete loose trailing square bracket but only if not matching
1170 if (istyle==1) then
1171 if (index(labels(nlabels),']') > 0) then
1172 i1 = count_char(labels(nlabels),'[') ! number of open brackets
1173 i2 = count_char(labels(nlabels),']') ! number of closed brackets
1174 if (i2 > i1) then ! if brackets do not match
1175 ! find last trailing bracket
1176 i2 = index(labels(nlabels),']',back=.true.)
1177 ! delete it, but only if followed by spaces
1178 if (i2==len_trim(labels(nlabels))) then
1179 labels(nlabels) = labels(nlabels)(1:i2-1)
1180 endif
1181 endif
1182 endif
1183 endif
1184
1185 end subroutine get_column_labels
1186
1187 !---------------------------------------------------------------------------
1188 !
1189 ! interface to the above routine that also searches for the line
1190 ! containing the column labels in the list of header lines
1191 !
1192 !---------------------------------------------------------------------------
1193 subroutine read_column_labels(iunit,nheaderlines,ncols,nlabels,labels,csv,debug)
1194 integer, intent(in) :: iunit,nheaderlines,ncols
1195 integer, intent(out) :: nlabels
1196 character(len=*), dimension(:), intent(out) :: labels
1197 logical, intent(in), optional :: csv,debug
1198 character(len=len(labels(1))), dimension(size(labels)) :: tmplabel
1199 character(len=max_line_length) :: line
1200 logical :: is_csv,verbose,got_labels
1201 integer :: i,imethod,ierr,nwanted,nlabelstmp
1202
1203 is_csv = .false.
1204 verbose = .false.
1205 if (present(csv)) is_csv = csv
1206 if (present(debug)) verbose = debug
1207 got_labels = .false.
1208 nlabels = 0
1209 nwanted = min(ncols,size(labels)) ! can either retrieve all labels or completely fill the labels array
1210 labels = ''
1211 rewind(iunit)
1212 do i=1,nheaderlines
1213 read(iunit,"(a)",iostat=ierr) line
1214 !--try to match column labels from this header line, if not already matched (or dubious match)
1215 call get_column_labels(trim(line),nlabelstmp,tmplabel,method=imethod,ndesired=nwanted,csv=csv)
1216 !--if we get nlabels > ncolumns, use them, but keep trying for a better match
1217 if ((got_labels .and. nlabelstmp == nwanted) .or. (.not.got_labels .and. imethod==2) .or. &
1218 (.not.got_labels .and. nlabelstmp >= nwanted & ! only allow single-spaced labels if == ncols
1219 .and. (.not.(imethod>=4) .or. nlabelstmp==nwanted))) then
1220 labels(1:nwanted) = tmplabel(1:nwanted)
1221 got_labels = .true.
1222 nlabels = nlabelstmp
1223 endif
1224 if (verbose) print "(5(1x,a,i0),1x,a,l1)",'DEBUG: line ',i,'nlabels = ',nlabels,&
1225 'want ',ncols,'method=',imethod,'len_trim(line)=',len_trim(line),'got_labels=',got_labels !,' LABELS= '//tmplabel(1:ncols)
1226 enddo
1227
1228 end subroutine read_column_labels
1229
1230 !---------------------------------------------------------------------------
1231 !
1232 ! count the number of sensible labels in a list of possible labels
1233 !
1234 !---------------------------------------------------------------------------
1235 integer function count_sensible_labels(n,labels) result(m)
1236 integer, intent(in) :: n
1237 character(len=*), dimension(n), intent(in) :: labels
1238 integer :: i
1239
1240 m = 0
1241 do i=1,n
1242 if (is_sensible_label(labels(i))) m = m + 1
1243 enddo
1244
1245 end function count_sensible_labels
1246
1247 !---------------------------------------------------------------------------
1248 !
1249 ! determine if a particular string makes sense as a column label or not
1250 !
1251 !---------------------------------------------------------------------------
1252 logical function is_sensible_label(string)
1253 character(len=*), intent(in) :: string
1254 real :: dum
1255 integer :: ierr
1256 real, parameter :: dum_prev = -66666666.
1257
1258 is_sensible_label = .true.
1259
1260 ! should not start with a decimal point
1261 if (string(1:1)=='.') is_sensible_label = .false.
1262
1263 ! should not contain equals sign
1264 !if (index(string,'=') > 0) is_sensible_label = .false.
1265
1266 dum = dum_prev
1267 ! should not be able to read it as a real number
1268 read(string,*,iostat=ierr) dum
1269 if (ierr==0 .and. abs(dum-dum_prev) > tiny(dum)) is_sensible_label = .false.
1270
1271 end function is_sensible_label
1272
1273 !------------------------------------------
1274 ! match tag against a list of tags
1275 ! returns index of matching tag in the list
1276 !------------------------------------------
1277 integer function match_tag(tags,tag)
1278 character(len=*), intent(in) :: tags(:)
1279 character(len=*), intent(in) :: tag
1280 integer :: i
1281
1282 match_tag = 0 ! default if not found
1283 do i=1,size(tags)
1284 if (trim(tags(i))==trim(adjustl(tag))) then
1285 match_tag = i
1286 exit ! only match first occurrence
1287 endif
1288 enddo
1289
1290 end function match_tag
1291
1292 !--------------------------------------------
1293 ! as above but only match first N characters
1294 ! where N=5 by default
1295 !--------------------------------------------
1296 integer function match_tag_start(tags,tag,n)
1297 character(len=*), intent(in) :: tags(:)
1298 character(len=*), intent(in) :: tag
1299 integer, intent(in), optional :: n
1300 integer :: i,ilen
1301 character(len=len(tag)) :: str1,str2
1302
1303 ilen = 5
1304 if (present(n)) ilen = n
1305
1306 match_tag_start = 0 ! default if not found
1307 do i=1,size(tags)
1308 str1 = tags(i)(1:ilen)
1309 str2 = tag(1:ilen)
1310 if (trim(lcase(str2))==trim(lcase(str1))) then
1311 match_tag_start = i
1312 exit ! only match first occurrence
1313 endif
1314 enddo
1315
1316 end function match_tag_start
1317
1318 !------------------------------------------
1319 ! match tag against a list of tags
1320 ! or by giving the column number explicitly
1321 ! returns index of matching tag in the list
1322 !------------------------------------------
1323 integer function match_column(tags,tag)
1324 character(len=*), intent(in) :: tags(:)
1325 character(len=*), intent(in) :: tag
1326 integer :: ierr
1327
1328 ! try to match the string tag first
1329 match_column = match_tag(tags,tag)
1330 if (match_column == 0) then
1331 ! try to read it as an integer from the string
1332 read(tag,*,iostat=ierr) match_column
1333 endif
1334
1335 end function match_column
1336
1337 !----------------------------------------------
1338 ! match tag against a list of tags
1339 ! and extract the value from an array of reals
1340 !----------------------------------------------
1341 real function get_value(tag,tags,vals,default)
1342 character(len=*), intent(in) :: tag
1343 character(len=*), intent(in) :: tags(:)
1344 real, intent(in) :: vals(:)
1345 real, intent(in), optional :: default
1346 integer :: itag
1347
1348 itag = match_tag(tags,tag)
1349 if (itag > 0 .and. itag <= size(vals)) then
1350 get_value = vals(itag)
1351 else
1352 if (present(default)) then
1353 get_value = default
1354 else
1355 get_value = 0.
1356 endif
1357 endif
1358
1359 end function get_value
1360
1361 !-----------------------------------------------
1362 ! match multiple tags against a list of strings
1363 ! e.g. find 'x','y','z' in list of labels
1364 !-----------------------------------------------
1365 subroutine match_taglist(taglist,tags,istartmatch,nmatch)
1366 character(len=*), intent(in) :: taglist(:)
1367 character(len=*), intent(in) :: tags(:)
1368 integer, intent(out) :: istartmatch,nmatch
1369 integer :: i,j
1370
1371 istartmatch = 0
1372 nmatch = 0
1373 if (size(taglist) < 1) return
1374 do i=1,size(tags)
1375 if (nmatch <= 1 .and. trim(tags(i))==trim(taglist(1))) then
1376 nmatch = 1
1377 istartmatch = i
1378 do j=2,min(size(taglist),size(tags)-i+1)
1379 if (trim(tags(i+j-1))==trim(taglist(j))) then
1380 nmatch = nmatch + 1
1381 endif
1382 enddo
1383 endif
1384 enddo
1385
1386 end subroutine match_taglist
1387
1388 !------------------------------------------
1389 ! find first integer that matches in a
1390 ! list of integers
1391 !------------------------------------------
1392 integer function match_integer(ivals,i)
1393 integer, intent(in) :: ivals(:)
1394 integer, intent(in) :: i
1395 integer :: k
1396
1397 match_integer = 0
1398 do k=1,size(ivals)
1399 if (ivals(k)==i) then
1400 match_integer = k
1401 exit
1402 endif
1403 enddo
1404
1405 end function match_integer
1406
1407 !------------------------------------------
1408 ! find labels that match between two lists
1409 ! (match == first N characters are the same)
1410 ! output is a list of indices of labels
1411 ! from list1 that match list2
1412 !------------------------------------------
1413 function match_lists(list1,list2) result(imap)
1414 character(len=*), intent(in) :: list1(:),list2(:)
1415 integer :: imap(size(list1))
1416 integer :: j,icol
1417
1418 do j=1,size(list1)
1419 icol = match_tag_start(list2,list1(j))
1420 if (icol > 0) imap(j) = icol
1421 enddo
1422
1423 end function match_lists
1424
1425 !------------------------------
1426 ! Append a number to a string
1427 ! e.g. string,2 -> string2
1428 !------------------------------
1429 subroutine append_number(string,j)
1430 character(len=*), intent(inout) :: string
1431 integer, intent(in) :: j
1432 character(len=12) :: strj
1433
1434 write(strj,"(i12)") j
1435 string = trim(string)//trim(adjustl(strj))
1436
1437 end subroutine append_number
1438
1439 !----------------------------------------------------------------------
1440 ! Append numbers to otherwise identical tags to make them unique
1441 ! e.g. massoftype1, massoftype2, massoftype3, etc.
1442 !----------------------------------------------------------------------
1443 subroutine make_tags_unique(ntags,tags)
1444 integer, intent(in) :: ntags
1445 character(len=*), dimension(ntags), intent(inout) :: tags
1446 character(len=len(tags)) :: tagprev
1447 integer :: i,j
1448
1449 if (ntags < 1) return
1450 j = 0
1451 tagprev = tags(1)
1452 do i=2,ntags
1453 if (tags(i)==tagprev) then
1454 j = j + 1
1455 if (j==1) then
1456 call append_number(tags(i-1),j)
1457 j = j + 1
1458 endif
1459 call append_number(tags(i),j)
1460 else
1461 tagprev = tags(i)
1462 j = 0
1463 endif
1464 enddo
1465
1466 end subroutine make_tags_unique
1467
1468 !-----------------------------------------------------------------
1469 !
1470 ! utility to count number of non-blank strings in a list
1471 !
1472 !-----------------------------------------------------------------
1473 integer function count_non_blank(string)
1474 character(len=*), dimension(:), intent(in) :: string
1475 integer :: i
1476
1477 count_non_blank = 0
1478 do i=1,size(string)
1479 if (len_trim(string(i))<=0) exit
1480 count_non_blank = count_non_blank + 1
1481 enddo
1482
1483 end function count_non_blank
1484
1485 !-----------------------------------------------------------------
1486 !
1487 ! utility to count number of times a character appears in a string
1488 !
1489 !-----------------------------------------------------------------
1490 integer function count_char(string,mychar)
1491 character(len=*), intent(in) :: string
1492 character(len=1), intent(in) :: mychar
1493 integer :: i
1494
1495 count_char = 0
1496 do i=1,len(string)
1497 if (string(i:i)==mychar) count_char = count_char + 1
1498 enddo
1499
1500 end function count_char
1501
1502 !---------------------------------------------------------------------
1503 ! utility to identify repeated tags in a list, written
1504 ! for use when labels were made by "make_tags_unique"
1505 !
1506 ! IN:
1507 ! tag - string to match, e.g. "massoftype"
1508 ! ntags - length of array to search
1509 ! tags - sequence of character strings to search
1510 !
1511 ! the routine then searches for consecutive entries matching
1512 ! the tag, e.g. massoftype1, massoftype2 etc and returns:
1513 !
1514 ! OUT:
1515 ! istartlist - start of list (e.g. location of massoftype1)
1516 ! nlist - number of tags matching string (i.e. N in massoftypeN)
1517 !----------------------------------------------------------------------
1518 subroutine find_repeated_tags(tag,ntags,tags,istartlist,nlist)
1519 character(len=*), intent(in) :: tag
1520 integer, intent(in) :: ntags
1521 character(len=*), intent(in) :: tags(ntags)
1522 integer, intent(out) :: istartlist,nlist
1523 integer :: i
1524 logical :: consecutive
1525
1526 istartlist = 0
1527 nlist = 0
1528 consecutive = .false.
1529 do i=1,ntags
1530 if (trim(tag)==tags(i)(1:len_trim(tag))) then
1531 if (nlist==0) then
1532 istartlist = i
1533 consecutive = .true.
1534 endif
1535 if (consecutive) nlist = nlist + 1
1536 else
1537 consecutive = .false.
1538 endif
1539 enddo
1540
1541 end subroutine find_repeated_tags
1542
1543 !------------------------------------------------------------
1544 ! utility to return up to five file extensions
1545 !------------------------------------------------------------
1546 subroutine get_extensions(string,extensions)
1547 character(len=*), intent(in) :: string
1548 character(len=12), dimension(5), intent(out) :: extensions(5)
1549 character(:), allocatable :: tmp_string
1550
1551 integer :: ppos_new
1552 integer :: ppos_old
1553 integer :: i
1554
1555 ppos_new = scan(trim(string),".", BACK= .true.)
1556 ppos_old = len(string)
1557 tmp_string = lcase(string)
1558
1559 do i=1,5
1560 if (ppos_new > 0) then
1561 extensions(i) = trim(tmp_string(ppos_new:ppos_old))
1562 tmp_string=tmp_string(1:ppos_new-1)
1563 ppos_old=ppos_new-1
1564 ppos_new=scan(trim(tmp_string),".",BACK=.true.)
1565 else
1566 extensions(i)=""
1567 endif
1568 enddo
1569
1570 end subroutine get_extensions
1571
1572 !---------------------------------------------------------------------------
1573 !+
1574 ! extract the start of the file extension, if the filename does not
1575 ! end with digits
1576 !+
1577 !---------------------------------------------------------------------------
1578 pure integer function get_idot(string)
1579 character(len=*), intent(in) :: string
1580 integer :: ilen
1581
1582 ilen = len_trim(string)
1583 get_idot = 0
1584 !
1585 ! if file ends in at least two numbers then use the numbers at the end
1586 ! (two is to avoid problems with .hdf5 etc)
1587 !
1588 if (ilen >= 2) then
1589 if (isdigit(string(ilen:ilen)) .and. isdigit(string(ilen-1:ilen-1))) then
1590 get_idot = ilen + 1
1591 endif
1592 endif
1593 !
1594 ! otherwise, look for numbers before the file extension (e.g. _0000.dat)
1595 !
1596 if (get_idot==0) then
1597 get_idot = index(string,'.',back=.true.)
1598 if (get_idot==0) get_idot = len_trim(string) + 1
1599 endif
1600
1601 end function get_idot
1602
1603 !----------------------------------------------------------------
1604 !+
1605 ! this function extracts the number at the end of the filename
1606 !+
1607 !----------------------------------------------------------------
1608 integer function numfromfile(filename)
1609 character(len=*), intent(in) :: filename
1610 character(len=len(filename)) :: string
1611 integer :: idot,istartnum,ilen,i,ierr
1612 !
1613 !--extract current number from filename
1614 !
1615 string = basename(filename)
1616 idot = get_idot(string)
1617 istartnum = 0
1618 do i=idot-1,1,-1
1619 if (istartnum==0) then
1620 if (.not.isdigit(string(i:i))) istartnum = i
1621 endif
1622 enddo
1623 if (istartnum /= 0) istartnum = istartnum + 1
1624 ilen = idot - istartnum
1625
1626 if (ilen > 0) then
1627 read(string(istartnum:istartnum+ilen-1),*,iostat=ierr) numfromfile
1628 if (ierr /= 0) then
1629 !print*,'internal error in numfromfilename'
1630 numfromfile = -1
1631 endif
1632 else
1633 numfromfile = 0
1634 endif
1635
1636 end function numfromfile
1637
1638 !------------------------------------------------------------
1639 ! utility to reorder a list of files. We use an insertion
1640 ! sort algorithm which preserves relative order of filenames
1641 ! so a list of files like:
1642 !
1643 ! disc_00000 disc_00001 disc_00002 disc1_00000 disc1_00002
1644 !
1645 ! will be reordered as:
1646 !
1647 ! disc_00000 disc1_00000 disc_00001 disc1_00001 disc_00002
1648 !
1649 ! Enhanced to handle padding: if multiple sequences exist and
1650 ! one runs out of files, it pads with the last available file
1651 ! from that sequence
1652 !------------------------------------------------------------
1653 subroutine sort_filenames_for_comparison(nfiles,filenames,pad)
1654 integer, intent(inout) :: nfiles
1655 character(len=*), intent(inout) :: filenames(:)
1656 logical, intent(in), optional :: pad
1657 character(len=100) :: key
1658 integer :: i,j,num
1659
1660 do i = 2, nfiles
1661 key = filenames(i)
1662 num = numfromfile(key)
1663 j = i - 1
1664
1665 ! move elements of the filenames array with number
1666 ! greater than the key to one position ahead
1667 ! of their current position
1668 do while(j >= 1 .and. numfromfile(filenames(j)) > num)
1669 filenames(j+1) = filenames(j)
1670 j = j - 1
1671 enddo
1672 filenames(j+1) = key
1673 enddo
1674
1675 ! Apply padding for incomplete groups
1676 if (present(pad)) then
1677 if (pad) call pad_incomplete_groups(nfiles, filenames)
1678 endif
1679
1680 end subroutine sort_filenames_for_comparison
1681
1682 !------------------------------------------------------------
1683 ! Subroutine to pad incomplete groups with files from
1684 ! the last complete group
1685 !------------------------------------------------------------
1686 subroutine pad_incomplete_groups(nfiles, filenames)
1687 integer, intent(inout) :: nfiles
1688 character(len=*), intent(inout) :: filenames(:)
1689 integer :: i, j, group_size, expected_size, last_complete_start
1690 integer :: current_num, last_complete_num
1691
1692 ! Find expected group size and last complete group
1693 expected_size = 1
1694 last_complete_start = 1
1695 last_complete_num = -1
1696 i = 1
1697
1698 do while (i <= nfiles)
1699 current_num = numfromfile(filenames(i))
1700 group_size = 1
1701 do while (i + group_size <= nfiles .and. numfromfile(filenames(i + group_size)) == current_num)
1702 group_size = group_size + 1
1703 enddo
1704
1705 if (group_size >= expected_size) then
1706 expected_size = group_size
1707 if (group_size > 1) then
1708 last_complete_start = i
1709 last_complete_num = current_num
1710 endif
1711 endif
1712 i = i + group_size
1713 enddo
1714
1715 ! Pad incomplete groups that come after the last complete group
1716 if (expected_size > 1 .and. last_complete_num >= 0) then
1717 i = 1
1718 do while (i <= nfiles)
1719 current_num = numfromfile(filenames(i))
1720 if (current_num > last_complete_num .and. i < nfiles .and. &
1721 numfromfile(filenames(i+1)) /= current_num) then
1722 ! This is an incomplete group - insert padding file after it
1723 if (nfiles < size(filenames)) then
1724 nfiles = nfiles + 1
1725 ! Shift everything after this position
1726 do j = nfiles, i + 2, -1
1727 filenames(j) = filenames(j-1)
1728 enddo
1729 ! Insert the padding file
1730 filenames(i+1) = filenames(last_complete_start + 1)
1731 endif
1732 endif
1733 i = i + 1
1734 enddo
1735 endif
1736
1737 end subroutine pad_incomplete_groups
1738
1739 !------------------------------------------------------------
1740 ! utility to read a variable from an ascii file
1741 ! in the form:
1742 !
1743 ! var = val ! comment
1744 !
1745 ! val is returned as a string, if not found leaves the
1746 ! input value unmodified
1747 !------------------------------------------------------------
1748 subroutine read_var_from_file(var,val,filename,ierr)
1749 character(len=*), intent(in) :: var
1750 character(len=*), intent(inout) :: val
1751 character(len=*), intent(in) :: filename
1752 integer, intent(out) :: ierr
1753 character(len=130) :: line
1754 integer :: j,lu,ieq,istart
1755 logical :: match
1756
1757 open(newunit=lu,file=filename,status='old',iostat=ierr)
1758 match = .false.
1759 do while(ierr==0 .and. .not.match)
1760 read(lu,"(a)",iostat=ierr) line
1761 if (index(line,var) /= 0) then
1762 istart = index(line,var)
1763 ieq = index(line(istart:),'=')
1764 val = line(istart+ieq+1:)
1765 match = .true.
1766 endif
1767 enddo
1768 close(lu)
1769
1770 if (match) then
1771 val = trim(adjustl(val))
1772 ! now cull the variable at a space or comma
1773 do j=1,len_trim(val)
1774 if (any((/' ',',',';',':','=','!'/)==val(j:j))) then
1775 val = val(1:j)
1776 exit
1777 endif
1778 enddo
1779 !else
1780 !print*,trim(var)//' not found in '//trim(filename)
1781 endif
1782
1783 end subroutine read_var_from_file
1784
1785 end module asciiutils