script/sort_dcms.pl untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 26 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 144 CC 2 SCAR 10.0
CC
2
Cov
0%
new_name
6.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.7
1 #!/usr/local/bin/perl
2  
3 =head1 sort_dcm.pl
4  
5 Reads dicom files from a zip file or directory, extracts Series, Study, and
6 Instance Number as well as series description and properly renames them.
7  
8 Call with
9 sort_dcms.pl < zip | directory > [ target ] [copy_flag]
10  
11 Default is to move (rename) the file to its new location, set copy_flag if you
12 want to copy instead.
13  
14 =cut
15  
16 use DicomPack::IO::DicomReader;
17 use Storable qw/dclone/;
18 use DicomPack::DB::DicomTagDict qw/getTag getTagDesc/;
19 use DicomPack::DB::DicomVRDict qw/getVR/;
20 use File::Copy 'move';
21 #use Exporter;
22 use strict;
23 use File::Copy;
24 use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
25 use 5.10.0;
26  
27  
28 my $path=shift || '.';
29 my $target=shift || "dicom";
30 my $cpy=shift ||0;
31 mkdir ("$target") unless (-d "$target");
32  
33 sub new_name {
34 my $file=shift;
35 my $dcm=DicomPack::IO::DicomReader->new($file) || return;
36 my $sn=$dcm->getValue("SeriesNumber");
37 my $in=$dcm->getValue("InstanceNumber");
38 my $st=$dcm->getValue("StudyID");
39 my $fn=$dcm->getValue("SeriesDescription");
40 my $en=eval{ $dcm->getValue("EchoNumbers"); } ||1;
41 return if ($fn=~/Phoenix.*Report/i);
42 $fn=~s/-\d*$//;
43 $fn=~s/ /_/g;
44 #say "file $file fn $fn";
45 my $newfile="Series_$st\_$sn\_$in\_echo_$en\_".$fn;
46 #say "new file $newfile;";
47 return $newfile;
48 }
49  
50 # directory or zip?
51 if ( -f $path && $path =~/.zip/ ) {
52 my $zip = new Archive::Zip;
53 ($zip->read($path) == AZ_OK) || die "Not a zip archive!\n";
54 my $tf='extract.tmp';
55 say "reading from zip";
56 for my $file ($zip->memberNames) {
57 #say "file $file";
58 $zip->extractMemberWithoutPaths($file,$tf);
59 my $newfile=new_name('extract.tmp');
60 if ($cpy) {
61 copy $tf,"$target/$newfile.IMA" ;
62 } else {
63 #say "move $tf, $target/$newfile.dcm" ;
64 move $tf,"$target/$newfile.IMA" ;
65 }
66 }
67 } else {
68 opendir( my $p ,$path) || die "Could not read from directory $path\n";
69 say "reading from directory";
70 for my $d (readdir ($p)) {
71 my $dir="$path/$d";
72 next if ($d eq '..' );
73 next unless ((-d $dir) || ((-f $dir) && $dir=~m/.IMA$|.dcm$/)) ;
74 opendir (my $dd ,$dir);
75 for my $f (readdir ($dd)) {
76 my $file="$dir/$f";
77 next unless ((-f $file) && $file=~m/.IMA$|.dcm$/) ;
78 my $newfile=new_name($file);
79 if ($cpy) {
80 copy $file,"$target/$newfile.IMA" ;
81 } else {
82 move $file,"$target/$newfile.IMA" ;
83 }
84 }
85 close $dd;
86 }
87 close $p;
88 }