]> granicus.if.org Git - imagemagick/blob - magick/utility.c
(no commit message)
[imagemagick] / magick / utility.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %             U   U  TTTTT  IIIII  L      IIIII  TTTTT  Y   Y                 %
7 %             U   U    T      I    L        I      T     Y Y                  %
8 %             U   U    T      I    L        I      T      Y                   %
9 %             U   U    T      I    L        I      T      Y                   %
10 %              UUU     T    IIIII  LLLLL  IIIII    T      Y                   %
11 %                                                                             %
12 %                                                                             %
13 %                       MagickCore Utility Methods                            %
14 %                                                                             %
15 %                             Software Design                                 %
16 %                               John Cristy                                   %
17 %                              January 1993                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2009 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "magick/studio.h"
43 #include "magick/property.h"
44 #include "magick/blob.h"
45 #include "magick/color.h"
46 #include "magick/exception.h"
47 #include "magick/exception-private.h"
48 #include "magick/geometry.h"
49 #include "magick/list.h"
50 #include "magick/log.h"
51 #include "magick/memory_.h"
52 #include "magick/option.h"
53 #include "magick/resource_.h"
54 #include "magick/semaphore.h"
55 #include "magick/signature-private.h"
56 #include "magick/statistic.h"
57 #include "magick/string_.h"
58 #include "magick/token.h"
59 #include "magick/utility.h"
60 #if defined(MAGICKCORE_HAVE_MACH_O_DYLD_H)
61 #include <mach-o/dyld.h>
62 #endif
63 \f
64 /*
65   Static declarations.
66 */
67 static const char
68   Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
69 \f
70 /*
71   Forward declaration.
72 */
73 static int
74   IsPathDirectory(const char *);
75 \f
76 /*
77 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78 %                                                                             %
79 %                                                                             %
80 %                                                                             %
81 %   A c q u i r e U n i q u e F i l e n a m e                                 %
82 %                                                                             %
83 %                                                                             %
84 %                                                                             %
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86 %
87 %  AcquireUniqueFilename() replaces the contents of path by a unique path name.
88 %
89 %  The format of the AcquireUniqueFilename method is:
90 %
91 %      MagickBooleanType AcquireUniqueFilename(char *path)
92 %
93 %  A description of each parameter follows.
94 %
95 %   o  path:  Specifies a pointer to an array of characters.  The unique path
96 %      name is returned in this array.
97 %
98 */
99 MagickExport MagickBooleanType AcquireUniqueFilename(char *path)
100 {
101   int
102     file;
103
104   file=AcquireUniqueFileResource(path);
105   if (file == -1)
106     return(MagickFalse);
107   file=close(file)-1;
108   return(MagickTrue);
109 }
110 \f
111 /*
112 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
113 %                                                                             %
114 %                                                                             %
115 %                                                                             %
116 %   A c q u i r e U n i q u e S ym b o l i c L i n k                          %
117 %                                                                             %
118 %                                                                             %
119 %                                                                             %
120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121 %
122 %  AcquireUniqueSymbolicLink() creates a unique symbolic link to the specified
123 %  source path and returns MagickTrue on success otherwise MagickFalse.  If the
124 %  symlink() method fails or is not available, a unique file name is generated
125 %  and the source file copied to it.  When you are finished with the file, use
126 %  RelinquishUniqueFilename() to destroy it.
127 %
128 %  The format of the AcquireUniqueSymbolicLink method is:
129 %
130 %      MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
131 %        char destination)
132 %
133 %  A description of each parameter follows.
134 %
135 %   o  source:  the source path.
136 %
137 %   o  destination:  the destination path.
138 %
139 */
140
141 static inline size_t MagickMin(const size_t x,const size_t y)
142 {
143   if (x < y)
144     return(x);
145   return(y);
146 }
147
148 MagickExport MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
149   char *destination)
150 {
151   int
152     destination_file,
153     source_file;
154
155   size_t
156     length,
157     quantum;
158
159   ssize_t
160     count;
161
162   struct stat
163     attributes;
164
165   unsigned char
166     *buffer;
167
168   assert(source != (const char *) NULL);
169   assert(destination != (char *) NULL);
170 #if defined(MAGICKCORE_HAVE_SYMLINK)
171   (void) AcquireUniqueFilename(destination);
172   (void) RelinquishUniqueFileResource(destination);
173   if (*source == *DirectorySeparator)
174     {
175       if (symlink(source,destination) == 0)
176         return(MagickTrue);
177     }
178   else
179     {
180       char
181         path[MaxTextExtent];
182
183       *path='\0';
184       if (getcwd(path,MaxTextExtent) == (char *) NULL)
185         return(MagickFalse);
186       (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
187       (void) ConcatenateMagickString(path,source,MaxTextExtent);
188       if (symlink(path,destination) == 0)
189         return(MagickTrue);
190     }
191 #endif
192   destination_file=AcquireUniqueFileResource(destination);
193   if (destination_file == -1)
194     return(MagickFalse);
195   source_file=open(source,O_RDONLY | O_BINARY);
196   if (source_file == -1)
197     {
198       (void) close(destination_file);
199       (void) RelinquishUniqueFileResource(destination);
200       return(MagickFalse);
201     }
202   quantum=(size_t) MagickMaxBufferExtent;
203   if ((fstat(source_file,&attributes) == 0) && (attributes.st_size != 0))
204     quantum=MagickMin((size_t) attributes.st_size,MagickMaxBufferExtent);
205   buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
206   if (buffer == (unsigned char *) NULL)
207     {
208       (void) close(source_file);
209       (void) close(destination_file);
210       (void) RelinquishUniqueFileResource(destination);
211       return(MagickFalse);
212     }
213   for (length=0; ; )
214   {
215     count=(ssize_t) read(source_file,buffer,quantum);
216     if (count <= 0)
217       break;
218     length=(size_t) count;
219     count=(ssize_t) write(destination_file,buffer,length);
220     if ((size_t) count != length)
221       {
222         (void) close(destination_file);
223         (void) close(source_file);
224         buffer=(unsigned char *) RelinquishMagickMemory(buffer);
225         (void) RelinquishUniqueFileResource(destination);
226         return(MagickFalse);
227       }
228   }
229   (void) close(destination_file);
230   (void) close(source_file);
231   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
232   return(MagickTrue);
233 }
234 \f
235 /*
236 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
237 %                                                                             %
238 %                                                                             %
239 %                                                                             %
240 %  A p p e n d I m a g e F o r m a t                                          %
241 %                                                                             %
242 %                                                                             %
243 %                                                                             %
244 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
245 %
246 %  AppendImageFormat() appends the image format type to the filename.  If an
247 %  extension to the file already exists, it is first removed.
248 %
249 %  The format of the AppendImageFormat method is:
250 %
251 %      void AppendImageFormat(const char *format,char *filename)
252 %
253 %  A description of each parameter follows.
254 %
255 %   o  format:  Specifies a pointer to an array of characters.  This the
256 %      format of the image.
257 %
258 %   o  filename:  Specifies a pointer to an array of characters.  The unique
259 %      file name is returned in this array.
260 %
261 */
262 MagickExport void AppendImageFormat(const char *format,char *filename)
263 {
264   char
265     root[MaxTextExtent];
266
267   assert(format != (char *) NULL);
268   assert(filename != (char *) NULL);
269   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
270   if ((*format == '\0') || (*filename == '\0'))
271     return;
272   if (LocaleCompare(filename,"-") == 0)
273     {
274       char
275         message[MaxTextExtent];
276
277       (void) FormatMagickString(message,MaxTextExtent,"%s:%s",format,filename);
278       (void) CopyMagickString(filename,message,MaxTextExtent);
279       return;
280     }
281   GetPathComponent(filename,RootPath,root);
282   (void) FormatMagickString(filename,MaxTextExtent,"%s.%s",root,format);
283 }
284 \f
285 /*
286 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
287 %                                                                             %
288 %                                                                             %
289 %                                                                             %
290 %   B a s e 6 4 D e c o d e                                                   %
291 %                                                                             %
292 %                                                                             %
293 %                                                                             %
294 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
295 %
296 %  Base64Decode() decodes Base64-encoded text and returns its binary
297 %  equivalent.  NULL is returned if the text is not valid Base64 data, or a
298 %  memory allocation failure occurs.
299 %
300 %  The format of the Base64Decode method is:
301 %
302 %      unsigned char *Base64Decode(const char *source,length_t *length)
303 %
304 %  A description of each parameter follows:
305 %
306 %    o source:  A pointer to a Base64-encoded string.
307 %
308 %    o length: the number of bytes decoded.
309 %
310 */
311 MagickExport unsigned char *Base64Decode(const char *source,size_t *length)
312 {
313   int
314     state;
315
316   register const char
317     *p,
318     *q;
319
320   register size_t
321     i;
322
323   unsigned char
324     *decode;
325
326   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
327   assert(source != (char *) NULL);
328   assert(length != (size_t *) NULL);
329   *length=0;
330   decode=(unsigned char *) AcquireQuantumMemory(strlen(source)/4+4,
331     3*sizeof(*decode));
332   if (decode == (unsigned char *) NULL)
333     return((unsigned char *) NULL);
334   i=0;
335   state=0;
336   for (p=source; *p != '\0'; p++)
337   {
338     if (isspace((int) ((unsigned char) *p)) != 0)
339       continue;
340     if (*p == '=')
341       break;
342     q=strchr(Base64,*p);
343     if (q == (char *) NULL)
344       {
345         decode=(unsigned char *) RelinquishMagickMemory(decode);
346         return((unsigned char *) NULL);  /* non-Base64 character */
347       }
348     switch (state)
349     {
350       case 0:
351       {
352         decode[i]=(q-Base64) << 2;
353         state++;
354         break;
355       }
356       case 1:
357       {
358         decode[i++]|=(q-Base64) >> 4;
359         decode[i]=((q-Base64) & 0x0f) << 4;
360         state++;
361         break;
362       }
363       case 2:
364       {
365         decode[i++]|=(q-Base64) >> 2;
366         decode[i]=((q-Base64) & 0x03) << 6;
367         state++;
368         break;
369       }
370       case 3:
371       {
372         decode[i++]|=(q-Base64);
373         state=0;
374         break;
375       }
376     }
377   }
378   /*
379     Verify Base-64 string has proper terminal characters.
380   */
381   if (*p != '=')
382     {
383       if (state != 0)
384         {
385           decode=(unsigned char *) RelinquishMagickMemory(decode);
386           return((unsigned char *) NULL);
387         }
388     }
389   else
390     {
391       p++;
392       switch (state)
393       {
394         case 0:
395         case 1:
396         {
397           /*
398             Unrecognized '=' character.
399           */
400           decode=(unsigned char *) RelinquishMagickMemory(decode);
401           return((unsigned char *) NULL);
402         }
403         case 2:
404         {
405           for ( ; *p != '\0'; p++)
406             if (isspace((int) ((unsigned char) *p)) == 0)
407               break;
408           if (*p != '=')
409             {
410               decode=(unsigned char *) RelinquishMagickMemory(decode);
411               return((unsigned char *) NULL);
412             }
413           p++;
414         }
415         case 3:
416         {
417           for ( ; *p != '\0'; p++)
418             if (isspace((int) ((unsigned char) *p)) == 0)
419               {
420                 decode=(unsigned char *) RelinquishMagickMemory(decode);
421                 return((unsigned char *) NULL);
422               }
423           if ((int) decode[i] != 0)
424             {
425               decode=(unsigned char *) RelinquishMagickMemory(decode);
426               return((unsigned char *) NULL);
427             }
428         }
429       }
430     }
431   *length=i;
432   return(decode);
433 }
434 \f
435 /*
436 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
437 %                                                                             %
438 %                                                                             %
439 %                                                                             %
440 %   B a s e 6 4 E n c o d e                                                   %
441 %                                                                             %
442 %                                                                             %
443 %                                                                             %
444 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
445 %
446 %  Base64Encode() encodes arbitrary binary data to Base64 encoded format as
447 %  described by the "Base64 Content-Transfer-Encoding" section of RFC 2045 and
448 %  returns the result as a null-terminated ASCII string.  NULL is returned if
449 %  a memory allocation failure occurs.
450 %
451 %  The format of the Base64Encode method is:
452 %
453 %      char *Base64Encode(const unsigned char *blob,const size_t blob_length,
454 %        size_t *encode_length)
455 %
456 %  A description of each parameter follows:
457 %
458 %    o blob:  A pointer to binary data to encode.
459 %
460 %    o blob_length: the number of bytes to encode.
461 %
462 %    o encode_length:  The number of bytes encoded.
463 %
464 */
465 MagickExport char *Base64Encode(const unsigned char *blob,
466   const size_t blob_length,size_t *encode_length)
467 {
468   char
469     *encode;
470
471   register const unsigned char
472     *p;
473
474   register size_t
475     i;
476
477   size_t
478     remainder;
479
480   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
481   assert(blob != (const unsigned char *) NULL);
482   assert(blob_length != 0);
483   assert(encode_length != (size_t *) NULL);
484   *encode_length=0;
485   encode=(char *) AcquireQuantumMemory(blob_length/3+4,4*sizeof(*encode));
486   if (encode == (char *) NULL)
487     return((char *) NULL);
488   i=0;
489   for (p=blob; p < (blob+blob_length-2); p+=3)
490   {
491     encode[i++]=Base64[(int) (*p >> 2)];
492     encode[i++]=Base64[(int) (((*p & 0x03) << 4)+(*(p+1) >> 4))];
493     encode[i++]=Base64[(int) (((*(p+1) & 0x0f) << 2)+(*(p+2) >> 6))];
494     encode[i++]=Base64[(int) (*(p+2) & 0x3f)];
495   }
496   remainder=blob_length % 3;
497   if (remainder != 0)
498     {
499       long
500         j;
501
502       unsigned char
503         code[3];
504
505       code[0]='\0';
506       code[1]='\0';
507       code[2]='\0';
508       for (j=0; j < (long) remainder; j++)
509         code[j]=(*p++);
510       encode[i++]=Base64[(int) (code[0] >> 2)];
511       encode[i++]=Base64[(int) (((code[0] & 0x03) << 4)+(code[1] >> 4))];
512       if (remainder == 1)
513         encode[i++]='=';
514       else
515         encode[i++]=Base64[(int) (((code[1] & 0x0f) << 2)+(code[2] >> 6))];
516       encode[i++]='=';
517     }
518   *encode_length=i;
519   encode[i++]='\0';
520   return(encode);
521 }
522 \f
523 /*
524 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
525 %                                                                             %
526 %                                                                             %
527 %                                                                             %
528 %   C h o p P a t h C o m p o n e n t s                                       %
529 %                                                                             %
530 %                                                                             %
531 %                                                                             %
532 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
533 %
534 %  ChopPathComponents() removes the number of specified file components from a
535 %  path.
536 %
537 %  The format of the ChopPathComponents method is:
538 %
539 %      ChopPathComponents(char *path,unsigned long components)
540 %
541 %  A description of each parameter follows:
542 %
543 %    o path:  The path.
544 %
545 %    o components:  The number of components to chop.
546 %
547 */
548 MagickExport void ChopPathComponents(char *path,const unsigned long components)
549 {
550   register long
551     i;
552
553   for (i=0; i < (long) components; i++)
554     GetPathComponent(path,HeadPath,path);
555 }
556 \f
557 /*
558 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
559 %                                                                             %
560 %                                                                             %
561 %                                                                             %
562 %   E x p a n d F i l e n a m e                                               %
563 %                                                                             %
564 %                                                                             %
565 %                                                                             %
566 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
567 %
568 %  ExpandFilename() expands '~' in a path.
569 %
570 %  The format of the ExpandFilename function is:
571 %
572 %      ExpandFilename(char *path)
573 %
574 %  A description of each parameter follows:
575 %
576 %    o path: Specifies a pointer to a character array that contains the
577 %      path.
578 %
579 */
580 MagickExport void ExpandFilename(char *path)
581 {
582   char
583     expand_path[MaxTextExtent];
584
585   if (path == (char *) NULL)
586     return;
587   if (*path != '~')
588     return;
589   (void) CopyMagickString(expand_path,path,MaxTextExtent);
590   if ((*(path+1) == *DirectorySeparator) || (*(path+1) == '\0'))
591     {
592       char
593         *home;
594
595       /*
596         Substitute ~ with $HOME.
597       */
598       (void) CopyMagickString(expand_path,".",MaxTextExtent);
599       (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
600       home=GetEnvironmentValue("HOME");
601       if (home == (char *) NULL)
602         home=GetEnvironmentValue("USERPROFILE");
603       if (home != (char *) NULL)
604         {
605           (void) CopyMagickString(expand_path,home,MaxTextExtent);
606           (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
607           home=DestroyString(home);
608         }
609     }
610   else
611     {
612 #if defined(MAGICKCORE_POSIX_SUPPORT) && !defined(__OS2__)
613       char
614         username[MaxTextExtent];
615
616       register char
617         *p;
618
619       struct passwd
620         *entry;
621
622       /*
623         Substitute ~ with home directory from password file.
624       */
625       (void) CopyMagickString(username,path+1,MaxTextExtent);
626       p=strchr(username,'/');
627       if (p != (char *) NULL)
628         *p='\0';
629       entry=getpwnam(username);
630       if (entry == (struct passwd *) NULL)
631         return;
632       (void) CopyMagickString(expand_path,entry->pw_dir,MaxTextExtent);
633       if (p != (char *) NULL)
634         {
635           (void) ConcatenateMagickString(expand_path,"/",MaxTextExtent);
636           (void) ConcatenateMagickString(expand_path,p+1,MaxTextExtent);
637         }
638 #endif
639     }
640   (void) CopyMagickString(path,expand_path,MaxTextExtent);
641 }
642 \f
643 /*
644 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
645 %                                                                             %
646 %                                                                             %
647 %                                                                             %
648 %   E x p a n d F i l e n a m e s                                             %
649 %                                                                             %
650 %                                                                             %
651 %                                                                             %
652 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
653 %
654 %  ExpandFilenames() checks each argument of the command line vector and
655 %  expands it if they have a wildcard character.  For example, *.jpg might
656 %  expand to:  bird.jpg rose.jpg tiki.jpg.
657 %
658 %  The format of the ExpandFilenames function is:
659 %
660 %      status=ExpandFilenames(int *number_arguments,char ***arguments)
661 %
662 %  A description of each parameter follows:
663 %
664 %    o number_arguments: Specifies a pointer to an integer describing the
665 %      number of elements in the argument vector.
666 %
667 %    o arguments: Specifies a pointer to a text array containing the command
668 %      line arguments.
669 %
670 */
671 MagickExport MagickBooleanType ExpandFilenames(int *number_arguments,
672   char ***arguments)
673 {
674   char
675     *cwd,
676     home_directory[MaxTextExtent],
677     **vector;
678
679   long
680     count,
681     parameters;
682
683   register long
684     i,
685     j;
686
687   unsigned long
688     number_files;
689
690   /*
691     Allocate argument vector.
692   */
693   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
694   assert(number_arguments != (int *) NULL);
695   assert(arguments != (char ***) NULL);
696   vector=(char **) AcquireQuantumMemory((size_t) (*number_arguments+1),
697     sizeof(*vector));
698   if (vector == (char **) NULL)
699     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
700   /*
701     Expand any wildcard filenames.
702   */
703   *home_directory='\0';
704   cwd=getcwd(home_directory,MaxTextExtent);
705   count=0;
706   for (i=0; i < (long) *number_arguments; i++)
707   {
708     char
709       **filelist,
710       filename[MaxTextExtent],
711       magick[MaxTextExtent],
712       *option,
713       path[MaxTextExtent],
714       subimage[MaxTextExtent];
715
716     MagickBooleanType
717       destroy;
718
719     option=(*arguments)[i];
720     *magick='\0';
721     *path='\0';
722     *filename='\0';
723     *subimage='\0';
724     vector[count++]=ConstantString(option);
725     destroy=MagickTrue;
726     parameters=ParseMagickOption(MagickCommandOptions,MagickFalse,option);
727     if (parameters > 0)
728       {
729         /*
730           Do not expand command option parameters.
731         */
732         for (j=0; j < parameters; j++)
733         {
734           i++;
735           if (i == (long) *number_arguments)
736             break;
737           option=(*arguments)[i];
738           vector[count++]=ConstantString(option);
739         }
740         continue;
741       }
742     if ((*option == '"') || (*option == '\''))
743       continue;
744     GetPathComponent(option,TailPath,filename);
745     GetPathComponent(option,MagickPath,magick);
746     if ((LocaleCompare(magick,"CAPTION") == 0) ||
747         (LocaleCompare(magick,"LABEL") == 0) ||
748         (LocaleCompare(magick,"VID") == 0))
749       continue;
750     if ((IsGlob(filename) == MagickFalse) && (*filename != '@'))
751       continue;
752     if (*filename != '@')
753       {
754         /*
755           Generate file list from wildcard filename (e.g. *.jpg).
756         */
757         GetPathComponent(option,HeadPath,path);
758         GetPathComponent(option,SubimagePath,subimage);
759         ExpandFilename(path);
760         filelist=ListFiles(*path == '\0' ? home_directory : path,filename,
761           &number_files);
762       }
763     else
764       {
765         char
766           *files;
767
768         ExceptionInfo
769           *exception;
770
771         int
772           number_images;
773
774         /*
775           Generate file list from file list (e.g. @filelist.txt).
776         */
777         exception=AcquireExceptionInfo();
778         files=FileToString(filename+1,~0,exception);
779         exception=DestroyExceptionInfo(exception);
780         if (files == (char *) NULL)
781           continue;
782         StripString(files);
783         filelist=StringToArgv(files,&number_images);
784         files=DestroyString(files);
785         number_files=(unsigned long) number_images;
786         if (filelist != (char **) NULL)
787           {
788             number_files--;
789             for (j=0; j < (long) number_files; j++)
790               filelist[j]=filelist[j+1];
791           }
792       }
793     if (filelist == (char **) NULL)
794       continue;
795     for (j=0; j < (long) number_files; j++)
796       if (IsPathDirectory(filelist[j]) <= 0)
797         break;
798     if (j == (long) number_files)
799       {
800         for (j=0; j < (long) number_files; j++)
801           filelist[j]=DestroyString(filelist[j]);
802         filelist=(char **) RelinquishMagickMemory(filelist);
803         continue;
804       }
805     /*
806       Transfer file list to argument vector.
807     */
808     vector=(char **) ResizeQuantumMemory(vector,(size_t) *number_arguments+
809       count+number_files+1,sizeof(*vector));
810     if (vector == (char **) NULL)
811       return(MagickFalse);
812     for (j=0; j < (long) number_files; j++)
813     {
814       (void) CopyMagickString(filename,path,MaxTextExtent);
815       if (*path != '\0')
816         (void) ConcatenateMagickString(filename,DirectorySeparator,
817           MaxTextExtent);
818       (void) ConcatenateMagickString(filename,filelist[j],MaxTextExtent);
819       filelist[j]=DestroyString(filelist[j]);
820       if (strlen(filename) >= MaxTextExtent)
821         ThrowFatalException(OptionFatalError,"FilenameTruncated");
822       if (IsPathDirectory(filename) == 0)
823         {
824           char
825             path[MaxTextExtent];
826
827           *path='\0';
828           if (*magick != '\0')
829             {
830               (void) ConcatenateMagickString(path,magick,MaxTextExtent);
831               (void) ConcatenateMagickString(path,":",MaxTextExtent);
832             }
833           (void) ConcatenateMagickString(path,filename,MaxTextExtent);
834           if (*subimage != '\0')
835             {
836               (void) ConcatenateMagickString(path,"[",MaxTextExtent);
837               (void) ConcatenateMagickString(path,subimage,MaxTextExtent);
838               (void) ConcatenateMagickString(path,"]",MaxTextExtent);
839             }
840           if (strlen(path) >= MaxTextExtent)
841             ThrowFatalException(OptionFatalError,"FilenameTruncated");
842           if (destroy != MagickFalse)
843             {
844               count--;
845               vector[count]=DestroyString(vector[count]);
846               destroy=MagickFalse;
847             }
848           vector[count++]=ConstantString(path);
849         }
850     }
851     filelist=(char **) RelinquishMagickMemory(filelist);
852   }
853   vector[count]=(char *) NULL;
854   if (IsEventLogging() != MagickFalse)
855     {
856       char
857         *command_line;
858
859       command_line=AcquireString(vector[0]);
860       for (i=1; i < count; i++)
861       {
862         (void) ConcatenateString(&command_line," {");
863         (void) ConcatenateString(&command_line,vector[i]);
864         (void) ConcatenateString(&command_line,"}");
865       }
866       (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
867         "Command line: %s",command_line);
868       command_line=DestroyString(command_line);
869     }
870   *number_arguments=(int) count;
871   *arguments=vector;
872   return(MagickTrue);
873 }
874 \f
875 /*
876 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
877 %                                                                             %
878 %                                                                             %
879 %                                                                             %
880 %   G e t E x e c u t i o n P a t h                                           %
881 %                                                                             %
882 %                                                                             %
883 %                                                                             %
884 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
885 %
886 %  GetExecutionPath() returns the pathname of the executable that started
887 %  the process.  On success MagickTrue is returned, otherwise MagickFalse.
888 %
889 %  The format of the GetExecutionPath method is:
890 %
891 %      MagickBooleanType GetExecutionPath(char *path,const size_t extent)
892 %
893 %  A description of each parameter follows:
894 %
895 %    o path: the pathname of the executable that started the process.
896 %
897 %    o extent: the maximum extent of the path.
898 %
899 */
900 MagickExport MagickBooleanType GetExecutionPath(char *path,const size_t extent)
901 {
902   char
903     *cwd;
904
905   *path='\0';
906   cwd=getcwd(path,(unsigned long) extent);
907 #if defined(MAGICKCORE_HAVE_GETPID) && defined(MAGICKCORE_HAVE_READLINK)
908   {
909     char
910       link_path[MaxTextExtent],
911       real_path[PATH_MAX+1];
912
913     ssize_t
914       count;
915
916     (void) FormatMagickString(link_path,MaxTextExtent,"/proc/%ld/exe",
917       (long) getpid());
918     count=readlink(link_path,real_path,PATH_MAX);
919     if (count == -1)
920       {
921         (void) FormatMagickString(link_path,MaxTextExtent,"/proc/%ld/file",
922           (long) getpid());
923         count=readlink(link_path,real_path,PATH_MAX);
924       }
925     if ((count > 0) && (count <= (ssize_t) PATH_MAX))
926       {
927         real_path[count]='\0';
928         (void) CopyMagickString(path,real_path,extent);
929       }
930   }
931 #endif
932 #if defined(MAGICKCORE_HAVE__NSGETEXECUTABLEPATH)
933   {
934     char
935       executable_path[PATH_MAX << 1],
936       real_path[PATH_MAX+1];
937
938     uint32_t
939       length;
940
941     length=sizeof(executable_path);
942     if ((_NSGetExecutablePath(executable_path,&length) == 0) &&
943         (realpath(executable_path,real_path) != (char *) NULL))
944       (void) CopyMagickString(path,real_path,extent);
945   }
946 #endif
947 #if defined(MAGICKCORE_HAVE_GETEXECNAME)
948   {
949     const char
950       *execution_path;
951
952     execution_path=(const char *) getexecname();
953     if (execution_path != (const char *) NULL)
954       {
955         if (*execution_path != *DirectorySeparator)
956           (void) ConcatenateMagickString(path,DirectorySeparator,extent);
957         (void) ConcatenateMagickString(path,execution_path,extent);
958       }
959   }
960 #endif
961 #if defined(__WINDOWS__)
962   NTGetExecutionPath(path,extent);
963 #endif
964   return(IsPathAccessible(path));
965 }
966 \f
967 /*
968 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
969 %                                                                             %
970 %                                                                             %
971 %                                                                             %
972 %   G e t P a t h A t t r i b u t e s                                         %
973 %                                                                             %
974 %                                                                             %
975 %                                                                             %
976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
977 %
978 %  GetPathAttributes() returns attributes (e.g. size of file) about a path.
979 %
980 %  The path of the GetPathAttributes method is:
981 %
982 %      MagickBooleanType GetPathAttributes(const char *path,void *attributes)
983 %
984 %  A description of each parameter follows.
985 %
986 %   o  path: the file path.
987 %
988 %   o  attributes: the path attributes are returned here.
989 %
990 */
991
992 #if defined(MAGICKCORE_HAVE__WFOPEN)
993 static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16)
994 {
995   register const unsigned char
996     *p;
997
998   if (utf16 != (wchar_t *) NULL)
999     {
1000       register wchar_t
1001         *q;
1002
1003       wchar_t
1004         c;
1005
1006       /*
1007         Convert UTF-8 to UTF-16.
1008       */
1009       q=utf16;
1010       for (p=utf8; *p != '\0'; p++)
1011       {
1012         if ((*p & 0x80) == 0)
1013           *q=(*p);
1014         else
1015           if ((*p & 0xE0) == 0xC0)
1016             {
1017               c=(*p);
1018               *q=(c & 0x1F) << 6;
1019               p++;
1020               if ((*p & 0xC0) != 0x80)
1021                 return(0);
1022               *q|=(*p & 0x3F);
1023             }
1024           else
1025             if ((*p & 0xF0) == 0xE0)
1026               {
1027                 c=(*p);
1028                 *q=c << 12;
1029                 p++;
1030                 if ((*p & 0xC0) != 0x80)
1031                   return(0);
1032                 c=(*p);
1033                 *q|=(c & 0x3F) << 6;
1034                 p++;
1035                 if ((*p & 0xC0) != 0x80)
1036                   return(0);
1037                 *q|=(*p & 0x3F);
1038               }
1039             else
1040               return(0);
1041         q++;
1042       }
1043       *q++='\0';
1044       return(q-utf16);
1045     }
1046   /*
1047     Compute UTF-16 string length.
1048   */
1049   for (p=utf8; *p != '\0'; p++)
1050   {
1051     if ((*p & 0x80) == 0)
1052       ;
1053     else
1054       if ((*p & 0xE0) == 0xC0)
1055         {
1056           p++;
1057           if ((*p & 0xC0) != 0x80)
1058             return(0);
1059         }
1060       else
1061         if ((*p & 0xF0) == 0xE0)
1062           {
1063             p++;
1064             if ((*p & 0xC0) != 0x80)
1065               return(0);
1066             p++;
1067             if ((*p & 0xC0) != 0x80)
1068               return(0);
1069          }
1070        else
1071          return(0);
1072   }
1073   return(p-utf8);
1074 }
1075
1076 static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source)
1077 {
1078   size_t
1079     length;
1080
1081   wchar_t
1082     *utf16;
1083
1084   length=UTF8ToUTF16(source,(wchar_t *) NULL);
1085   if (length == 0)
1086     {
1087       register long
1088         i;
1089
1090       /*
1091         Not UTF-8, just copy.
1092       */
1093       length=strlen(source);
1094       utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
1095       if (utf16 == (wchar_t *) NULL)
1096         return((wchar_t *) NULL);
1097       for (i=0; i <= (long) length; i++)
1098         utf16[i]=source[i];
1099       return(utf16);
1100     }
1101   utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
1102   if (utf16 == (wchar_t *) NULL)
1103     return((wchar_t *) NULL);
1104   length=UTF8ToUTF16(source,utf16);
1105   return(utf16);
1106 }
1107 #endif
1108
1109 MagickExport MagickBooleanType GetPathAttributes(const char *path,
1110   void *attributes)
1111 {
1112   MagickBooleanType
1113     status;
1114
1115   if (path == (const char *) NULL)
1116     {
1117       errno=EINVAL;
1118       return(MagickFalse);
1119     }
1120 #if !defined(MAGICKCORE_HAVE__WSTAT)
1121   status=stat(path,(struct stat *) attributes) == 0 ? MagickTrue : MagickFalse;
1122 #else
1123   {
1124     wchar_t
1125       *unicode_path;
1126
1127     unicode_path=ConvertUTF8ToUTF16(path);
1128     if (unicode_path == (wchar_t *) NULL)
1129       return(MagickFalse);
1130     status=wstat(unicode_path,(struct stat *) attributes) == 0 ? MagickTrue :
1131       MagickFalse;
1132     unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1133   }
1134 #endif
1135   return(status);
1136 }
1137 \f
1138 /*
1139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1140 %                                                                             %
1141 %                                                                             %
1142 %                                                                             %
1143 %   G e t P a t h C o m p o n e n t                                           %
1144 %                                                                             %
1145 %                                                                             %
1146 %                                                                             %
1147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1148 %
1149 %  GetPathComponent() returns the parent directory name, filename, basename, or
1150 %  extension of a file path.
1151 %
1152 %  The format of the GetPathComponent function is:
1153 %
1154 %      GetPathComponent(const char *path,PathType type,char *component)
1155 %
1156 %  A description of each parameter follows:
1157 %
1158 %    o path: Specifies a pointer to a character array that contains the
1159 %      file path.
1160 %
1161 %    o type: Specififies which file path component to return.
1162 %
1163 %    o component: the selected file path component is returned here.
1164 %
1165 */
1166 MagickExport void GetPathComponent(const char *path,PathType type,
1167   char *component)
1168 {
1169   char
1170     magick[MaxTextExtent],
1171     *q,
1172     subimage[MaxTextExtent];
1173
1174   register char
1175     *p;
1176
1177   assert(path != (const char *) NULL);
1178   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",path);
1179   assert(component != (char *) NULL);
1180   if (*path == '\0')
1181     {
1182       *component='\0';
1183       return;
1184     }
1185   (void) CopyMagickString(component,path,MaxTextExtent);
1186   *magick='\0';
1187 #if defined(__OS2__)
1188   if (path[1] != ":")
1189 #endif
1190   for (p=component; *p != '\0'; p++)
1191     if ((*p == ':') && (IsPathDirectory(path) < 0) &&
1192         (IsPathAccessible(path) == MagickFalse))
1193       {
1194         /*
1195           Look for image format specification (e.g. ps3:image).
1196         */
1197         (void) CopyMagickString(magick,component,(size_t) (p-component+1));
1198         if (IsMagickConflict(magick) != MagickFalse)
1199           *magick='\0';
1200         else
1201           for (q=component; *q != '\0'; q++)
1202             *q=(*++p);
1203         break;
1204       }
1205   *subimage='\0';
1206   p=component;
1207   if (*p != '\0')
1208     p=component+strlen(component)-1;
1209   if ((*p == ']') && (strchr(component,'[') != (char *) NULL) &&
1210       (IsPathAccessible(path) == MagickFalse))
1211     {
1212       /*
1213         Look for scene specification (e.g. img0001.pcd[4]).
1214       */
1215       for (q=p-1; q > component; q--)
1216         if (*q == '[')
1217           break;
1218       if (*q == '[')
1219         {
1220           (void) CopyMagickString(subimage,q+1,MaxTextExtent);
1221           subimage[p-q-1]='\0';
1222           if ((IsSceneGeometry(subimage,MagickFalse) == MagickFalse) &&
1223               (IsGeometry(subimage) == MagickFalse))
1224             *subimage='\0';
1225           else
1226             *q='\0';
1227         }
1228     }
1229   p=component;
1230   if (*p != '\0')
1231     for (p=component+strlen(component)-1; p > component; p--)
1232       if (IsBasenameSeparator(*p) != MagickFalse)
1233         break;
1234   switch (type)
1235   {
1236     case MagickPath:
1237     {
1238       (void) CopyMagickString(component,magick,MaxTextExtent);
1239       break;
1240     }
1241     case RootPath:
1242     {
1243       for (p=component+(strlen(component)-1); p > component; p--)
1244       {
1245         if (IsBasenameSeparator(*p) != MagickFalse)
1246           break;
1247         if (*p == '.')
1248           break;
1249       }
1250       if (*p == '.')
1251         *p='\0';
1252       break;
1253     }
1254     case HeadPath:
1255     {
1256       *p='\0';
1257       break;
1258     }
1259     case TailPath:
1260     {
1261       if (IsBasenameSeparator(*p) != MagickFalse)
1262         (void) CopyMagickMemory((unsigned char *) component,
1263           (const unsigned char *) (p+1),strlen(p+1)+1);
1264       break;
1265     }
1266     case BasePath:
1267     {
1268       if (IsBasenameSeparator(*p) != MagickFalse)
1269         (void) CopyMagickString(component,p+1,MaxTextExtent);
1270       for (p=component+(strlen(component)-1); p > component; p--)
1271         if (*p == '.')
1272           {
1273             *p='\0';
1274             break;
1275           }
1276       break;
1277     }
1278     case ExtensionPath:
1279     {
1280       if (IsBasenameSeparator(*p) != MagickFalse)
1281         (void) CopyMagickString(component,p+1,MaxTextExtent);
1282       p=component;
1283       if (*p != '\0')
1284         for (p=component+strlen(component)-1; p > component; p--)
1285           if (*p == '.')
1286             break;
1287       *component='\0';
1288       if (*p == '.')
1289         (void) CopyMagickString(component,p+1,MaxTextExtent);
1290       break;
1291     }
1292     case SubimagePath:
1293     {
1294       (void) CopyMagickString(component,subimage,MaxTextExtent);
1295       break;
1296     }
1297     case CanonicalPath:
1298     case UndefinedPath:
1299       break;
1300   }
1301 }
1302 \f
1303 /*
1304 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1305 %                                                                             %
1306 %                                                                             %
1307 %                                                                             %
1308 %  G e t P a t h C o m p o n e n t s                                          %
1309 %                                                                             %
1310 %                                                                             %
1311 %                                                                             %
1312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1313 %
1314 %  GetPathComponents() returns a list of path components.
1315 %
1316 %  The format of the GetPathComponents method is:
1317 %
1318 %      char **GetPathComponents(const char *path,
1319 %        unsigned long *number_componenets)
1320 %
1321 %  A description of each parameter follows:
1322 %
1323 %    o path:  Specifies the string to segment into a list.
1324 %
1325 %    o number_components:  return the number of components in the list
1326 %
1327 */
1328 MagickExport char **GetPathComponents(const char *path,
1329   unsigned long *number_components)
1330 {
1331   char
1332     **components;
1333
1334   register const char
1335     *p,
1336     *q;
1337
1338   register long
1339     i;
1340
1341   if (path == (char *) NULL)
1342     return((char **) NULL);
1343   *number_components=1;
1344   for (p=path; *p != '\0'; p++)
1345     if (IsBasenameSeparator(*p))
1346       (*number_components)++;
1347   components=(char **) AcquireQuantumMemory((size_t) *number_components+1UL,
1348     sizeof(*components));
1349   if (components == (char **) NULL)
1350     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1351   p=path;
1352   for (i=0; i < (long) *number_components; i++)
1353   {
1354     for (q=p; *q != '\0'; q++)
1355       if (IsBasenameSeparator(*q))
1356         break;
1357     components[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MaxTextExtent,
1358       sizeof(*components));
1359     if (components[i] == (char *) NULL)
1360       ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1361     (void) CopyMagickString(components[i],p,(size_t) (q-p+1));
1362     p=q+1;
1363   }
1364   components[i]=(char *) NULL;
1365   return(components);
1366 }
1367 \f
1368 /*
1369 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1370 %                                                                             %
1371 %                                                                             %
1372 %                                                                             %
1373 %  I s P a t h A c c e s s i b l e                                            %
1374 %                                                                             %
1375 %                                                                             %
1376 %                                                                             %
1377 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1378 %
1379 %  IsPathAccessible() returns MagickTrue if the file as defined by the path is
1380 %  accessible.
1381 %
1382 %  The format of the IsPathAccessible method is:
1383 %
1384 %      MagickBooleanType IsPathAccessible(const char *filename)
1385 %
1386 %  A description of each parameter follows.
1387 %
1388 %    o path:  Specifies a path to a file.
1389 %
1390 */
1391 MagickExport MagickBooleanType IsPathAccessible(const char *path)
1392 {
1393   MagickBooleanType
1394     status;
1395
1396   struct stat
1397     attributes;
1398
1399   if ((path == (const char *) NULL) || (*path == '\0'))
1400     return(MagickFalse);
1401   status=GetPathAttributes(path,&attributes);
1402   if (status == MagickFalse)
1403     return(status);
1404   if (S_ISREG(attributes.st_mode) == 0)
1405     return(MagickFalse);
1406   if (access(path,F_OK) != 0)
1407     return(MagickFalse);
1408   return(MagickTrue);
1409 }
1410 \f
1411 /*
1412 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1413 %                                                                             %
1414 %                                                                             %
1415 %                                                                             %
1416 +  I s P a t h D i r e c t o r y                                              %
1417 %                                                                             %
1418 %                                                                             %
1419 %                                                                             %
1420 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1421 %
1422 %  IsPathDirectory() returns -1 if the directory does not exist,  1 is returned
1423 %  if the path represents a directory otherwise 0.
1424 %
1425 %  The format of the IsPathDirectory method is:
1426 %
1427 %      int IsPathDirectory(const char *path)
1428 %
1429 %  A description of each parameter follows.
1430 %
1431 %   o  path:  The directory path.
1432 %
1433 */
1434 static int IsPathDirectory(const char *path)
1435 {
1436   MagickBooleanType
1437     status;
1438
1439   struct stat
1440     attributes;
1441
1442   if ((path == (const char *) NULL) || (*path == '\0'))
1443     return(MagickFalse);
1444   status=GetPathAttributes(path,&attributes);
1445   if (status == MagickFalse)
1446     return(-1);
1447   if (S_ISDIR(attributes.st_mode) == 0)
1448     return(0);
1449   return(1);
1450 }
1451 \f
1452 /*
1453 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1454 %                                                                             %
1455 %                                                                             %
1456 %                                                                             %
1457 %   I s M a g i c k T r u e                                                   %
1458 %                                                                             %
1459 %                                                                             %
1460 %                                                                             %
1461 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1462 %
1463 %  IsMagickTrue() returns MagickTrue if the value is "true", "on", "yes" or
1464 %  "1".
1465 %
1466 %  The format of the IsMagickTrue method is:
1467 %
1468 %      MagickBooleanType IsMagickTrue(const char *value)
1469 %
1470 %  A description of each parameter follows:
1471 %
1472 %    o option: either MagickTrue or MagickFalse depending on the value
1473 %      parameter.
1474 %
1475 %    o value: Specifies a pointer to a character array.
1476 %
1477 */
1478 MagickExport MagickBooleanType IsMagickTrue(const char *value)
1479 {
1480   if (value == (const char *) NULL)
1481     return(MagickFalse);
1482   if (LocaleCompare(value,"true") == 0)
1483     return(MagickTrue);
1484   if (LocaleCompare(value,"on") == 0)
1485     return(MagickTrue);
1486   if (LocaleCompare(value,"yes") == 0)
1487     return(MagickTrue);
1488   if (LocaleCompare(value,"1") == 0)
1489     return(MagickTrue);
1490   return(MagickFalse);
1491 }
1492 \f
1493 /*
1494 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1495 %                                                                             %
1496 %                                                                             %
1497 %                                                                             %
1498 %   L i s t F i l e s                                                         %
1499 %                                                                             %
1500 %                                                                             %
1501 %                                                                             %
1502 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1503 %
1504 %  ListFiles() reads the directory specified and returns a list of filenames
1505 %  contained in the directory sorted in ascending alphabetic order.
1506 %
1507 %  The format of the ListFiles function is:
1508 %
1509 %      char **ListFiles(const char *directory,const char *pattern,
1510 %        long *number_entries)
1511 %
1512 %  A description of each parameter follows:
1513 %
1514 %    o filelist: Method ListFiles returns a list of filenames contained
1515 %      in the directory.  If the directory specified cannot be read or it is
1516 %      a file a NULL list is returned.
1517 %
1518 %    o directory: Specifies a pointer to a text string containing a directory
1519 %      name.
1520 %
1521 %    o pattern: Specifies a pointer to a text string containing a pattern.
1522 %
1523 %    o number_entries:  This integer returns the number of filenames in the
1524 %      list.
1525 %
1526 */
1527
1528 #if defined(__cplusplus) || defined(c_plusplus)
1529 extern "C" {
1530 #endif
1531
1532 static int FileCompare(const void *x,const void *y)
1533 {
1534   register const char
1535     **p,
1536     **q;
1537
1538   p=(const char **) x;
1539   q=(const char **) y;
1540   return(LocaleCompare(*p,*q));
1541 }
1542
1543 #if defined(__cplusplus) || defined(c_plusplus)
1544 }
1545 #endif
1546
1547 static inline int MagickReadDirectory(DIR *directory,struct dirent *entry,
1548   struct dirent **result)
1549 {
1550 #if defined(MAGICKCORE_HAVE_READDIR_R)
1551   return(readdir_r(directory,entry,result));
1552 #else
1553   (void) entry;
1554   errno=0;
1555   *result=readdir(directory);
1556   return(errno);
1557 #endif
1558 }
1559
1560 MagickExport char **ListFiles(const char *directory,const char *pattern,
1561   unsigned long *number_entries)
1562 {
1563   char
1564     **filelist;
1565
1566   DIR
1567     *current_directory;
1568
1569   struct dirent
1570     *buffer,
1571     *entry;
1572
1573   unsigned long
1574     max_entries;
1575
1576   /*
1577     Open directory.
1578   */
1579   assert(directory != (const char *) NULL);
1580   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",directory);
1581   assert(pattern != (const char *) NULL);
1582   assert(number_entries != (unsigned long *) NULL);
1583   *number_entries=0;
1584   current_directory=opendir(directory);
1585   if (current_directory == (DIR *) NULL)
1586     return((char **) NULL);
1587   /*
1588     Allocate filelist.
1589   */
1590   max_entries=2048;
1591   filelist=(char **) AcquireQuantumMemory((size_t) max_entries,
1592     sizeof(*filelist));
1593   if (filelist == (char **) NULL)
1594     {
1595       (void) closedir(current_directory);
1596       return((char **) NULL);
1597     }
1598   /*
1599     Save the current and change to the new directory.
1600   */
1601   buffer=(struct dirent *) AcquireMagickMemory(sizeof(*buffer)+FILENAME_MAX+1);
1602   if (buffer == (struct dirent *) NULL)
1603     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1604   while ((MagickReadDirectory(current_directory,buffer,&entry) == 0) &&
1605          (entry != (struct dirent *) NULL))
1606   {
1607     if (*entry->d_name == '.')
1608       continue;
1609     if ((IsPathDirectory(entry->d_name) > 0) ||
1610 #if defined(__WINDOWS__)
1611         (GlobExpression(entry->d_name,pattern,MagickTrue) != MagickFalse))
1612 #else
1613         (GlobExpression(entry->d_name,pattern,MagickFalse) != MagickFalse))
1614 #endif
1615       {
1616         if (*number_entries >= max_entries)
1617           {
1618             /*
1619               Extend the file list.
1620             */
1621             max_entries<<=1;
1622             filelist=(char **) ResizeQuantumMemory(filelist,(size_t)
1623               max_entries,sizeof(*filelist));
1624             if (filelist == (char **) NULL)
1625               break;
1626           }
1627 #if defined(vms)
1628         {
1629           register char
1630             *p;
1631
1632           p=strchr(entry->d_name,';');
1633           if (p)
1634             *p='\0';
1635           if (*number_entries > 0)
1636             if (LocaleCompare(entry->d_name,filelist[*number_entries-1]) == 0)
1637               continue;
1638         }
1639 #endif
1640         filelist[*number_entries]=(char *) AcquireString(entry->d_name);
1641         if (IsPathDirectory(entry->d_name) > 0)
1642           (void) ConcatenateMagickString(filelist[*number_entries],
1643             DirectorySeparator,MaxTextExtent);
1644         (*number_entries)++;
1645       }
1646   }
1647   buffer=(struct dirent *) RelinquishMagickMemory(buffer);
1648   (void) closedir(current_directory);
1649   if (filelist == (char **) NULL)
1650     return((char **) NULL);
1651   /*
1652     Sort filelist in ascending order.
1653   */
1654   qsort((void *) filelist,(size_t) *number_entries,sizeof(*filelist),
1655     FileCompare);
1656   return(filelist);
1657 }
1658 \f
1659 /*
1660 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1661 %                                                                             %
1662 %                                                                             %
1663 %                                                                             %
1664 %  M u l t i l i n e C e n s u s                                              %
1665 %                                                                             %
1666 %                                                                             %
1667 %                                                                             %
1668 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1669 %
1670 %  MultilineCensus() returns the number of lines within a label.  A line is
1671 %  represented by a \n character.
1672 %
1673 %  The format of the MultilineCenus method is:
1674 %
1675 %      unsigned long MultilineCensus(const char *label)
1676 %
1677 %  A description of each parameter follows.
1678 %
1679 %   o  label:  This character string is the label.
1680 %
1681 %
1682 */
1683 MagickExport unsigned long MultilineCensus(const char *label)
1684 {
1685   unsigned long
1686     number_lines;
1687
1688   /*
1689     Determine the number of lines within this label.
1690   */
1691   if (label == (char *) NULL)
1692     return(0);
1693   for (number_lines=1; *label != '\0'; label++)
1694     if (*label == '\n')
1695       number_lines++;
1696   return(number_lines);
1697 }
1698 \f
1699 /*
1700 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1701 %                                                                             %
1702 %                                                                             %
1703 %                                                                             %
1704 %   O p e n M a g i c k S t r e a m                                           %
1705 %                                                                             %
1706 %                                                                             %
1707 %                                                                             %
1708 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1709 %
1710 %  OpenMagickStream() opens the file at the specified path and return the
1711 %  associated stream.
1712 %
1713 %  The path of the OpenMagickStream method is:
1714 %
1715 %      FILE *OpenMagickStream(const char *path,const char *mode)
1716 %
1717 %  A description of each parameter follows.
1718 %
1719 %   o  path: the file path.
1720 %
1721 %   o  mode: the file mode.
1722 %
1723 */
1724 MagickExport FILE *OpenMagickStream(const char *path,const char *mode)
1725 {
1726   FILE
1727     *file;
1728
1729   if ((path == (const char *) NULL) || (mode == (const char *) NULL))
1730     {
1731       errno=EINVAL;
1732       return((FILE *) NULL);
1733     }
1734   file=(FILE *) NULL;
1735 #if defined(MAGICKCORE_HAVE__WFOPEN)
1736   {
1737     wchar_t
1738       *unicode_mode,
1739       *unicode_path;
1740
1741     unicode_path=ConvertUTF8ToUTF16(path);
1742     if (unicode_path == (wchar_t *) NULL)
1743       return((FILE *) NULL);
1744     unicode_mode=ConvertUTF8ToUTF16(mode);
1745     if (unicode_mode == (wchar_t *) NULL)
1746       {
1747         unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1748         return((FILE *) NULL);
1749       }
1750     file=_wfopen(unicode_path,unicode_mode);
1751     unicode_mode=(wchar_t *) RelinquishMagickMemory(unicode_mode);
1752     unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1753   }
1754 #endif
1755   if (file == (FILE *) NULL)
1756     file=fopen(path,mode);
1757   return(file);
1758 }
1759 \f
1760 /*
1761 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1762 %                                                                             %
1763 %                                                                             %
1764 %                                                                             %
1765 %   S y s t e m C o m m a n d                                                 %
1766 %                                                                             %
1767 %                                                                             %
1768 %                                                                             %
1769 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1770 %
1771 %  SystemCommand() executes the specified command and waits until it
1772 %  terminates.  The returned value is the exit status of the command.
1773 %
1774 %  The format of the SystemCommand method is:
1775 %
1776 %      int SystemCommand(const MagickBooleanType verbose,const char *command)
1777 %
1778 %  A description of each parameter follows:
1779 %
1780 %    o verbose: A value other than 0 prints the executed command before it is
1781 %      invoked.
1782 %
1783 %    o command: This string is the command to execute.
1784 %
1785 */
1786 MagickExport int SystemCommand(const MagickBooleanType verbose,
1787   const char *command)
1788 {
1789   int
1790     status;
1791
1792   if (verbose != MagickFalse)
1793     {
1794       (void) fprintf(stderr,"%s\n",command);
1795       (void) fflush(stderr);
1796     }
1797   status=(-1);
1798 #if defined(MAGICKCORE_POSIX_SUPPORT)
1799 #if !defined(MAGICKCORE_HAVE_EXECVP)
1800   status=system(command);
1801 #else
1802   if (strspn(command,"&;<>|") == 0)
1803     status=system(command);
1804   else
1805     {
1806       char
1807         **arguments;
1808
1809       int
1810         number_arguments;
1811
1812       arguments=StringToArgv(command,&number_arguments);
1813       if (arguments == (char **) NULL)
1814         status=system(command);
1815       else
1816         {
1817           pid_t
1818             child_pid;
1819
1820           register long
1821             i;
1822
1823           /*
1824             Call application directly rather than from a shell.
1825           */
1826           child_pid=fork();
1827           if (child_pid == (pid_t) -1)
1828             status=system(command);
1829           else
1830             if (child_pid == 0)
1831               {
1832                 status=execvp(arguments[1],arguments+1);
1833                 _exit(1);
1834               }
1835             else
1836               {
1837                 int
1838                   child_status;
1839
1840                 pid_t
1841                   pid;
1842
1843                 child_status=0;
1844                 pid=waitpid(child_pid,&child_status,0);
1845                 if (pid == -1)
1846                   status=(-1);
1847                 else
1848                   {
1849                     if (WIFEXITED(child_status) != 0)
1850                       status=WEXITSTATUS(child_status);
1851                     else
1852                       if (WIFSIGNALED(child_status))
1853                         status=(-1);
1854                   }
1855               }
1856           for (i=0; i < number_arguments; i++)
1857             arguments[i]=DestroyString(arguments[i]);
1858           arguments=(char **) RelinquishMagickMemory(arguments);
1859         }
1860     }
1861 #endif
1862 #elif defined(__WINDOWS__)
1863   status=NTSystemCommand(command);
1864 #elif defined(macintosh)
1865   status=MACSystemCommand(command);
1866 #elif defined(vms)
1867   status=system(command);
1868 #else
1869 #  error No suitable system() method.
1870 #endif
1871   if (status < 0)
1872     {
1873       char
1874         *message;
1875
1876       ExceptionInfo
1877         *exception;
1878
1879       exception=AcquireExceptionInfo();
1880       message=GetExceptionMessage(errno);
1881       (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
1882         "`%s': %s",command,message);
1883       message=DestroyString(message);
1884       CatchException(exception);
1885       exception=DestroyExceptionInfo(exception);
1886     }
1887   return(status);
1888 }